babylon.viewer.max.js 4.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610
  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 = 17);
  77. /******/ })
  78. /************************************************************************/
  79. /******/ ([
  80. /* 0 */
  81. /***/ (function(module, exports, __webpack_require__) {
  82. /* WEBPACK VAR INJECTION */(function(global) {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};
  83. 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)}}();
  84. (function universalModuleDefinition(root, factory) {
  85. var amdDependencies = [];
  86. var CANNON = root.CANNON;
  87. var OIMO = root.OIMO;
  88. var earcut = root.earcut;
  89. if(true) {
  90. try { CANNON = CANNON || __webpack_require__(20); } catch(e) {}
  91. try { OIMO = OIMO || __webpack_require__(21); } catch(e) {}
  92. try { earcut = earcut || __webpack_require__(22); } catch(e) {}
  93. module.exports = factory(CANNON,OIMO,earcut);
  94. } else if(typeof define === 'function' && define.amd) {
  95. if(require.specified && require.specified("cannon")) amdDependencies.push("cannon");
  96. if(require.specified && require.specified("oimo")) amdDependencies.push("oimo");
  97. if(require.specified && require.specified("earcut")) amdDependencies.push("earcut");
  98. define("babylonjs", amdDependencies, factory);
  99. } else if(typeof exports === 'object') {
  100. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  101. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  102. try { earcut = earcut || require("earcut"); } catch(e) {}
  103. exports["babylonjs"] = factory(CANNON,OIMO,earcut);
  104. } else {
  105. root["BABYLON"] = factory(CANNON,OIMO,earcut);
  106. }
  107. })(this, function(CANNON,OIMO,earcut) {
  108. CANNON = CANNON || this.CANNON;
  109. OIMO = OIMO || this.OIMO;
  110. earcut = earcut || this.earcut;
  111. "use strict";
  112. var BABYLON;
  113. (function (BABYLON) {
  114. /**
  115. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  116. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  117. */
  118. var EffectFallbacks = /** @class */ (function () {
  119. function EffectFallbacks() {
  120. this._defines = {};
  121. this._currentRank = 32;
  122. this._maxRank = -1;
  123. }
  124. /**
  125. * Removes the fallback from the bound mesh.
  126. */
  127. EffectFallbacks.prototype.unBindMesh = function () {
  128. this._mesh = null;
  129. };
  130. /**
  131. * Adds a fallback on the specified property.
  132. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  133. * @param define The name of the define in the shader
  134. */
  135. EffectFallbacks.prototype.addFallback = function (rank, define) {
  136. if (!this._defines[rank]) {
  137. if (rank < this._currentRank) {
  138. this._currentRank = rank;
  139. }
  140. if (rank > this._maxRank) {
  141. this._maxRank = rank;
  142. }
  143. this._defines[rank] = new Array();
  144. }
  145. this._defines[rank].push(define);
  146. };
  147. /**
  148. * Sets the mesh to use CPU skinning when needing to fallback.
  149. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  150. * @param mesh The mesh to use the fallbacks.
  151. */
  152. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  153. this._mesh = mesh;
  154. if (rank < this._currentRank) {
  155. this._currentRank = rank;
  156. }
  157. if (rank > this._maxRank) {
  158. this._maxRank = rank;
  159. }
  160. };
  161. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  162. /**
  163. * Checks to see if more fallbacks are still availible.
  164. */
  165. get: function () {
  166. return this._currentRank <= this._maxRank;
  167. },
  168. enumerable: true,
  169. configurable: true
  170. });
  171. /**
  172. * Removes the defines that shoould be removed when falling back.
  173. * @param currentDefines defines the current define statements for the shader.
  174. * @param effect defines the current effect we try to compile
  175. * @returns The resulting defines with defines of the current rank removed.
  176. */
  177. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  178. // First we try to switch to CPU skinning
  179. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  180. this._mesh.computeBonesUsingShaders = false;
  181. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  182. var scene = this._mesh.getScene();
  183. for (var index = 0; index < scene.meshes.length; index++) {
  184. var otherMesh = scene.meshes[index];
  185. if (!otherMesh.material) {
  186. continue;
  187. }
  188. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  189. continue;
  190. }
  191. if (otherMesh.material.getEffect() === effect) {
  192. otherMesh.computeBonesUsingShaders = false;
  193. }
  194. else {
  195. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  196. var subMesh = _a[_i];
  197. var subMeshEffect = subMesh.effect;
  198. if (subMeshEffect === effect) {
  199. otherMesh.computeBonesUsingShaders = false;
  200. break;
  201. }
  202. }
  203. }
  204. }
  205. }
  206. else {
  207. var currentFallbacks = this._defines[this._currentRank];
  208. if (currentFallbacks) {
  209. for (var index = 0; index < currentFallbacks.length; index++) {
  210. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  211. }
  212. }
  213. this._currentRank++;
  214. }
  215. return currentDefines;
  216. };
  217. return EffectFallbacks;
  218. }());
  219. BABYLON.EffectFallbacks = EffectFallbacks;
  220. /**
  221. * Options to be used when creating an effect.
  222. */
  223. var EffectCreationOptions = /** @class */ (function () {
  224. function EffectCreationOptions() {
  225. }
  226. return EffectCreationOptions;
  227. }());
  228. BABYLON.EffectCreationOptions = EffectCreationOptions;
  229. /**
  230. * Effect containing vertex and fragment shader that can be executed on an object.
  231. */
  232. var Effect = /** @class */ (function () {
  233. /**
  234. * Instantiates an effect.
  235. * An effect can be used to create/manage/execute vertex and fragment shaders.
  236. * @param baseName Name of the effect.
  237. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  238. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  239. * @param samplers List of sampler variables that will be passed to the shader.
  240. * @param engine Engine to be used to render the effect
  241. * @param defines Define statements to be added to the shader.
  242. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  243. * @param onCompiled Callback that will be called when the shader is compiled.
  244. * @param onError Callback that will be called if an error occurs during shader compilation.
  245. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  246. */
  247. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  248. if (samplers === void 0) { samplers = null; }
  249. if (defines === void 0) { defines = null; }
  250. if (fallbacks === void 0) { fallbacks = null; }
  251. if (onCompiled === void 0) { onCompiled = null; }
  252. if (onError === void 0) { onError = null; }
  253. var _this = this;
  254. /**
  255. * Unique ID of the effect.
  256. */
  257. this.uniqueId = 0;
  258. /**
  259. * Observable that will be called when the shader is compiled.
  260. */
  261. this.onCompileObservable = new BABYLON.Observable();
  262. /**
  263. * Observable that will be called if an error occurs during shader compilation.
  264. */
  265. this.onErrorObservable = new BABYLON.Observable();
  266. /**
  267. * Observable that will be called when effect is bound.
  268. */
  269. this.onBindObservable = new BABYLON.Observable();
  270. this._uniformBuffersNames = {};
  271. this._isReady = false;
  272. this._compilationError = "";
  273. this.name = baseName;
  274. if (attributesNamesOrOptions.attributes) {
  275. var options = attributesNamesOrOptions;
  276. this._engine = uniformsNamesOrEngine;
  277. this._attributesNames = options.attributes;
  278. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  279. this._samplers = options.samplers.slice();
  280. this.defines = options.defines;
  281. this.onError = options.onError;
  282. this.onCompiled = options.onCompiled;
  283. this._fallbacks = options.fallbacks;
  284. this._indexParameters = options.indexParameters;
  285. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  286. if (options.uniformBuffersNames) {
  287. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  288. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  289. }
  290. }
  291. }
  292. else {
  293. this._engine = engine;
  294. this.defines = defines;
  295. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  296. this._samplers = samplers ? samplers.slice() : [];
  297. this._attributesNames = attributesNamesOrOptions;
  298. this.onError = onError;
  299. this.onCompiled = onCompiled;
  300. this._indexParameters = indexParameters;
  301. this._fallbacks = fallbacks;
  302. }
  303. this.uniqueId = Effect._uniqueIdSeed++;
  304. var vertexSource;
  305. var fragmentSource;
  306. if (baseName.vertexElement) {
  307. vertexSource = document.getElementById(baseName.vertexElement);
  308. if (!vertexSource) {
  309. vertexSource = baseName.vertexElement;
  310. }
  311. }
  312. else {
  313. vertexSource = baseName.vertex || baseName;
  314. }
  315. if (baseName.fragmentElement) {
  316. fragmentSource = document.getElementById(baseName.fragmentElement);
  317. if (!fragmentSource) {
  318. fragmentSource = baseName.fragmentElement;
  319. }
  320. }
  321. else {
  322. fragmentSource = baseName.fragment || baseName;
  323. }
  324. this._loadVertexShader(vertexSource, function (vertexCode) {
  325. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  326. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  327. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  328. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  329. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  330. if (baseName) {
  331. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  332. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  333. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  334. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  335. }
  336. else {
  337. _this._vertexSourceCode = migratedVertexCode;
  338. _this._fragmentSourceCode = migratedFragmentCode;
  339. }
  340. _this._prepareEffect();
  341. });
  342. });
  343. });
  344. });
  345. });
  346. });
  347. }
  348. Object.defineProperty(Effect.prototype, "key", {
  349. /**
  350. * Unique key for this effect
  351. */
  352. get: function () {
  353. return this._key;
  354. },
  355. enumerable: true,
  356. configurable: true
  357. });
  358. /**
  359. * If the effect has been compiled and prepared.
  360. * @returns if the effect is compiled and prepared.
  361. */
  362. Effect.prototype.isReady = function () {
  363. return this._isReady;
  364. };
  365. /**
  366. * The engine the effect was initialized with.
  367. * @returns the engine.
  368. */
  369. Effect.prototype.getEngine = function () {
  370. return this._engine;
  371. };
  372. /**
  373. * The compiled webGL program for the effect
  374. * @returns the webGL program.
  375. */
  376. Effect.prototype.getProgram = function () {
  377. return this._program;
  378. };
  379. /**
  380. * The set of names of attribute variables for the shader.
  381. * @returns An array of attribute names.
  382. */
  383. Effect.prototype.getAttributesNames = function () {
  384. return this._attributesNames;
  385. };
  386. /**
  387. * Returns the attribute at the given index.
  388. * @param index The index of the attribute.
  389. * @returns The location of the attribute.
  390. */
  391. Effect.prototype.getAttributeLocation = function (index) {
  392. return this._attributes[index];
  393. };
  394. /**
  395. * Returns the attribute based on the name of the variable.
  396. * @param name of the attribute to look up.
  397. * @returns the attribute location.
  398. */
  399. Effect.prototype.getAttributeLocationByName = function (name) {
  400. var index = this._attributesNames.indexOf(name);
  401. return this._attributes[index];
  402. };
  403. /**
  404. * The number of attributes.
  405. * @returns the numnber of attributes.
  406. */
  407. Effect.prototype.getAttributesCount = function () {
  408. return this._attributes.length;
  409. };
  410. /**
  411. * Gets the index of a uniform variable.
  412. * @param uniformName of the uniform to look up.
  413. * @returns the index.
  414. */
  415. Effect.prototype.getUniformIndex = function (uniformName) {
  416. return this._uniformsNames.indexOf(uniformName);
  417. };
  418. /**
  419. * Returns the attribute based on the name of the variable.
  420. * @param uniformName of the uniform to look up.
  421. * @returns the location of the uniform.
  422. */
  423. Effect.prototype.getUniform = function (uniformName) {
  424. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  425. };
  426. /**
  427. * Returns an array of sampler variable names
  428. * @returns The array of sampler variable neames.
  429. */
  430. Effect.prototype.getSamplers = function () {
  431. return this._samplers;
  432. };
  433. /**
  434. * The error from the last compilation.
  435. * @returns the error string.
  436. */
  437. Effect.prototype.getCompilationError = function () {
  438. return this._compilationError;
  439. };
  440. /**
  441. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  442. * @param func The callback to be used.
  443. */
  444. Effect.prototype.executeWhenCompiled = function (func) {
  445. if (this.isReady()) {
  446. func(this);
  447. return;
  448. }
  449. this.onCompileObservable.add(function (effect) {
  450. func(effect);
  451. });
  452. };
  453. /** @ignore */
  454. Effect.prototype._loadVertexShader = function (vertex, callback) {
  455. if (BABYLON.Tools.IsWindowObjectExist()) {
  456. // DOM element ?
  457. if (vertex instanceof HTMLElement) {
  458. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  459. callback(vertexCode);
  460. return;
  461. }
  462. }
  463. // Base64 encoded ?
  464. if (vertex.substr(0, 7) === "base64:") {
  465. var vertexBinary = window.atob(vertex.substr(7));
  466. callback(vertexBinary);
  467. return;
  468. }
  469. // Is in local store ?
  470. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  471. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  472. return;
  473. }
  474. var vertexShaderUrl;
  475. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  476. vertexShaderUrl = vertex;
  477. }
  478. else {
  479. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  480. }
  481. // Vertex shader
  482. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  483. };
  484. /** @ignore */
  485. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  486. if (BABYLON.Tools.IsWindowObjectExist()) {
  487. // DOM element ?
  488. if (fragment instanceof HTMLElement) {
  489. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  490. callback(fragmentCode);
  491. return;
  492. }
  493. }
  494. // Base64 encoded ?
  495. if (fragment.substr(0, 7) === "base64:") {
  496. var fragmentBinary = window.atob(fragment.substr(7));
  497. callback(fragmentBinary);
  498. return;
  499. }
  500. // Is in local store ?
  501. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  502. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  503. return;
  504. }
  505. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  506. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  507. return;
  508. }
  509. var fragmentShaderUrl;
  510. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  511. fragmentShaderUrl = fragment;
  512. }
  513. else {
  514. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  515. }
  516. // Fragment shader
  517. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  518. };
  519. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  520. // Rebuild shaders source code
  521. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  522. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  523. vertexCode = prefix + vertexCode;
  524. fragmentCode = prefix + fragmentCode;
  525. // Number lines of shaders source code
  526. var i = 2;
  527. var regex = /\n/gm;
  528. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  529. i = 2;
  530. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  531. // Dump shaders name and formatted source code
  532. if (this.name.vertexElement) {
  533. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  534. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  535. }
  536. else if (this.name.vertex) {
  537. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  538. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  539. }
  540. else {
  541. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  542. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  543. }
  544. };
  545. ;
  546. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  547. var preparedSourceCode = this._processPrecision(sourceCode);
  548. if (this._engine.webGLVersion == 1) {
  549. callback(preparedSourceCode);
  550. return;
  551. }
  552. // Already converted
  553. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  554. callback(preparedSourceCode.replace("#version 300 es", ""));
  555. return;
  556. }
  557. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  558. // Remove extensions
  559. // #extension GL_OES_standard_derivatives : enable
  560. // #extension GL_EXT_shader_texture_lod : enable
  561. // #extension GL_EXT_frag_depth : enable
  562. // #extension GL_EXT_draw_buffers : require
  563. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  564. var result = preparedSourceCode.replace(regex, "");
  565. // Migrate to GLSL v300
  566. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  567. result = result.replace(/attribute[ \t]/g, "in ");
  568. result = result.replace(/[ \t]attribute/g, " in");
  569. if (isFragment) {
  570. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  571. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  572. result = result.replace(/texture2D\s*\(/g, "texture(");
  573. result = result.replace(/textureCube\s*\(/g, "texture(");
  574. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  575. result = result.replace(/gl_FragColor/g, "glFragColor");
  576. result = result.replace(/gl_FragData/g, "glFragData");
  577. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  578. }
  579. callback(result);
  580. };
  581. Effect.prototype._processIncludes = function (sourceCode, callback) {
  582. var _this = this;
  583. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  584. var match = regex.exec(sourceCode);
  585. var returnValue = new String(sourceCode);
  586. while (match != null) {
  587. var includeFile = match[1];
  588. // Uniform declaration
  589. if (includeFile.indexOf("__decl__") !== -1) {
  590. includeFile = includeFile.replace(/__decl__/, "");
  591. if (this._engine.supportsUniformBuffers) {
  592. includeFile = includeFile.replace(/Vertex/, "Ubo");
  593. includeFile = includeFile.replace(/Fragment/, "Ubo");
  594. }
  595. includeFile = includeFile + "Declaration";
  596. }
  597. if (Effect.IncludesShadersStore[includeFile]) {
  598. // Substitution
  599. var includeContent = Effect.IncludesShadersStore[includeFile];
  600. if (match[2]) {
  601. var splits = match[3].split(",");
  602. for (var index = 0; index < splits.length; index += 2) {
  603. var source = new RegExp(splits[index], "g");
  604. var dest = splits[index + 1];
  605. includeContent = includeContent.replace(source, dest);
  606. }
  607. }
  608. if (match[4]) {
  609. var indexString = match[5];
  610. if (indexString.indexOf("..") !== -1) {
  611. var indexSplits = indexString.split("..");
  612. var minIndex = parseInt(indexSplits[0]);
  613. var maxIndex = parseInt(indexSplits[1]);
  614. var sourceIncludeContent = includeContent.slice(0);
  615. includeContent = "";
  616. if (isNaN(maxIndex)) {
  617. maxIndex = this._indexParameters[indexSplits[1]];
  618. }
  619. for (var i = minIndex; i < maxIndex; i++) {
  620. if (!this._engine.supportsUniformBuffers) {
  621. // Ubo replacement
  622. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  623. return p1 + "{X}";
  624. });
  625. }
  626. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  627. }
  628. }
  629. else {
  630. if (!this._engine.supportsUniformBuffers) {
  631. // Ubo replacement
  632. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  633. return p1 + "{X}";
  634. });
  635. }
  636. includeContent = includeContent.replace(/\{X\}/g, indexString);
  637. }
  638. }
  639. // Replace
  640. returnValue = returnValue.replace(match[0], includeContent);
  641. }
  642. else {
  643. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  644. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  645. Effect.IncludesShadersStore[includeFile] = fileContent;
  646. _this._processIncludes(returnValue, callback);
  647. });
  648. return;
  649. }
  650. match = regex.exec(sourceCode);
  651. }
  652. callback(returnValue);
  653. };
  654. Effect.prototype._processPrecision = function (source) {
  655. if (source.indexOf("precision highp float") === -1) {
  656. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  657. source = "precision mediump float;\n" + source;
  658. }
  659. else {
  660. source = "precision highp float;\n" + source;
  661. }
  662. }
  663. else {
  664. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  665. source = source.replace("precision highp float", "precision mediump float");
  666. }
  667. }
  668. return source;
  669. };
  670. /**
  671. * Recompiles the webGL program
  672. * @param vertexSourceCode The source code for the vertex shader.
  673. * @param fragmentSourceCode The source code for the fragment shader.
  674. * @param onCompiled Callback called when completed.
  675. * @param onError Callback called on error.
  676. */
  677. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  678. var _this = this;
  679. this._isReady = false;
  680. this._vertexSourceCodeOverride = vertexSourceCode;
  681. this._fragmentSourceCodeOverride = fragmentSourceCode;
  682. this.onError = function (effect, error) {
  683. if (onError) {
  684. onError(error);
  685. }
  686. };
  687. this.onCompiled = function () {
  688. var scenes = _this.getEngine().scenes;
  689. for (var i = 0; i < scenes.length; i++) {
  690. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  691. }
  692. if (onCompiled) {
  693. onCompiled(_this._program);
  694. }
  695. };
  696. this._fallbacks = null;
  697. this._prepareEffect();
  698. };
  699. /**
  700. * Gets the uniform locations of the the specified variable names
  701. * @param names THe names of the variables to lookup.
  702. * @returns Array of locations in the same order as variable names.
  703. */
  704. Effect.prototype.getSpecificUniformLocations = function (names) {
  705. var engine = this._engine;
  706. return engine.getUniforms(this._program, names);
  707. };
  708. /**
  709. * Prepares the effect
  710. */
  711. Effect.prototype._prepareEffect = function () {
  712. var attributesNames = this._attributesNames;
  713. var defines = this.defines;
  714. var fallbacks = this._fallbacks;
  715. this._valueCache = {};
  716. var previousProgram = this._program;
  717. try {
  718. var engine = this._engine;
  719. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  720. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  721. }
  722. else {
  723. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  724. }
  725. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  726. if (engine.supportsUniformBuffers) {
  727. for (var name in this._uniformBuffersNames) {
  728. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  729. }
  730. }
  731. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  732. this._attributes = engine.getAttributes(this._program, attributesNames);
  733. var index;
  734. for (index = 0; index < this._samplers.length; index++) {
  735. var sampler = this.getUniform(this._samplers[index]);
  736. if (sampler == null) {
  737. this._samplers.splice(index, 1);
  738. index--;
  739. }
  740. }
  741. engine.bindSamplers(this);
  742. this._compilationError = "";
  743. this._isReady = true;
  744. if (this.onCompiled) {
  745. this.onCompiled(this);
  746. }
  747. this.onCompileObservable.notifyObservers(this);
  748. this.onCompileObservable.clear();
  749. // Unbind mesh reference in fallbacks
  750. if (this._fallbacks) {
  751. this._fallbacks.unBindMesh();
  752. }
  753. if (previousProgram) {
  754. this.getEngine()._deleteProgram(previousProgram);
  755. }
  756. }
  757. catch (e) {
  758. this._compilationError = e.message;
  759. // Let's go through fallbacks then
  760. BABYLON.Tools.Error("Unable to compile effect:");
  761. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  762. return " " + uniform;
  763. }));
  764. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  765. return " " + attribute;
  766. }));
  767. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  768. BABYLON.Tools.Error("Error: " + this._compilationError);
  769. if (previousProgram) {
  770. this._program = previousProgram;
  771. this._isReady = true;
  772. if (this.onError) {
  773. this.onError(this, this._compilationError);
  774. }
  775. this.onErrorObservable.notifyObservers(this);
  776. }
  777. if (fallbacks && fallbacks.isMoreFallbacks) {
  778. BABYLON.Tools.Error("Trying next fallback.");
  779. this.defines = fallbacks.reduce(this.defines, this);
  780. this._prepareEffect();
  781. }
  782. else {
  783. if (this.onError) {
  784. this.onError(this, this._compilationError);
  785. }
  786. this.onErrorObservable.notifyObservers(this);
  787. this.onErrorObservable.clear();
  788. // Unbind mesh reference in fallbacks
  789. if (this._fallbacks) {
  790. this._fallbacks.unBindMesh();
  791. }
  792. }
  793. }
  794. };
  795. Object.defineProperty(Effect.prototype, "isSupported", {
  796. /**
  797. * Checks if the effect is supported. (Must be called after compilation)
  798. */
  799. get: function () {
  800. return this._compilationError === "";
  801. },
  802. enumerable: true,
  803. configurable: true
  804. });
  805. /**
  806. * Binds a texture to the engine to be used as output of the shader.
  807. * @param channel Name of the output variable.
  808. * @param texture Texture to bind.
  809. */
  810. Effect.prototype._bindTexture = function (channel, texture) {
  811. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  812. };
  813. /**
  814. * Sets a texture on the engine to be used in the shader.
  815. * @param channel Name of the sampler variable.
  816. * @param texture Texture to set.
  817. */
  818. Effect.prototype.setTexture = function (channel, texture) {
  819. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  820. };
  821. /**
  822. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  823. * @param channel Name of the sampler variable.
  824. * @param texture Texture to set.
  825. */
  826. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  827. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  828. };
  829. /**
  830. * Sets an array of textures on the engine to be used in the shader.
  831. * @param channel Name of the variable.
  832. * @param textures Textures to set.
  833. */
  834. Effect.prototype.setTextureArray = function (channel, textures) {
  835. if (this._samplers.indexOf(channel + "Ex") === -1) {
  836. var initialPos = this._samplers.indexOf(channel);
  837. for (var index = 1; index < textures.length; index++) {
  838. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  839. }
  840. }
  841. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  842. };
  843. /**
  844. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  845. * @param channel Name of the sampler variable.
  846. * @param postProcess Post process to get the input texture from.
  847. */
  848. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  849. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  850. };
  851. /**
  852. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  853. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  854. * @param channel Name of the sampler variable.
  855. * @param postProcess Post process to get the output texture from.
  856. */
  857. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  858. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  859. };
  860. /** @ignore */
  861. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  862. var cache = this._valueCache[uniformName];
  863. var flag = matrix.updateFlag;
  864. if (cache !== undefined && cache === flag) {
  865. return false;
  866. }
  867. this._valueCache[uniformName] = flag;
  868. return true;
  869. };
  870. /** @ignore */
  871. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  872. var cache = this._valueCache[uniformName];
  873. if (!cache) {
  874. cache = [x, y];
  875. this._valueCache[uniformName] = cache;
  876. return true;
  877. }
  878. var changed = false;
  879. if (cache[0] !== x) {
  880. cache[0] = x;
  881. changed = true;
  882. }
  883. if (cache[1] !== y) {
  884. cache[1] = y;
  885. changed = true;
  886. }
  887. return changed;
  888. };
  889. /** @ignore */
  890. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  891. var cache = this._valueCache[uniformName];
  892. if (!cache) {
  893. cache = [x, y, z];
  894. this._valueCache[uniformName] = cache;
  895. return true;
  896. }
  897. var changed = false;
  898. if (cache[0] !== x) {
  899. cache[0] = x;
  900. changed = true;
  901. }
  902. if (cache[1] !== y) {
  903. cache[1] = y;
  904. changed = true;
  905. }
  906. if (cache[2] !== z) {
  907. cache[2] = z;
  908. changed = true;
  909. }
  910. return changed;
  911. };
  912. /** @ignore */
  913. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  914. var cache = this._valueCache[uniformName];
  915. if (!cache) {
  916. cache = [x, y, z, w];
  917. this._valueCache[uniformName] = cache;
  918. return true;
  919. }
  920. var changed = false;
  921. if (cache[0] !== x) {
  922. cache[0] = x;
  923. changed = true;
  924. }
  925. if (cache[1] !== y) {
  926. cache[1] = y;
  927. changed = true;
  928. }
  929. if (cache[2] !== z) {
  930. cache[2] = z;
  931. changed = true;
  932. }
  933. if (cache[3] !== w) {
  934. cache[3] = w;
  935. changed = true;
  936. }
  937. return changed;
  938. };
  939. /**
  940. * Binds a buffer to a uniform.
  941. * @param buffer Buffer to bind.
  942. * @param name Name of the uniform variable to bind to.
  943. */
  944. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  945. var bufferName = this._uniformBuffersNames[name];
  946. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  947. return;
  948. }
  949. Effect._baseCache[bufferName] = buffer;
  950. this._engine.bindUniformBufferBase(buffer, bufferName);
  951. };
  952. /**
  953. * Binds block to a uniform.
  954. * @param blockName Name of the block to bind.
  955. * @param index Index to bind.
  956. */
  957. Effect.prototype.bindUniformBlock = function (blockName, index) {
  958. this._engine.bindUniformBlock(this._program, blockName, index);
  959. };
  960. /**
  961. * Sets an interger value on a uniform variable.
  962. * @param uniformName Name of the variable.
  963. * @param value Value to be set.
  964. * @returns this effect.
  965. */
  966. Effect.prototype.setInt = function (uniformName, value) {
  967. var cache = this._valueCache[uniformName];
  968. if (cache !== undefined && cache === value)
  969. return this;
  970. this._valueCache[uniformName] = value;
  971. this._engine.setInt(this.getUniform(uniformName), value);
  972. return this;
  973. };
  974. /**
  975. * Sets an int array on a uniform variable.
  976. * @param uniformName Name of the variable.
  977. * @param array array to be set.
  978. * @returns this effect.
  979. */
  980. Effect.prototype.setIntArray = function (uniformName, array) {
  981. this._valueCache[uniformName] = null;
  982. this._engine.setIntArray(this.getUniform(uniformName), array);
  983. return this;
  984. };
  985. /**
  986. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  987. * @param uniformName Name of the variable.
  988. * @param array array to be set.
  989. * @returns this effect.
  990. */
  991. Effect.prototype.setIntArray2 = function (uniformName, array) {
  992. this._valueCache[uniformName] = null;
  993. this._engine.setIntArray2(this.getUniform(uniformName), array);
  994. return this;
  995. };
  996. /**
  997. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  998. * @param uniformName Name of the variable.
  999. * @param array array to be set.
  1000. * @returns this effect.
  1001. */
  1002. Effect.prototype.setIntArray3 = function (uniformName, array) {
  1003. this._valueCache[uniformName] = null;
  1004. this._engine.setIntArray3(this.getUniform(uniformName), array);
  1005. return this;
  1006. };
  1007. /**
  1008. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1009. * @param uniformName Name of the variable.
  1010. * @param array array to be set.
  1011. * @returns this effect.
  1012. */
  1013. Effect.prototype.setIntArray4 = function (uniformName, array) {
  1014. this._valueCache[uniformName] = null;
  1015. this._engine.setIntArray4(this.getUniform(uniformName), array);
  1016. return this;
  1017. };
  1018. /**
  1019. * Sets an float array on a uniform variable.
  1020. * @param uniformName Name of the variable.
  1021. * @param array array to be set.
  1022. * @returns this effect.
  1023. */
  1024. Effect.prototype.setFloatArray = function (uniformName, array) {
  1025. this._valueCache[uniformName] = null;
  1026. this._engine.setFloatArray(this.getUniform(uniformName), array);
  1027. return this;
  1028. };
  1029. /**
  1030. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1031. * @param uniformName Name of the variable.
  1032. * @param array array to be set.
  1033. * @returns this effect.
  1034. */
  1035. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  1036. this._valueCache[uniformName] = null;
  1037. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  1038. return this;
  1039. };
  1040. /**
  1041. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1042. * @param uniformName Name of the variable.
  1043. * @param array array to be set.
  1044. * @returns this effect.
  1045. */
  1046. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  1047. this._valueCache[uniformName] = null;
  1048. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  1049. return this;
  1050. };
  1051. /**
  1052. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1053. * @param uniformName Name of the variable.
  1054. * @param array array to be set.
  1055. * @returns this effect.
  1056. */
  1057. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  1058. this._valueCache[uniformName] = null;
  1059. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  1060. return this;
  1061. };
  1062. /**
  1063. * Sets an array on a uniform variable.
  1064. * @param uniformName Name of the variable.
  1065. * @param array array to be set.
  1066. * @returns this effect.
  1067. */
  1068. Effect.prototype.setArray = function (uniformName, array) {
  1069. this._valueCache[uniformName] = null;
  1070. this._engine.setArray(this.getUniform(uniformName), array);
  1071. return this;
  1072. };
  1073. /**
  1074. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1075. * @param uniformName Name of the variable.
  1076. * @param array array to be set.
  1077. * @returns this effect.
  1078. */
  1079. Effect.prototype.setArray2 = function (uniformName, array) {
  1080. this._valueCache[uniformName] = null;
  1081. this._engine.setArray2(this.getUniform(uniformName), array);
  1082. return this;
  1083. };
  1084. /**
  1085. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1086. * @param uniformName Name of the variable.
  1087. * @param array array to be set.
  1088. * @returns this effect.
  1089. */
  1090. Effect.prototype.setArray3 = function (uniformName, array) {
  1091. this._valueCache[uniformName] = null;
  1092. this._engine.setArray3(this.getUniform(uniformName), array);
  1093. return this;
  1094. };
  1095. /**
  1096. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1097. * @param uniformName Name of the variable.
  1098. * @param array array to be set.
  1099. * @returns this effect.
  1100. */
  1101. Effect.prototype.setArray4 = function (uniformName, array) {
  1102. this._valueCache[uniformName] = null;
  1103. this._engine.setArray4(this.getUniform(uniformName), array);
  1104. return this;
  1105. };
  1106. /**
  1107. * Sets matrices on a uniform variable.
  1108. * @param uniformName Name of the variable.
  1109. * @param matrices matrices to be set.
  1110. * @returns this effect.
  1111. */
  1112. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1113. if (!matrices) {
  1114. return this;
  1115. }
  1116. this._valueCache[uniformName] = null;
  1117. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1118. return this;
  1119. };
  1120. /**
  1121. * Sets matrix on a uniform variable.
  1122. * @param uniformName Name of the variable.
  1123. * @param matrix matrix to be set.
  1124. * @returns this effect.
  1125. */
  1126. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1127. if (this._cacheMatrix(uniformName, matrix)) {
  1128. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1129. }
  1130. return this;
  1131. };
  1132. /**
  1133. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1134. * @param uniformName Name of the variable.
  1135. * @param matrix matrix to be set.
  1136. * @returns this effect.
  1137. */
  1138. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1139. this._valueCache[uniformName] = null;
  1140. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1141. return this;
  1142. };
  1143. /**
  1144. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1145. * @param uniformName Name of the variable.
  1146. * @param matrix matrix to be set.
  1147. * @returns this effect.
  1148. */
  1149. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1150. this._valueCache[uniformName] = null;
  1151. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1152. return this;
  1153. };
  1154. /**
  1155. * Sets a float on a uniform variable.
  1156. * @param uniformName Name of the variable.
  1157. * @param value value to be set.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setFloat = function (uniformName, value) {
  1161. var cache = this._valueCache[uniformName];
  1162. if (cache !== undefined && cache === value)
  1163. return this;
  1164. this._valueCache[uniformName] = value;
  1165. this._engine.setFloat(this.getUniform(uniformName), value);
  1166. return this;
  1167. };
  1168. /**
  1169. * Sets a boolean on a uniform variable.
  1170. * @param uniformName Name of the variable.
  1171. * @param bool value to be set.
  1172. * @returns this effect.
  1173. */
  1174. Effect.prototype.setBool = function (uniformName, bool) {
  1175. var cache = this._valueCache[uniformName];
  1176. if (cache !== undefined && cache === bool)
  1177. return this;
  1178. this._valueCache[uniformName] = bool;
  1179. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1180. return this;
  1181. };
  1182. /**
  1183. * Sets a Vector2 on a uniform variable.
  1184. * @param uniformName Name of the variable.
  1185. * @param vector2 vector2 to be set.
  1186. * @returns this effect.
  1187. */
  1188. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1189. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1190. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1191. }
  1192. return this;
  1193. };
  1194. /**
  1195. * Sets a float2 on a uniform variable.
  1196. * @param uniformName Name of the variable.
  1197. * @param x First float in float2.
  1198. * @param y Second float in float2.
  1199. * @returns this effect.
  1200. */
  1201. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1202. if (this._cacheFloat2(uniformName, x, y)) {
  1203. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1204. }
  1205. return this;
  1206. };
  1207. /**
  1208. * Sets a Vector3 on a uniform variable.
  1209. * @param uniformName Name of the variable.
  1210. * @param vector3 Value to be set.
  1211. * @returns this effect.
  1212. */
  1213. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1214. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1215. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1216. }
  1217. return this;
  1218. };
  1219. /**
  1220. * Sets a float3 on a uniform variable.
  1221. * @param uniformName Name of the variable.
  1222. * @param x First float in float3.
  1223. * @param y Second float in float3.
  1224. * @param z Third float in float3.
  1225. * @returns this effect.
  1226. */
  1227. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1228. if (this._cacheFloat3(uniformName, x, y, z)) {
  1229. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1230. }
  1231. return this;
  1232. };
  1233. /**
  1234. * Sets a Vector4 on a uniform variable.
  1235. * @param uniformName Name of the variable.
  1236. * @param vector4 Value to be set.
  1237. * @returns this effect.
  1238. */
  1239. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1240. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1241. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1242. }
  1243. return this;
  1244. };
  1245. /**
  1246. * Sets a float4 on a uniform variable.
  1247. * @param uniformName Name of the variable.
  1248. * @param x First float in float4.
  1249. * @param y Second float in float4.
  1250. * @param z Third float in float4.
  1251. * @param w Fourth float in float4.
  1252. * @returns this effect.
  1253. */
  1254. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1255. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1256. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1257. }
  1258. return this;
  1259. };
  1260. /**
  1261. * Sets a Color3 on a uniform variable.
  1262. * @param uniformName Name of the variable.
  1263. * @param color3 Value to be set.
  1264. * @returns this effect.
  1265. */
  1266. Effect.prototype.setColor3 = function (uniformName, color3) {
  1267. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1268. this._engine.setColor3(this.getUniform(uniformName), color3);
  1269. }
  1270. return this;
  1271. };
  1272. /**
  1273. * Sets a Color4 on a uniform variable.
  1274. * @param uniformName Name of the variable.
  1275. * @param color3 Value to be set.
  1276. * @param alpha Alpha value to be set.
  1277. * @returns this effect.
  1278. */
  1279. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1280. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1281. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1282. }
  1283. return this;
  1284. };
  1285. /**
  1286. * Sets a Color4 on a uniform variable
  1287. * @param uniformName defines the name of the variable
  1288. * @param color4 defines the value to be set
  1289. * @returns this effect.
  1290. */
  1291. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1292. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1293. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1294. }
  1295. return this;
  1296. };
  1297. /**
  1298. * Resets the cache of effects.
  1299. */
  1300. Effect.ResetCache = function () {
  1301. Effect._baseCache = {};
  1302. };
  1303. Effect._uniqueIdSeed = 0;
  1304. Effect._baseCache = {};
  1305. /**
  1306. * Store of each shader (The can be looked up using effect.key)
  1307. */
  1308. Effect.ShadersStore = {};
  1309. /**
  1310. * Store of each included file for a shader (The can be looked up using effect.key)
  1311. */
  1312. Effect.IncludesShadersStore = {};
  1313. return Effect;
  1314. }());
  1315. BABYLON.Effect = Effect;
  1316. })(BABYLON || (BABYLON = {}));
  1317. //# sourceMappingURL=babylon.effect.js.map
  1318. "use strict";
  1319. //# sourceMappingURL=babylon.types.js.map
  1320. "use strict";
  1321. var BABYLON;
  1322. (function (BABYLON) {
  1323. var KeyboardEventTypes = /** @class */ (function () {
  1324. function KeyboardEventTypes() {
  1325. }
  1326. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1327. get: function () {
  1328. return KeyboardEventTypes._KEYDOWN;
  1329. },
  1330. enumerable: true,
  1331. configurable: true
  1332. });
  1333. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1334. get: function () {
  1335. return KeyboardEventTypes._KEYUP;
  1336. },
  1337. enumerable: true,
  1338. configurable: true
  1339. });
  1340. KeyboardEventTypes._KEYDOWN = 0x01;
  1341. KeyboardEventTypes._KEYUP = 0x02;
  1342. return KeyboardEventTypes;
  1343. }());
  1344. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1345. var KeyboardInfo = /** @class */ (function () {
  1346. function KeyboardInfo(type, event) {
  1347. this.type = type;
  1348. this.event = event;
  1349. }
  1350. return KeyboardInfo;
  1351. }());
  1352. BABYLON.KeyboardInfo = KeyboardInfo;
  1353. /**
  1354. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1355. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1356. */
  1357. var KeyboardInfoPre = /** @class */ (function (_super) {
  1358. __extends(KeyboardInfoPre, _super);
  1359. function KeyboardInfoPre(type, event) {
  1360. var _this = _super.call(this, type, event) || this;
  1361. _this.skipOnPointerObservable = false;
  1362. return _this;
  1363. }
  1364. return KeyboardInfoPre;
  1365. }(KeyboardInfo));
  1366. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1367. })(BABYLON || (BABYLON = {}));
  1368. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1369. "use strict";
  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. _this.skipOnPointerObservable = false;
  1451. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1452. return _this;
  1453. }
  1454. return PointerInfoPre;
  1455. }(PointerInfoBase));
  1456. BABYLON.PointerInfoPre = PointerInfoPre;
  1457. /**
  1458. * This type contains all the data related to a pointer event in Babylon.js.
  1459. * 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.
  1460. */
  1461. var PointerInfo = /** @class */ (function (_super) {
  1462. __extends(PointerInfo, _super);
  1463. function PointerInfo(type, event, pickInfo) {
  1464. var _this = _super.call(this, type, event) || this;
  1465. _this.pickInfo = pickInfo;
  1466. return _this;
  1467. }
  1468. return PointerInfo;
  1469. }(PointerInfoBase));
  1470. BABYLON.PointerInfo = PointerInfo;
  1471. })(BABYLON || (BABYLON = {}));
  1472. //# sourceMappingURL=babylon.pointerEvents.js.map
  1473. "use strict";
  1474. var BABYLON;
  1475. (function (BABYLON) {
  1476. BABYLON.ToGammaSpace = 1 / 2.2;
  1477. BABYLON.ToLinearSpace = 2.2;
  1478. BABYLON.Epsilon = 0.001;
  1479. /**
  1480. * Class used to hold a RBG color
  1481. */
  1482. var Color3 = /** @class */ (function () {
  1483. /**
  1484. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1485. * @param r defines the red component (between 0 and 1, default is 0)
  1486. * @param g defines the green component (between 0 and 1, default is 0)
  1487. * @param b defines the blue component (between 0 and 1, default is 0)
  1488. */
  1489. function Color3(
  1490. /**
  1491. * Defines the red component (between 0 and 1, default is 0)
  1492. */
  1493. r,
  1494. /**
  1495. * Defines the green component (between 0 and 1, default is 0)
  1496. */
  1497. g,
  1498. /**
  1499. * Defines the blue component (between 0 and 1, default is 0)
  1500. */
  1501. b) {
  1502. if (r === void 0) { r = 0; }
  1503. if (g === void 0) { g = 0; }
  1504. if (b === void 0) { b = 0; }
  1505. this.r = r;
  1506. this.g = g;
  1507. this.b = b;
  1508. }
  1509. /**
  1510. * Creates a string with the Color3 current values
  1511. * @returns the string representation of the Color3 object
  1512. */
  1513. Color3.prototype.toString = function () {
  1514. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1515. };
  1516. /**
  1517. * Returns the string "Color3"
  1518. * @returns "Color3"
  1519. */
  1520. Color3.prototype.getClassName = function () {
  1521. return "Color3";
  1522. };
  1523. /**
  1524. * Compute the Color3 hash code
  1525. * @returns an unique number that can be used to hash Color3 objects
  1526. */
  1527. Color3.prototype.getHashCode = function () {
  1528. var hash = this.r || 0;
  1529. hash = (hash * 397) ^ (this.g || 0);
  1530. hash = (hash * 397) ^ (this.b || 0);
  1531. return hash;
  1532. };
  1533. // Operators
  1534. /**
  1535. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1536. * @param array defines the array where to store the r,g,b components
  1537. * @param index defines an optional index in the target array to define where to start storing values
  1538. * @returns the current Color3 object
  1539. */
  1540. Color3.prototype.toArray = function (array, index) {
  1541. if (index === undefined) {
  1542. index = 0;
  1543. }
  1544. array[index] = this.r;
  1545. array[index + 1] = this.g;
  1546. array[index + 2] = this.b;
  1547. return this;
  1548. };
  1549. /**
  1550. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1551. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1552. * @returns a new {BABYLON.Color4} object
  1553. */
  1554. Color3.prototype.toColor4 = function (alpha) {
  1555. if (alpha === void 0) { alpha = 1; }
  1556. return new Color4(this.r, this.g, this.b, alpha);
  1557. };
  1558. /**
  1559. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1560. * @returns the new array
  1561. */
  1562. Color3.prototype.asArray = function () {
  1563. var result = new Array();
  1564. this.toArray(result, 0);
  1565. return result;
  1566. };
  1567. /**
  1568. * Returns the luminance value
  1569. * @returns a float value
  1570. */
  1571. Color3.prototype.toLuminance = function () {
  1572. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1573. };
  1574. /**
  1575. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1576. * @param otherColor defines the second operand
  1577. * @returns the new Color3 object
  1578. */
  1579. Color3.prototype.multiply = function (otherColor) {
  1580. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1581. };
  1582. /**
  1583. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1584. * @param otherColor defines the second operand
  1585. * @param result defines the Color3 object where to store the result
  1586. * @returns the current Color3
  1587. */
  1588. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1589. result.r = this.r * otherColor.r;
  1590. result.g = this.g * otherColor.g;
  1591. result.b = this.b * otherColor.b;
  1592. return this;
  1593. };
  1594. /**
  1595. * Determines equality between Color3 objects
  1596. * @param otherColor defines the second operand
  1597. * @returns true if the rgb values are equal to the passed ones
  1598. */
  1599. Color3.prototype.equals = function (otherColor) {
  1600. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1601. };
  1602. /**
  1603. * Determines equality between the current Color3 object and a set of r,b,g values
  1604. * @param r defines the red component to check
  1605. * @param g defines the green component to check
  1606. * @param b defines the blue component to check
  1607. * @returns true if the rgb values are equal to the passed ones
  1608. */
  1609. Color3.prototype.equalsFloats = function (r, g, b) {
  1610. return this.r === r && this.g === g && this.b === b;
  1611. };
  1612. /**
  1613. * Multiplies in place each rgb value by scale
  1614. * @param scale defines the scaling factor
  1615. * @returns the updated Color3
  1616. */
  1617. Color3.prototype.scale = function (scale) {
  1618. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1619. };
  1620. /**
  1621. * Multiplies the rgb values by scale and stores the result into "result"
  1622. * @param scale defines the scaling factor
  1623. * @param result defines the Color3 object where to store the result
  1624. * @returns the unmodified current Color3
  1625. */
  1626. Color3.prototype.scaleToRef = function (scale, result) {
  1627. result.r = this.r * scale;
  1628. result.g = this.g * scale;
  1629. result.b = this.b * scale;
  1630. return this;
  1631. };
  1632. /**
  1633. * Scale the current Color3 values by a factor and add the result to a given Color3
  1634. * @param scale defines the scale factor
  1635. * @param result defines color to store the result into
  1636. * @returns the unmodified current Color3
  1637. */
  1638. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1639. result.r += this.r * scale;
  1640. result.g += this.g * scale;
  1641. result.b += this.b * scale;
  1642. return this;
  1643. };
  1644. /**
  1645. * Clamps the rgb values by the min and max values and stores the result into "result"
  1646. * @param min defines minimum clamping value (default is 0)
  1647. * @param max defines maximum clamping value (default is 1)
  1648. * @param result defines color to store the result into
  1649. * @returns the original Color3
  1650. */
  1651. Color3.prototype.clampToRef = function (min, max, result) {
  1652. if (min === void 0) { min = 0; }
  1653. if (max === void 0) { max = 1; }
  1654. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1655. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1656. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1657. return this;
  1658. };
  1659. /**
  1660. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1661. * @param otherColor defines the second operand
  1662. * @returns the new Color3
  1663. */
  1664. Color3.prototype.add = function (otherColor) {
  1665. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1666. };
  1667. /**
  1668. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1669. * @param otherColor defines the second operand
  1670. * @param result defines Color3 object to store the result into
  1671. * @returns the unmodified current Color3
  1672. */
  1673. Color3.prototype.addToRef = function (otherColor, result) {
  1674. result.r = this.r + otherColor.r;
  1675. result.g = this.g + otherColor.g;
  1676. result.b = this.b + otherColor.b;
  1677. return this;
  1678. };
  1679. /**
  1680. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1681. * @param otherColor defines the second operand
  1682. * @returns the new Color3
  1683. */
  1684. Color3.prototype.subtract = function (otherColor) {
  1685. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1686. };
  1687. /**
  1688. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1689. * @param otherColor defines the second operand
  1690. * @param result defines Color3 object to store the result into
  1691. * @returns the unmodified current Color3
  1692. */
  1693. Color3.prototype.subtractToRef = function (otherColor, result) {
  1694. result.r = this.r - otherColor.r;
  1695. result.g = this.g - otherColor.g;
  1696. result.b = this.b - otherColor.b;
  1697. return this;
  1698. };
  1699. /**
  1700. * Copy the current object
  1701. * @returns a new Color3 copied the current one
  1702. */
  1703. Color3.prototype.clone = function () {
  1704. return new Color3(this.r, this.g, this.b);
  1705. };
  1706. /**
  1707. * Copies the rgb values from the source in the current Color3
  1708. * @param source defines the source Color3 object
  1709. * @returns the updated Color3 object
  1710. */
  1711. Color3.prototype.copyFrom = function (source) {
  1712. this.r = source.r;
  1713. this.g = source.g;
  1714. this.b = source.b;
  1715. return this;
  1716. };
  1717. /**
  1718. * Updates the Color3 rgb values from the passed floats
  1719. * @param r defines the red component to read from
  1720. * @param g defines the green component to read from
  1721. * @param b defines the blue component to read from
  1722. * @returns the current Color3 object
  1723. */
  1724. Color3.prototype.copyFromFloats = function (r, g, b) {
  1725. this.r = r;
  1726. this.g = g;
  1727. this.b = b;
  1728. return this;
  1729. };
  1730. /**
  1731. * Updates the Color3 rgb values from the passed floats
  1732. * @param r defines the red component to read from
  1733. * @param g defines the green component to read from
  1734. * @param b defines the blue component to read from
  1735. * @returns the current Color3 object
  1736. */
  1737. Color3.prototype.set = function (r, g, b) {
  1738. return this.copyFromFloats(r, g, b);
  1739. };
  1740. /**
  1741. * Compute the Color3 hexadecimal code as a string
  1742. * @returns a string containing the hexadecimal representation of the Color3 object
  1743. */
  1744. Color3.prototype.toHexString = function () {
  1745. var intR = (this.r * 255) | 0;
  1746. var intG = (this.g * 255) | 0;
  1747. var intB = (this.b * 255) | 0;
  1748. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1749. };
  1750. /**
  1751. * Computes a new Color3 converted from the current one to linear space
  1752. * @returns a new Color3 object
  1753. */
  1754. Color3.prototype.toLinearSpace = function () {
  1755. var convertedColor = new Color3();
  1756. this.toLinearSpaceToRef(convertedColor);
  1757. return convertedColor;
  1758. };
  1759. /**
  1760. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1761. * @param convertedColor defines the Color3 object where to store the linear space version
  1762. * @returns the unmodified Color3
  1763. */
  1764. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1765. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1766. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1767. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1768. return this;
  1769. };
  1770. /**
  1771. * Computes a new Color3 converted from the current one to gamma space
  1772. * @returns a new Color3 object
  1773. */
  1774. Color3.prototype.toGammaSpace = function () {
  1775. var convertedColor = new Color3();
  1776. this.toGammaSpaceToRef(convertedColor);
  1777. return convertedColor;
  1778. };
  1779. /**
  1780. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1781. * @param convertedColor defines the Color3 object where to store the gamma space version
  1782. * @returns the unmodified Color3
  1783. */
  1784. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1785. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1786. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1787. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1788. return this;
  1789. };
  1790. // Statics
  1791. /**
  1792. * Creates a new Color3 from the string containing valid hexadecimal values
  1793. * @param hex defines a string containing valid hexadecimal values
  1794. * @returns a new Color3 object
  1795. */
  1796. Color3.FromHexString = function (hex) {
  1797. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1798. return new Color3(0, 0, 0);
  1799. }
  1800. var r = parseInt(hex.substring(1, 3), 16);
  1801. var g = parseInt(hex.substring(3, 5), 16);
  1802. var b = parseInt(hex.substring(5, 7), 16);
  1803. return Color3.FromInts(r, g, b);
  1804. };
  1805. /**
  1806. * Creates a new Vector3 from the starting index of the passed array
  1807. * @param array defines the source array
  1808. * @param offset defines an offset in the source array
  1809. * @returns a new Color3 object
  1810. */
  1811. Color3.FromArray = function (array, offset) {
  1812. if (offset === void 0) { offset = 0; }
  1813. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1814. };
  1815. /**
  1816. * Creates a new Color3 from integer values (< 256)
  1817. * @param r defines the red component to read from (value between 0 and 255)
  1818. * @param g defines the green component to read from (value between 0 and 255)
  1819. * @param b defines the blue component to read from (value between 0 and 255)
  1820. * @returns a new Color3 object
  1821. */
  1822. Color3.FromInts = function (r, g, b) {
  1823. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1824. };
  1825. /**
  1826. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1827. * @param start defines the start Color3 value
  1828. * @param end defines the end Color3 value
  1829. * @param amount defines the gradient value between start and end
  1830. * @returns a new Color3 object
  1831. */
  1832. Color3.Lerp = function (start, end, amount) {
  1833. var r = start.r + ((end.r - start.r) * amount);
  1834. var g = start.g + ((end.g - start.g) * amount);
  1835. var b = start.b + ((end.b - start.b) * amount);
  1836. return new Color3(r, g, b);
  1837. };
  1838. /**
  1839. * Returns a Color3 value containing a red color
  1840. * @returns a new Color3 object
  1841. */
  1842. Color3.Red = function () { return new Color3(1, 0, 0); };
  1843. /**
  1844. * Returns a Color3 value containing a green color
  1845. * @returns a new Color3 object
  1846. */
  1847. Color3.Green = function () { return new Color3(0, 1, 0); };
  1848. /**
  1849. * Returns a Color3 value containing a blue color
  1850. * @returns a new Color3 object
  1851. */
  1852. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1853. /**
  1854. * Returns a Color3 value containing a black color
  1855. * @returns a new Color3 object
  1856. */
  1857. Color3.Black = function () { return new Color3(0, 0, 0); };
  1858. /**
  1859. * Returns a Color3 value containing a white color
  1860. * @returns a new Color3 object
  1861. */
  1862. Color3.White = function () { return new Color3(1, 1, 1); };
  1863. /**
  1864. * Returns a Color3 value containing a purple color
  1865. * @returns a new Color3 object
  1866. */
  1867. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1868. /**
  1869. * Returns a Color3 value containing a magenta color
  1870. * @returns a new Color3 object
  1871. */
  1872. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1873. /**
  1874. * Returns a Color3 value containing a yellow color
  1875. * @returns a new Color3 object
  1876. */
  1877. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1878. /**
  1879. * Returns a Color3 value containing a gray color
  1880. * @returns a new Color3 object
  1881. */
  1882. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1883. /**
  1884. * Returns a Color3 value containing a teal color
  1885. * @returns a new Color3 object
  1886. */
  1887. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1888. /**
  1889. * Returns a Color3 value containing a random color
  1890. * @returns a new Color3 object
  1891. */
  1892. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1893. return Color3;
  1894. }());
  1895. BABYLON.Color3 = Color3;
  1896. /**
  1897. * Class used to hold a RBGA color
  1898. */
  1899. var Color4 = /** @class */ (function () {
  1900. /**
  1901. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1902. * @param r defines the red component (between 0 and 1, default is 0)
  1903. * @param g defines the green component (between 0 and 1, default is 0)
  1904. * @param b defines the blue component (between 0 and 1, default is 0)
  1905. * @param a defines the alpha component (between 0 and 1, default is 1)
  1906. */
  1907. function Color4(
  1908. /**
  1909. * Defines the red component (between 0 and 1, default is 0)
  1910. */
  1911. r,
  1912. /**
  1913. * Defines the green component (between 0 and 1, default is 0)
  1914. */
  1915. g,
  1916. /**
  1917. * Defines the blue component (between 0 and 1, default is 0)
  1918. */
  1919. b,
  1920. /**
  1921. * Defines the alpha component (between 0 and 1, default is 1)
  1922. */
  1923. a) {
  1924. if (r === void 0) { r = 0; }
  1925. if (g === void 0) { g = 0; }
  1926. if (b === void 0) { b = 0; }
  1927. if (a === void 0) { a = 1; }
  1928. this.r = r;
  1929. this.g = g;
  1930. this.b = b;
  1931. this.a = a;
  1932. }
  1933. // Operators
  1934. /**
  1935. * Adds in place the passed Color4 values to the current Color4 object
  1936. * @param right defines the second operand
  1937. * @returns the current updated Color4 object
  1938. */
  1939. Color4.prototype.addInPlace = function (right) {
  1940. this.r += right.r;
  1941. this.g += right.g;
  1942. this.b += right.b;
  1943. this.a += right.a;
  1944. return this;
  1945. };
  1946. /**
  1947. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1948. * @returns the new array
  1949. */
  1950. Color4.prototype.asArray = function () {
  1951. var result = new Array();
  1952. this.toArray(result, 0);
  1953. return result;
  1954. };
  1955. /**
  1956. * Stores from the starting index in the passed array the Color4 successive values
  1957. * @param array defines the array where to store the r,g,b components
  1958. * @param index defines an optional index in the target array to define where to start storing values
  1959. * @returns the current Color4 object
  1960. */
  1961. Color4.prototype.toArray = function (array, index) {
  1962. if (index === undefined) {
  1963. index = 0;
  1964. }
  1965. array[index] = this.r;
  1966. array[index + 1] = this.g;
  1967. array[index + 2] = this.b;
  1968. array[index + 3] = this.a;
  1969. return this;
  1970. };
  1971. /**
  1972. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1973. * @param right defines the second operand
  1974. * @returns a new Color4 object
  1975. */
  1976. Color4.prototype.add = function (right) {
  1977. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1978. };
  1979. /**
  1980. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1981. * @param right defines the second operand
  1982. * @returns a new Color4 object
  1983. */
  1984. Color4.prototype.subtract = function (right) {
  1985. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1986. };
  1987. /**
  1988. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1989. * @param right defines the second operand
  1990. * @param result defines the Color4 object where to store the result
  1991. * @returns the current Color4 object
  1992. */
  1993. Color4.prototype.subtractToRef = function (right, result) {
  1994. result.r = this.r - right.r;
  1995. result.g = this.g - right.g;
  1996. result.b = this.b - right.b;
  1997. result.a = this.a - right.a;
  1998. return this;
  1999. };
  2000. /**
  2001. * Creates a new Color4 with the current Color4 values multiplied by scale
  2002. * @param scale defines the scaling factor to apply
  2003. * @returns a new Color4 object
  2004. */
  2005. Color4.prototype.scale = function (scale) {
  2006. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  2007. };
  2008. /**
  2009. * Multiplies the current Color4 values by scale and stores the result in "result"
  2010. * @param scale defines the scaling factor to apply
  2011. * @param result defines the Color4 object where to store the result
  2012. * @returns the current unmodified Color4
  2013. */
  2014. Color4.prototype.scaleToRef = function (scale, result) {
  2015. result.r = this.r * scale;
  2016. result.g = this.g * scale;
  2017. result.b = this.b * scale;
  2018. result.a = this.a * scale;
  2019. return this;
  2020. };
  2021. /**
  2022. * Scale the current Color4 values by a factor and add the result to a given Color4
  2023. * @param scale defines the scale factor
  2024. * @param result defines the Color4 object where to store the result
  2025. * @returns the unmodified current Color4
  2026. */
  2027. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  2028. result.r += this.r * scale;
  2029. result.g += this.g * scale;
  2030. result.b += this.b * scale;
  2031. result.a += this.a * scale;
  2032. return this;
  2033. };
  2034. /**
  2035. * Clamps the rgb values by the min and max values and stores the result into "result"
  2036. * @param min defines minimum clamping value (default is 0)
  2037. * @param max defines maximum clamping value (default is 1)
  2038. * @param result defines color to store the result into.
  2039. * @returns the cuurent Color4
  2040. */
  2041. Color4.prototype.clampToRef = function (min, max, result) {
  2042. if (min === void 0) { min = 0; }
  2043. if (max === void 0) { max = 1; }
  2044. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2045. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2046. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2047. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2048. return this;
  2049. };
  2050. /**
  2051. * Multipy an Color4 value by another and return a new Color4 object
  2052. * @param color defines the Color4 value to multiply by
  2053. * @returns a new Color4 object
  2054. */
  2055. Color4.prototype.multiply = function (color) {
  2056. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2057. };
  2058. /**
  2059. * Multipy a Color4 value by another and push the result in a reference value
  2060. * @param color defines the Color4 value to multiply by
  2061. * @param result defines the Color4 to fill the result in
  2062. * @returns the result Color4
  2063. */
  2064. Color4.prototype.multiplyToRef = function (color, result) {
  2065. result.r = this.r * color.r;
  2066. result.g = this.g * color.g;
  2067. result.b = this.b * color.b;
  2068. result.a = this.a * color.a;
  2069. return result;
  2070. };
  2071. /**
  2072. * Creates a string with the Color4 current values
  2073. * @returns the string representation of the Color4 object
  2074. */
  2075. Color4.prototype.toString = function () {
  2076. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2077. };
  2078. /**
  2079. * Returns the string "Color4"
  2080. * @returns "Color4"
  2081. */
  2082. Color4.prototype.getClassName = function () {
  2083. return "Color4";
  2084. };
  2085. /**
  2086. * Compute the Color4 hash code
  2087. * @returns an unique number that can be used to hash Color4 objects
  2088. */
  2089. Color4.prototype.getHashCode = function () {
  2090. var hash = this.r || 0;
  2091. hash = (hash * 397) ^ (this.g || 0);
  2092. hash = (hash * 397) ^ (this.b || 0);
  2093. hash = (hash * 397) ^ (this.a || 0);
  2094. return hash;
  2095. };
  2096. /**
  2097. * Creates a new Color4 copied from the current one
  2098. * @returns a new Color4 object
  2099. */
  2100. Color4.prototype.clone = function () {
  2101. return new Color4(this.r, this.g, this.b, this.a);
  2102. };
  2103. /**
  2104. * Copies the passed Color4 values into the current one
  2105. * @param source defines the source Color4 object
  2106. * @returns the current updated Color4 object
  2107. */
  2108. Color4.prototype.copyFrom = function (source) {
  2109. this.r = source.r;
  2110. this.g = source.g;
  2111. this.b = source.b;
  2112. this.a = source.a;
  2113. return this;
  2114. };
  2115. /**
  2116. * Copies the passed float values into the current one
  2117. * @param r defines the red component to read from
  2118. * @param g defines the green component to read from
  2119. * @param b defines the blue component to read from
  2120. * @param a defines the alpha component to read from
  2121. * @returns the current updated Color4 object
  2122. */
  2123. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2124. this.r = r;
  2125. this.g = g;
  2126. this.b = b;
  2127. this.a = a;
  2128. return this;
  2129. };
  2130. /**
  2131. * Copies the passed float values into the current one
  2132. * @param r defines the red component to read from
  2133. * @param g defines the green component to read from
  2134. * @param b defines the blue component to read from
  2135. * @param a defines the alpha component to read from
  2136. * @returns the current updated Color4 object
  2137. */
  2138. Color4.prototype.set = function (r, g, b, a) {
  2139. return this.copyFromFloats(r, g, b, a);
  2140. };
  2141. /**
  2142. * Compute the Color4 hexadecimal code as a string
  2143. * @returns a string containing the hexadecimal representation of the Color4 object
  2144. */
  2145. Color4.prototype.toHexString = function () {
  2146. var intR = (this.r * 255) | 0;
  2147. var intG = (this.g * 255) | 0;
  2148. var intB = (this.b * 255) | 0;
  2149. var intA = (this.a * 255) | 0;
  2150. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2151. };
  2152. /**
  2153. * Computes a new Color4 converted from the current one to linear space
  2154. * @returns a new Color4 object
  2155. */
  2156. Color4.prototype.toLinearSpace = function () {
  2157. var convertedColor = new Color4();
  2158. this.toLinearSpaceToRef(convertedColor);
  2159. return convertedColor;
  2160. };
  2161. /**
  2162. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2163. * @param convertedColor defines the Color4 object where to store the linear space version
  2164. * @returns the unmodified Color4
  2165. */
  2166. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2167. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2168. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2169. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2170. convertedColor.a = this.a;
  2171. return this;
  2172. };
  2173. /**
  2174. * Computes a new Color4 converted from the current one to gamma space
  2175. * @returns a new Color4 object
  2176. */
  2177. Color4.prototype.toGammaSpace = function () {
  2178. var convertedColor = new Color4();
  2179. this.toGammaSpaceToRef(convertedColor);
  2180. return convertedColor;
  2181. };
  2182. /**
  2183. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2184. * @param convertedColor defines the Color4 object where to store the gamma space version
  2185. * @returns the unmodified Color4
  2186. */
  2187. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2188. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2189. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2190. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2191. convertedColor.a = this.a;
  2192. return this;
  2193. };
  2194. // Statics
  2195. /**
  2196. * Creates a new Color4 from the string containing valid hexadecimal values
  2197. * @param hex defines a string containing valid hexadecimal values
  2198. * @returns a new Color4 object
  2199. */
  2200. Color4.FromHexString = function (hex) {
  2201. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2202. return new Color4(0.0, 0.0, 0.0, 0.0);
  2203. }
  2204. var r = parseInt(hex.substring(1, 3), 16);
  2205. var g = parseInt(hex.substring(3, 5), 16);
  2206. var b = parseInt(hex.substring(5, 7), 16);
  2207. var a = parseInt(hex.substring(7, 9), 16);
  2208. return Color4.FromInts(r, g, b, a);
  2209. };
  2210. /**
  2211. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2212. * @param left defines the start value
  2213. * @param right defines the end value
  2214. * @param amount defines the gradient factor
  2215. * @returns a new Color4 object
  2216. */
  2217. Color4.Lerp = function (left, right, amount) {
  2218. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2219. Color4.LerpToRef(left, right, amount, result);
  2220. return result;
  2221. };
  2222. /**
  2223. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2224. * @param left defines the start value
  2225. * @param right defines the end value
  2226. * @param amount defines the gradient factor
  2227. * @param result defines the Color4 object where to store data
  2228. */
  2229. Color4.LerpToRef = function (left, right, amount, result) {
  2230. result.r = left.r + (right.r - left.r) * amount;
  2231. result.g = left.g + (right.g - left.g) * amount;
  2232. result.b = left.b + (right.b - left.b) * amount;
  2233. result.a = left.a + (right.a - left.a) * amount;
  2234. };
  2235. /**
  2236. * Creates a new Color4 from the starting index element of the passed array
  2237. * @param array defines the source array to read from
  2238. * @param offset defines the offset in the source array
  2239. * @returns a new Color4 object
  2240. */
  2241. Color4.FromArray = function (array, offset) {
  2242. if (offset === void 0) { offset = 0; }
  2243. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2244. };
  2245. /**
  2246. * Creates a new Color3 from integer values (< 256)
  2247. * @param r defines the red component to read from (value between 0 and 255)
  2248. * @param g defines the green component to read from (value between 0 and 255)
  2249. * @param b defines the blue component to read from (value between 0 and 255)
  2250. * @param a defines the alpha component to read from (value between 0 and 255)
  2251. * @returns a new Color3 object
  2252. */
  2253. Color4.FromInts = function (r, g, b, a) {
  2254. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2255. };
  2256. /**
  2257. * Check the content of a given array and convert it to an array containing RGBA data
  2258. * If the original array was already containing count * 4 values then it is returned directly
  2259. * @param colors defines the array to check
  2260. * @param count defines the number of RGBA data to expect
  2261. * @returns an array containing count * 4 values (RGBA)
  2262. */
  2263. Color4.CheckColors4 = function (colors, count) {
  2264. // Check if color3 was used
  2265. if (colors.length === count * 3) {
  2266. var colors4 = [];
  2267. for (var index = 0; index < colors.length; index += 3) {
  2268. var newIndex = (index / 3) * 4;
  2269. colors4[newIndex] = colors[index];
  2270. colors4[newIndex + 1] = colors[index + 1];
  2271. colors4[newIndex + 2] = colors[index + 2];
  2272. colors4[newIndex + 3] = 1.0;
  2273. }
  2274. return colors4;
  2275. }
  2276. return colors;
  2277. };
  2278. return Color4;
  2279. }());
  2280. BABYLON.Color4 = Color4;
  2281. var Vector2 = /** @class */ (function () {
  2282. /**
  2283. * Creates a new Vector2 from the passed x and y coordinates.
  2284. */
  2285. function Vector2(x, y) {
  2286. this.x = x;
  2287. this.y = y;
  2288. }
  2289. /**
  2290. * Returns a string with the Vector2 coordinates.
  2291. */
  2292. Vector2.prototype.toString = function () {
  2293. return "{X: " + this.x + " Y:" + this.y + "}";
  2294. };
  2295. /**
  2296. * Returns the string "Vector2"
  2297. */
  2298. Vector2.prototype.getClassName = function () {
  2299. return "Vector2";
  2300. };
  2301. /**
  2302. * Returns the Vector2 hash code as a number.
  2303. */
  2304. Vector2.prototype.getHashCode = function () {
  2305. var hash = this.x || 0;
  2306. hash = (hash * 397) ^ (this.y || 0);
  2307. return hash;
  2308. };
  2309. // Operators
  2310. /**
  2311. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2312. * Returns the Vector2.
  2313. */
  2314. Vector2.prototype.toArray = function (array, index) {
  2315. if (index === void 0) { index = 0; }
  2316. array[index] = this.x;
  2317. array[index + 1] = this.y;
  2318. return this;
  2319. };
  2320. /**
  2321. * Returns a new array with 2 elements : the Vector2 coordinates.
  2322. */
  2323. Vector2.prototype.asArray = function () {
  2324. var result = new Array();
  2325. this.toArray(result, 0);
  2326. return result;
  2327. };
  2328. /**
  2329. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2330. * Returns the updated Vector2.
  2331. */
  2332. Vector2.prototype.copyFrom = function (source) {
  2333. this.x = source.x;
  2334. this.y = source.y;
  2335. return this;
  2336. };
  2337. /**
  2338. * Sets the Vector2 coordinates with the passed floats.
  2339. * Returns the updated Vector2.
  2340. */
  2341. Vector2.prototype.copyFromFloats = function (x, y) {
  2342. this.x = x;
  2343. this.y = y;
  2344. return this;
  2345. };
  2346. /**
  2347. * Sets the Vector2 coordinates with the passed floats.
  2348. * Returns the updated Vector2.
  2349. */
  2350. Vector2.prototype.set = function (x, y) {
  2351. return this.copyFromFloats(x, y);
  2352. };
  2353. /**
  2354. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2355. */
  2356. Vector2.prototype.add = function (otherVector) {
  2357. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2358. };
  2359. /**
  2360. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2361. * Returns the Vector2.
  2362. */
  2363. Vector2.prototype.addToRef = function (otherVector, result) {
  2364. result.x = this.x + otherVector.x;
  2365. result.y = this.y + otherVector.y;
  2366. return this;
  2367. };
  2368. /**
  2369. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2370. * Returns the updated Vector2.
  2371. */
  2372. Vector2.prototype.addInPlace = function (otherVector) {
  2373. this.x += otherVector.x;
  2374. this.y += otherVector.y;
  2375. return this;
  2376. };
  2377. /**
  2378. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2379. */
  2380. Vector2.prototype.addVector3 = function (otherVector) {
  2381. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2382. };
  2383. /**
  2384. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2385. */
  2386. Vector2.prototype.subtract = function (otherVector) {
  2387. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2388. };
  2389. /**
  2390. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2391. * Returns the Vector2.
  2392. */
  2393. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2394. result.x = this.x - otherVector.x;
  2395. result.y = this.y - otherVector.y;
  2396. return this;
  2397. };
  2398. /**
  2399. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2400. * Returns the updated Vector2.
  2401. */
  2402. Vector2.prototype.subtractInPlace = function (otherVector) {
  2403. this.x -= otherVector.x;
  2404. this.y -= otherVector.y;
  2405. return this;
  2406. };
  2407. /**
  2408. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2409. * Returns the updated Vector2.
  2410. */
  2411. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2412. this.x *= otherVector.x;
  2413. this.y *= otherVector.y;
  2414. return this;
  2415. };
  2416. /**
  2417. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2418. */
  2419. Vector2.prototype.multiply = function (otherVector) {
  2420. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2421. };
  2422. /**
  2423. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2424. * Returns the Vector2.
  2425. */
  2426. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2427. result.x = this.x * otherVector.x;
  2428. result.y = this.y * otherVector.y;
  2429. return this;
  2430. };
  2431. /**
  2432. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2433. */
  2434. Vector2.prototype.multiplyByFloats = function (x, y) {
  2435. return new Vector2(this.x * x, this.y * y);
  2436. };
  2437. /**
  2438. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2439. */
  2440. Vector2.prototype.divide = function (otherVector) {
  2441. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2442. };
  2443. /**
  2444. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2445. * Returns the Vector2.
  2446. */
  2447. Vector2.prototype.divideToRef = function (otherVector, result) {
  2448. result.x = this.x / otherVector.x;
  2449. result.y = this.y / otherVector.y;
  2450. return this;
  2451. };
  2452. /**
  2453. * Divides the current Vector3 coordinates by the passed ones.
  2454. * Returns the updated Vector3.
  2455. */
  2456. Vector2.prototype.divideInPlace = function (otherVector) {
  2457. return this.divideToRef(otherVector, this);
  2458. };
  2459. /**
  2460. * Returns a new Vector2 with current Vector2 negated coordinates.
  2461. */
  2462. Vector2.prototype.negate = function () {
  2463. return new Vector2(-this.x, -this.y);
  2464. };
  2465. /**
  2466. * Multiply the Vector2 coordinates by scale.
  2467. * Returns the updated Vector2.
  2468. */
  2469. Vector2.prototype.scaleInPlace = function (scale) {
  2470. this.x *= scale;
  2471. this.y *= scale;
  2472. return this;
  2473. };
  2474. /**
  2475. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2476. */
  2477. Vector2.prototype.scale = function (scale) {
  2478. var result = new Vector2(0, 0);
  2479. this.scaleToRef(scale, result);
  2480. return result;
  2481. };
  2482. /**
  2483. * Scale the current Vector2 values by a factor to a given Vector2
  2484. * @param scale defines the scale factor
  2485. * @param result defines the Vector2 object where to store the result
  2486. * @returns the unmodified current Vector2
  2487. */
  2488. Vector2.prototype.scaleToRef = function (scale, result) {
  2489. result.x = this.x * scale;
  2490. result.y = this.y * scale;
  2491. return this;
  2492. };
  2493. /**
  2494. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2495. * @param scale defines the scale factor
  2496. * @param result defines the Vector2 object where to store the result
  2497. * @returns the unmodified current Vector2
  2498. */
  2499. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2500. result.x += this.x * scale;
  2501. result.y += this.y * scale;
  2502. return this;
  2503. };
  2504. /**
  2505. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2506. */
  2507. Vector2.prototype.equals = function (otherVector) {
  2508. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2509. };
  2510. /**
  2511. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2512. */
  2513. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2514. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2515. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2516. };
  2517. // Properties
  2518. /**
  2519. * Returns the vector length (float).
  2520. */
  2521. Vector2.prototype.length = function () {
  2522. return Math.sqrt(this.x * this.x + this.y * this.y);
  2523. };
  2524. /**
  2525. * Returns the vector squared length (float);
  2526. */
  2527. Vector2.prototype.lengthSquared = function () {
  2528. return (this.x * this.x + this.y * this.y);
  2529. };
  2530. // Methods
  2531. /**
  2532. * Normalize the vector.
  2533. * Returns the updated Vector2.
  2534. */
  2535. Vector2.prototype.normalize = function () {
  2536. var len = this.length();
  2537. if (len === 0)
  2538. return this;
  2539. var num = 1.0 / len;
  2540. this.x *= num;
  2541. this.y *= num;
  2542. return this;
  2543. };
  2544. /**
  2545. * Returns a new Vector2 copied from the Vector2.
  2546. */
  2547. Vector2.prototype.clone = function () {
  2548. return new Vector2(this.x, this.y);
  2549. };
  2550. // Statics
  2551. /**
  2552. * Returns a new Vector2(0, 0)
  2553. */
  2554. Vector2.Zero = function () {
  2555. return new Vector2(0, 0);
  2556. };
  2557. /**
  2558. * Returns a new Vector2(1, 1)
  2559. */
  2560. Vector2.One = function () {
  2561. return new Vector2(1, 1);
  2562. };
  2563. /**
  2564. * Returns a new Vector2 set from the passed index element of the passed array.
  2565. */
  2566. Vector2.FromArray = function (array, offset) {
  2567. if (offset === void 0) { offset = 0; }
  2568. return new Vector2(array[offset], array[offset + 1]);
  2569. };
  2570. /**
  2571. * Sets "result" from the passed index element of the passed array.
  2572. */
  2573. Vector2.FromArrayToRef = function (array, offset, result) {
  2574. result.x = array[offset];
  2575. result.y = array[offset + 1];
  2576. };
  2577. /**
  2578. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2579. */
  2580. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2581. var squared = amount * amount;
  2582. var cubed = amount * squared;
  2583. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2584. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2585. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2586. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2587. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2588. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2589. return new Vector2(x, y);
  2590. };
  2591. /**
  2592. * 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".
  2593. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2594. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2595. */
  2596. Vector2.Clamp = function (value, min, max) {
  2597. var x = value.x;
  2598. x = (x > max.x) ? max.x : x;
  2599. x = (x < min.x) ? min.x : x;
  2600. var y = value.y;
  2601. y = (y > max.y) ? max.y : y;
  2602. y = (y < min.y) ? min.y : y;
  2603. return new Vector2(x, y);
  2604. };
  2605. /**
  2606. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2607. */
  2608. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2609. var squared = amount * amount;
  2610. var cubed = amount * squared;
  2611. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2612. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2613. var part3 = (cubed - (2.0 * squared)) + amount;
  2614. var part4 = cubed - squared;
  2615. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2616. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2617. return new Vector2(x, y);
  2618. };
  2619. /**
  2620. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2621. */
  2622. Vector2.Lerp = function (start, end, amount) {
  2623. var x = start.x + ((end.x - start.x) * amount);
  2624. var y = start.y + ((end.y - start.y) * amount);
  2625. return new Vector2(x, y);
  2626. };
  2627. /**
  2628. * Returns the dot product (float) of the vector "left" and the vector "right".
  2629. */
  2630. Vector2.Dot = function (left, right) {
  2631. return left.x * right.x + left.y * right.y;
  2632. };
  2633. /**
  2634. * Returns a new Vector2 equal to the normalized passed vector.
  2635. */
  2636. Vector2.Normalize = function (vector) {
  2637. var newVector = vector.clone();
  2638. newVector.normalize();
  2639. return newVector;
  2640. };
  2641. /**
  2642. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2643. */
  2644. Vector2.Minimize = function (left, right) {
  2645. var x = (left.x < right.x) ? left.x : right.x;
  2646. var y = (left.y < right.y) ? left.y : right.y;
  2647. return new Vector2(x, y);
  2648. };
  2649. /**
  2650. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2651. */
  2652. Vector2.Maximize = function (left, right) {
  2653. var x = (left.x > right.x) ? left.x : right.x;
  2654. var y = (left.y > right.y) ? left.y : right.y;
  2655. return new Vector2(x, y);
  2656. };
  2657. /**
  2658. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2659. */
  2660. Vector2.Transform = function (vector, transformation) {
  2661. var r = Vector2.Zero();
  2662. Vector2.TransformToRef(vector, transformation, r);
  2663. return r;
  2664. };
  2665. /**
  2666. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2667. */
  2668. Vector2.TransformToRef = function (vector, transformation, result) {
  2669. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2670. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2671. result.x = x;
  2672. result.y = y;
  2673. };
  2674. /**
  2675. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2676. */
  2677. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2678. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2679. var sign = a < 0 ? -1 : 1;
  2680. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2681. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2682. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2683. };
  2684. /**
  2685. * Returns the distance (float) between the vectors "value1" and "value2".
  2686. */
  2687. Vector2.Distance = function (value1, value2) {
  2688. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2689. };
  2690. /**
  2691. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2692. */
  2693. Vector2.DistanceSquared = function (value1, value2) {
  2694. var x = value1.x - value2.x;
  2695. var y = value1.y - value2.y;
  2696. return (x * x) + (y * y);
  2697. };
  2698. /**
  2699. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2700. */
  2701. Vector2.Center = function (value1, value2) {
  2702. var center = value1.add(value2);
  2703. center.scaleInPlace(0.5);
  2704. return center;
  2705. };
  2706. /**
  2707. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2708. */
  2709. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2710. var l2 = Vector2.DistanceSquared(segA, segB);
  2711. if (l2 === 0.0) {
  2712. return Vector2.Distance(p, segA);
  2713. }
  2714. var v = segB.subtract(segA);
  2715. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2716. var proj = segA.add(v.multiplyByFloats(t, t));
  2717. return Vector2.Distance(p, proj);
  2718. };
  2719. return Vector2;
  2720. }());
  2721. BABYLON.Vector2 = Vector2;
  2722. /**
  2723. * Classed used to store (x,y,z) vector representation
  2724. * A Vector3 is the main object used in 3D geometry
  2725. * It can represent etiher the coordinates of a point the space, either a direction
  2726. * Reminder: Babylon.js uses a left handed forward facing system
  2727. */
  2728. var Vector3 = /** @class */ (function () {
  2729. /**
  2730. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2731. * @param x defines the first coordinates (on X axis)
  2732. * @param y defines the second coordinates (on Y axis)
  2733. * @param z defines the third coordinates (on Z axis)
  2734. */
  2735. function Vector3(
  2736. /**
  2737. * Defines the first coordinates (on X axis)
  2738. */
  2739. x,
  2740. /**
  2741. * Defines the second coordinates (on Y axis)
  2742. */
  2743. y,
  2744. /**
  2745. * Defines the third coordinates (on Z axis)
  2746. */
  2747. z) {
  2748. this.x = x;
  2749. this.y = y;
  2750. this.z = z;
  2751. }
  2752. /**
  2753. * Creates a string representation of the Vector3
  2754. * @returns a string with the Vector3 coordinates.
  2755. */
  2756. Vector3.prototype.toString = function () {
  2757. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2758. };
  2759. /**
  2760. * Gets the class name
  2761. * @returns the string "Vector3"
  2762. */
  2763. Vector3.prototype.getClassName = function () {
  2764. return "Vector3";
  2765. };
  2766. /**
  2767. * Creates the Vector3 hash code
  2768. * @returns a number which tends to be unique between Vector3 instances
  2769. */
  2770. Vector3.prototype.getHashCode = function () {
  2771. var hash = this.x || 0;
  2772. hash = (hash * 397) ^ (this.y || 0);
  2773. hash = (hash * 397) ^ (this.z || 0);
  2774. return hash;
  2775. };
  2776. // Operators
  2777. /**
  2778. * Creates an array containing three elements : the coordinates of the Vector3
  2779. * @returns a new array of numbers
  2780. */
  2781. Vector3.prototype.asArray = function () {
  2782. var result = [];
  2783. this.toArray(result, 0);
  2784. return result;
  2785. };
  2786. /**
  2787. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2788. * @param array defines the destination array
  2789. * @param index defines the offset in the destination array
  2790. * @returns the current Vector3
  2791. */
  2792. Vector3.prototype.toArray = function (array, index) {
  2793. if (index === void 0) { index = 0; }
  2794. array[index] = this.x;
  2795. array[index + 1] = this.y;
  2796. array[index + 2] = this.z;
  2797. return this;
  2798. };
  2799. /**
  2800. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2801. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2802. */
  2803. Vector3.prototype.toQuaternion = function () {
  2804. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2805. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2806. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2807. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2808. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2809. var cosy = Math.cos(this.y * 0.5);
  2810. var siny = Math.sin(this.y * 0.5);
  2811. result.x = coszMinusx * siny;
  2812. result.y = -sinzMinusx * siny;
  2813. result.z = sinxPlusz * cosy;
  2814. result.w = cosxPlusz * cosy;
  2815. return result;
  2816. };
  2817. /**
  2818. * Adds the passed vector to the current Vector3
  2819. * @param otherVector defines the second operand
  2820. * @returns the current updated Vector3
  2821. */
  2822. Vector3.prototype.addInPlace = function (otherVector) {
  2823. this.x += otherVector.x;
  2824. this.y += otherVector.y;
  2825. this.z += otherVector.z;
  2826. return this;
  2827. };
  2828. /**
  2829. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2830. * @param otherVector defines the second operand
  2831. * @returns the resulting Vector3
  2832. */
  2833. Vector3.prototype.add = function (otherVector) {
  2834. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2835. };
  2836. /**
  2837. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2838. * @param otherVector defines the second operand
  2839. * @param result defines the Vector3 object where to store the result
  2840. * @returns the current Vector3
  2841. */
  2842. Vector3.prototype.addToRef = function (otherVector, result) {
  2843. result.x = this.x + otherVector.x;
  2844. result.y = this.y + otherVector.y;
  2845. result.z = this.z + otherVector.z;
  2846. return this;
  2847. };
  2848. /**
  2849. * Subtract the passed vector from the current Vector3
  2850. * @param otherVector defines the second operand
  2851. * @returns the current updated Vector3
  2852. */
  2853. Vector3.prototype.subtractInPlace = function (otherVector) {
  2854. this.x -= otherVector.x;
  2855. this.y -= otherVector.y;
  2856. this.z -= otherVector.z;
  2857. return this;
  2858. };
  2859. /**
  2860. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2861. * @param otherVector defines the second operand
  2862. * @returns the resulting Vector3
  2863. */
  2864. Vector3.prototype.subtract = function (otherVector) {
  2865. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2866. };
  2867. /**
  2868. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2869. * @param otherVector defines the second operand
  2870. * @param result defines the Vector3 object where to store the result
  2871. * @returns the current Vector3
  2872. */
  2873. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2874. result.x = this.x - otherVector.x;
  2875. result.y = this.y - otherVector.y;
  2876. result.z = this.z - otherVector.z;
  2877. return this;
  2878. };
  2879. /**
  2880. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2881. * @param x defines the x coordinate of the operand
  2882. * @param y defines the y coordinate of the operand
  2883. * @param z defines the z coordinate of the operand
  2884. * @returns the resulting Vector3
  2885. */
  2886. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2887. return new Vector3(this.x - x, this.y - y, this.z - z);
  2888. };
  2889. /**
  2890. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2891. * @param x defines the x coordinate of the operand
  2892. * @param y defines the y coordinate of the operand
  2893. * @param z defines the z coordinate of the operand
  2894. * @param result defines the Vector3 object where to store the result
  2895. * @returns the current Vector3
  2896. */
  2897. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2898. result.x = this.x - x;
  2899. result.y = this.y - y;
  2900. result.z = this.z - z;
  2901. return this;
  2902. };
  2903. /**
  2904. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2905. * @returns a new Vector3
  2906. */
  2907. Vector3.prototype.negate = function () {
  2908. return new Vector3(-this.x, -this.y, -this.z);
  2909. };
  2910. /**
  2911. * Multiplies the Vector3 coordinates by the float "scale"
  2912. * @param scale defines the multiplier factor
  2913. * @returns the current updated Vector3
  2914. */
  2915. Vector3.prototype.scaleInPlace = function (scale) {
  2916. this.x *= scale;
  2917. this.y *= scale;
  2918. this.z *= scale;
  2919. return this;
  2920. };
  2921. /**
  2922. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2923. * @param scale defines the multiplier factor
  2924. * @returns a new Vector3
  2925. */
  2926. Vector3.prototype.scale = function (scale) {
  2927. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2928. };
  2929. /**
  2930. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2931. * @param scale defines the multiplier factor
  2932. * @param result defines the Vector3 object where to store the result
  2933. * @returns the current Vector3
  2934. */
  2935. Vector3.prototype.scaleToRef = function (scale, result) {
  2936. result.x = this.x * scale;
  2937. result.y = this.y * scale;
  2938. result.z = this.z * scale;
  2939. return this;
  2940. };
  2941. /**
  2942. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2943. * @param scale defines the scale factor
  2944. * @param result defines the Vector3 object where to store the result
  2945. * @returns the unmodified current Vector3
  2946. */
  2947. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2948. result.x += this.x * scale;
  2949. result.y += this.y * scale;
  2950. result.z += this.z * scale;
  2951. return this;
  2952. };
  2953. /**
  2954. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2955. * @param otherVector defines the second operand
  2956. * @returns true if both vectors are equals
  2957. */
  2958. Vector3.prototype.equals = function (otherVector) {
  2959. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2960. };
  2961. /**
  2962. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2963. * @param otherVector defines the second operand
  2964. * @param epsilon defines the minimal distance to define values as equals
  2965. * @returns true if both vectors are distant less than epsilon
  2966. */
  2967. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2968. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2969. 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);
  2970. };
  2971. /**
  2972. * Returns true if the current Vector3 coordinates equals the passed floats
  2973. * @param x defines the x coordinate of the operand
  2974. * @param y defines the y coordinate of the operand
  2975. * @param z defines the z coordinate of the operand
  2976. * @returns true if both vectors are equals
  2977. */
  2978. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2979. return this.x === x && this.y === y && this.z === z;
  2980. };
  2981. /**
  2982. * Multiplies the current Vector3 coordinates by the passed ones
  2983. * @param otherVector defines the second operand
  2984. * @returns the current updated Vector3
  2985. */
  2986. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2987. this.x *= otherVector.x;
  2988. this.y *= otherVector.y;
  2989. this.z *= otherVector.z;
  2990. return this;
  2991. };
  2992. /**
  2993. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2994. * @param otherVector defines the second operand
  2995. * @returns the new Vector3
  2996. */
  2997. Vector3.prototype.multiply = function (otherVector) {
  2998. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2999. };
  3000. /**
  3001. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  3002. * @param otherVector defines the second operand
  3003. * @param result defines the Vector3 object where to store the result
  3004. * @returns the current Vector3
  3005. */
  3006. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3007. result.x = this.x * otherVector.x;
  3008. result.y = this.y * otherVector.y;
  3009. result.z = this.z * otherVector.z;
  3010. return this;
  3011. };
  3012. /**
  3013. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  3014. * @param x defines the x coordinate of the operand
  3015. * @param y defines the y coordinate of the operand
  3016. * @param z defines the z coordinate of the operand
  3017. * @returns the new Vector3
  3018. */
  3019. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3020. return new Vector3(this.x * x, this.y * y, this.z * z);
  3021. };
  3022. /**
  3023. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  3024. * @param otherVector defines the second operand
  3025. * @returns the new Vector3
  3026. */
  3027. Vector3.prototype.divide = function (otherVector) {
  3028. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3029. };
  3030. /**
  3031. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  3032. * @param otherVector defines the second operand
  3033. * @param result defines the Vector3 object where to store the result
  3034. * @returns the current Vector3
  3035. */
  3036. Vector3.prototype.divideToRef = function (otherVector, result) {
  3037. result.x = this.x / otherVector.x;
  3038. result.y = this.y / otherVector.y;
  3039. result.z = this.z / otherVector.z;
  3040. return this;
  3041. };
  3042. /**
  3043. * Divides the current Vector3 coordinates by the passed ones.
  3044. * @param otherVector defines the second operand
  3045. * @returns the current updated Vector3
  3046. */
  3047. Vector3.prototype.divideInPlace = function (otherVector) {
  3048. return this.divideToRef(otherVector, this);
  3049. };
  3050. /**
  3051. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  3052. * @param other defines the second operand
  3053. * @returns the current updated Vector3
  3054. */
  3055. Vector3.prototype.minimizeInPlace = function (other) {
  3056. if (other.x < this.x)
  3057. this.x = other.x;
  3058. if (other.y < this.y)
  3059. this.y = other.y;
  3060. if (other.z < this.z)
  3061. this.z = other.z;
  3062. return this;
  3063. };
  3064. /**
  3065. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  3066. * @param other defines the second operand
  3067. * @returns the current updated Vector3
  3068. */
  3069. Vector3.prototype.maximizeInPlace = function (other) {
  3070. if (other.x > this.x)
  3071. this.x = other.x;
  3072. if (other.y > this.y)
  3073. this.y = other.y;
  3074. if (other.z > this.z)
  3075. this.z = other.z;
  3076. return this;
  3077. };
  3078. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3079. /**
  3080. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3081. */
  3082. get: function () {
  3083. var absX = Math.abs(this.x);
  3084. var absY = Math.abs(this.y);
  3085. if (absX !== absY) {
  3086. return true;
  3087. }
  3088. var absZ = Math.abs(this.z);
  3089. if (absX !== absZ) {
  3090. return true;
  3091. }
  3092. if (absY !== absZ) {
  3093. return true;
  3094. }
  3095. return false;
  3096. },
  3097. enumerable: true,
  3098. configurable: true
  3099. });
  3100. // Properties
  3101. /**
  3102. * Gets the length of the Vector3
  3103. * @returns the length of the Vecto3
  3104. */
  3105. Vector3.prototype.length = function () {
  3106. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3107. };
  3108. /**
  3109. * Gets the squared length of the Vector3
  3110. * @returns squared length of the Vector3
  3111. */
  3112. Vector3.prototype.lengthSquared = function () {
  3113. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3114. };
  3115. /**
  3116. * Normalize the current Vector3.
  3117. * Please note that this is an in place operation.
  3118. * @returns the current updated Vector3
  3119. */
  3120. Vector3.prototype.normalize = function () {
  3121. var len = this.length();
  3122. if (len === 0 || len === 1.0)
  3123. return this;
  3124. var num = 1.0 / len;
  3125. this.x *= num;
  3126. this.y *= num;
  3127. this.z *= num;
  3128. return this;
  3129. };
  3130. /**
  3131. * Normalize the current Vector3 to a new vector
  3132. * @returns the new Vector3
  3133. */
  3134. Vector3.prototype.normalizeToNew = function () {
  3135. var normalized = new Vector3(0, 0, 0);
  3136. this.normalizeToRef(normalized);
  3137. return normalized;
  3138. };
  3139. /**
  3140. * Normalize the current Vector3 to the reference
  3141. * @param reference define the Vector3 to update
  3142. * @returns the updated Vector3
  3143. */
  3144. Vector3.prototype.normalizeToRef = function (reference) {
  3145. var len = this.length();
  3146. if (len === 0 || len === 1.0) {
  3147. reference.set(this.x, this.y, this.z);
  3148. return reference;
  3149. }
  3150. var scale = 1.0 / len;
  3151. this.scaleToRef(scale, reference);
  3152. return reference;
  3153. };
  3154. /**
  3155. * Creates a new Vector3 copied from the current Vector3
  3156. * @returns the new Vector3
  3157. */
  3158. Vector3.prototype.clone = function () {
  3159. return new Vector3(this.x, this.y, this.z);
  3160. };
  3161. /**
  3162. * Copies the passed vector coordinates to the current Vector3 ones
  3163. * @param source defines the source Vector3
  3164. * @returns the current updated Vector3
  3165. */
  3166. Vector3.prototype.copyFrom = function (source) {
  3167. this.x = source.x;
  3168. this.y = source.y;
  3169. this.z = source.z;
  3170. return this;
  3171. };
  3172. /**
  3173. * Copies the passed floats to the current Vector3 coordinates
  3174. * @param x defines the x coordinate of the operand
  3175. * @param y defines the y coordinate of the operand
  3176. * @param z defines the z coordinate of the operand
  3177. * @returns the current updated Vector3
  3178. */
  3179. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3180. this.x = x;
  3181. this.y = y;
  3182. this.z = z;
  3183. return this;
  3184. };
  3185. /**
  3186. * Copies the passed floats to the current Vector3 coordinates
  3187. * @param x defines the x coordinate of the operand
  3188. * @param y defines the y coordinate of the operand
  3189. * @param z defines the z coordinate of the operand
  3190. * @returns the current updated Vector3
  3191. */
  3192. Vector3.prototype.set = function (x, y, z) {
  3193. return this.copyFromFloats(x, y, z);
  3194. };
  3195. // Statics
  3196. /**
  3197. * Get the clip factor between two vectors
  3198. * @param vector0 defines the first operand
  3199. * @param vector1 defines the second operand
  3200. * @param axis defines the axis to use
  3201. * @param size defines the size along the axis
  3202. * @returns the clip factor
  3203. */
  3204. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3205. var d0 = Vector3.Dot(vector0, axis) - size;
  3206. var d1 = Vector3.Dot(vector1, axis) - size;
  3207. var s = d0 / (d0 - d1);
  3208. return s;
  3209. };
  3210. /**
  3211. * Get angle between two vectors
  3212. * @param vector0 angle between vector0 and vector1
  3213. * @param vector1 angle between vector0 and vector1
  3214. * @param normal direction of the normal
  3215. * @return the angle between vector0 and vector1
  3216. */
  3217. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3218. var v0 = vector0.clone().normalize();
  3219. var v1 = vector1.clone().normalize();
  3220. var dot = Vector3.Dot(v0, v1);
  3221. var n = Vector3.Cross(v0, v1);
  3222. if (Vector3.Dot(n, normal) > 0) {
  3223. return Math.acos(dot);
  3224. }
  3225. return -Math.acos(dot);
  3226. };
  3227. /**
  3228. * Returns a new Vector3 set from the index "offset" of the passed array
  3229. * @param array defines the source array
  3230. * @param offset defines the offset in the source array
  3231. * @returns the new Vector3
  3232. */
  3233. Vector3.FromArray = function (array, offset) {
  3234. if (!offset) {
  3235. offset = 0;
  3236. }
  3237. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3238. };
  3239. /**
  3240. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3241. * This function is deprecated. Use FromArray instead
  3242. * @param array defines the source array
  3243. * @param offset defines the offset in the source array
  3244. * @returns the new Vector3
  3245. */
  3246. Vector3.FromFloatArray = function (array, offset) {
  3247. return Vector3.FromArray(array, offset);
  3248. };
  3249. /**
  3250. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3251. * @param array defines the source array
  3252. * @param offset defines the offset in the source array
  3253. * @param result defines the Vector3 where to store the result
  3254. */
  3255. Vector3.FromArrayToRef = function (array, offset, result) {
  3256. result.x = array[offset];
  3257. result.y = array[offset + 1];
  3258. result.z = array[offset + 2];
  3259. };
  3260. /**
  3261. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3262. * This function is deprecated. Use FromArrayToRef instead.
  3263. * @param array defines the source array
  3264. * @param offset defines the offset in the source array
  3265. * @param result defines the Vector3 where to store the result
  3266. */
  3267. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3268. return Vector3.FromArrayToRef(array, offset, result);
  3269. };
  3270. /**
  3271. * Sets the passed vector "result" with the passed floats.
  3272. * @param x defines the x coordinate of the source
  3273. * @param y defines the y coordinate of the source
  3274. * @param z defines the z coordinate of the source
  3275. * @param result defines the Vector3 where to store the result
  3276. */
  3277. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3278. result.x = x;
  3279. result.y = y;
  3280. result.z = z;
  3281. };
  3282. /**
  3283. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3284. * @returns a new empty Vector3
  3285. */
  3286. Vector3.Zero = function () {
  3287. return new Vector3(0.0, 0.0, 0.0);
  3288. };
  3289. /**
  3290. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3291. * @returns a new unit Vector3
  3292. */
  3293. Vector3.One = function () {
  3294. return new Vector3(1.0, 1.0, 1.0);
  3295. };
  3296. /**
  3297. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3298. * @returns a new up Vector3
  3299. */
  3300. Vector3.Up = function () {
  3301. return new Vector3(0.0, 1.0, 0.0);
  3302. };
  3303. /**
  3304. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3305. * @returns a new forward Vector3
  3306. */
  3307. Vector3.Forward = function () {
  3308. return new Vector3(0.0, 0.0, 1.0);
  3309. };
  3310. /**
  3311. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3312. * @returns a new right Vector3
  3313. */
  3314. Vector3.Right = function () {
  3315. return new Vector3(1.0, 0.0, 0.0);
  3316. };
  3317. /**
  3318. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3319. * @returns a new left Vector3
  3320. */
  3321. Vector3.Left = function () {
  3322. return new Vector3(-1.0, 0.0, 0.0);
  3323. };
  3324. /**
  3325. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3326. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3327. * @param vector defines the Vector3 to transform
  3328. * @param transformation defines the transformation matrix
  3329. * @returns the transformed Vector3
  3330. */
  3331. Vector3.TransformCoordinates = function (vector, transformation) {
  3332. var result = Vector3.Zero();
  3333. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3334. return result;
  3335. };
  3336. /**
  3337. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3338. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3339. * @param vector defines the Vector3 to transform
  3340. * @param transformation defines the transformation matrix
  3341. * @param result defines the Vector3 where to store the result
  3342. */
  3343. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3344. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3345. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3346. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3347. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3348. result.x = x / w;
  3349. result.y = y / w;
  3350. result.z = z / w;
  3351. };
  3352. /**
  3353. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3354. * This method computes tranformed coordinates only, not transformed direction vectors
  3355. * @param x define the x coordinate of the source vector
  3356. * @param y define the y coordinate of the source vector
  3357. * @param z define the z coordinate of the source vector
  3358. * @param transformation defines the transformation matrix
  3359. * @param result defines the Vector3 where to store the result
  3360. */
  3361. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3362. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3363. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3364. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3365. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3366. result.x = rx / rw;
  3367. result.y = ry / rw;
  3368. result.z = rz / rw;
  3369. };
  3370. /**
  3371. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3372. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3373. * @param vector defines the Vector3 to transform
  3374. * @param transformation defines the transformation matrix
  3375. * @returns the new Vector3
  3376. */
  3377. Vector3.TransformNormal = function (vector, transformation) {
  3378. var result = Vector3.Zero();
  3379. Vector3.TransformNormalToRef(vector, transformation, result);
  3380. return result;
  3381. };
  3382. /**
  3383. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3384. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3385. * @param vector defines the Vector3 to transform
  3386. * @param transformation defines the transformation matrix
  3387. * @param result defines the Vector3 where to store the result
  3388. */
  3389. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3390. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3391. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3392. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3393. result.x = x;
  3394. result.y = y;
  3395. result.z = z;
  3396. };
  3397. /**
  3398. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3399. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3400. * @param x define the x coordinate of the source vector
  3401. * @param y define the y coordinate of the source vector
  3402. * @param z define the z coordinate of the source vector
  3403. * @param transformation defines the transformation matrix
  3404. * @param result defines the Vector3 where to store the result
  3405. */
  3406. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3407. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3408. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3409. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3410. };
  3411. /**
  3412. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3413. * @param value1 defines the first control point
  3414. * @param value2 defines the second control point
  3415. * @param value3 defines the third control point
  3416. * @param value4 defines the fourth control point
  3417. * @param amount defines the amount on the spline to use
  3418. * @returns the new Vector3
  3419. */
  3420. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3421. var squared = amount * amount;
  3422. var cubed = amount * squared;
  3423. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3424. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3425. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3426. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3427. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3428. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3429. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3430. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3431. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3432. return new Vector3(x, y, z);
  3433. };
  3434. /**
  3435. * 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"
  3436. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3437. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3438. * @param value defines the current value
  3439. * @param min defines the lower range value
  3440. * @param max defines the upper range value
  3441. * @returns the new Vector3
  3442. */
  3443. Vector3.Clamp = function (value, min, max) {
  3444. var x = value.x;
  3445. x = (x > max.x) ? max.x : x;
  3446. x = (x < min.x) ? min.x : x;
  3447. var y = value.y;
  3448. y = (y > max.y) ? max.y : y;
  3449. y = (y < min.y) ? min.y : y;
  3450. var z = value.z;
  3451. z = (z > max.z) ? max.z : z;
  3452. z = (z < min.z) ? min.z : z;
  3453. return new Vector3(x, y, z);
  3454. };
  3455. /**
  3456. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3457. * @param value1 defines the first control point
  3458. * @param tangent1 defines the first tangent vector
  3459. * @param value2 defines the second control point
  3460. * @param tangent2 defines the second tangent vector
  3461. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3462. * @returns the new Vector3
  3463. */
  3464. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3465. var squared = amount * amount;
  3466. var cubed = amount * squared;
  3467. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3468. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3469. var part3 = (cubed - (2.0 * squared)) + amount;
  3470. var part4 = cubed - squared;
  3471. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3472. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3473. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3474. return new Vector3(x, y, z);
  3475. };
  3476. /**
  3477. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3478. * @param start defines the start value
  3479. * @param end defines the end value
  3480. * @param amount max defines amount between both (between 0 and 1)
  3481. * @returns the new Vector3
  3482. */
  3483. Vector3.Lerp = function (start, end, amount) {
  3484. var result = new Vector3(0, 0, 0);
  3485. Vector3.LerpToRef(start, end, amount, result);
  3486. return result;
  3487. };
  3488. /**
  3489. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3490. * @param start defines the start value
  3491. * @param end defines the end value
  3492. * @param amount max defines amount between both (between 0 and 1)
  3493. * @param result defines the Vector3 where to store the result
  3494. */
  3495. Vector3.LerpToRef = function (start, end, amount, result) {
  3496. result.x = start.x + ((end.x - start.x) * amount);
  3497. result.y = start.y + ((end.y - start.y) * amount);
  3498. result.z = start.z + ((end.z - start.z) * amount);
  3499. };
  3500. /**
  3501. * Returns the dot product (float) between the vectors "left" and "right"
  3502. * @param left defines the left operand
  3503. * @param right defines the right operand
  3504. * @returns the dot product
  3505. */
  3506. Vector3.Dot = function (left, right) {
  3507. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3508. };
  3509. /**
  3510. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3511. * The cross product is then orthogonal to both "left" and "right"
  3512. * @param left defines the left operand
  3513. * @param right defines the right operand
  3514. * @returns the cross product
  3515. */
  3516. Vector3.Cross = function (left, right) {
  3517. var result = Vector3.Zero();
  3518. Vector3.CrossToRef(left, right, result);
  3519. return result;
  3520. };
  3521. /**
  3522. * Sets the passed vector "result" with the cross product of "left" and "right"
  3523. * The cross product is then orthogonal to both "left" and "right"
  3524. * @param left defines the left operand
  3525. * @param right defines the right operand
  3526. * @param result defines the Vector3 where to store the result
  3527. */
  3528. Vector3.CrossToRef = function (left, right, result) {
  3529. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3530. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3531. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3532. result.copyFrom(MathTmp.Vector3[0]);
  3533. };
  3534. /**
  3535. * Returns a new Vector3 as the normalization of the passed vector
  3536. * @param vector defines the Vector3 to normalize
  3537. * @returns the new Vector3
  3538. */
  3539. Vector3.Normalize = function (vector) {
  3540. var result = Vector3.Zero();
  3541. Vector3.NormalizeToRef(vector, result);
  3542. return result;
  3543. };
  3544. /**
  3545. * Sets the passed vector "result" with the normalization of the passed first vector
  3546. * @param vector defines the Vector3 to normalize
  3547. * @param result defines the Vector3 where to store the result
  3548. */
  3549. Vector3.NormalizeToRef = function (vector, result) {
  3550. result.copyFrom(vector);
  3551. result.normalize();
  3552. };
  3553. /**
  3554. * Project a Vector3 onto screen space
  3555. * @param vector defines the Vector3 to project
  3556. * @param world defines the world matrix to use
  3557. * @param transform defines the transform (view x projection) matrix to use
  3558. * @param viewport defines the screen viewport to use
  3559. * @returns the new Vector3
  3560. */
  3561. Vector3.Project = function (vector, world, transform, viewport) {
  3562. var cw = viewport.width;
  3563. var ch = viewport.height;
  3564. var cx = viewport.x;
  3565. var cy = viewport.y;
  3566. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3567. 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);
  3568. var matrix = MathTmp.Matrix[0];
  3569. world.multiplyToRef(transform, matrix);
  3570. matrix.multiplyToRef(viewportMatrix, matrix);
  3571. return Vector3.TransformCoordinates(vector, matrix);
  3572. };
  3573. /**
  3574. * Unproject from screen space to object space
  3575. * @param source defines the screen space Vector3 to use
  3576. * @param viewportWidth defines the current width of the viewport
  3577. * @param viewportHeight defines the current height of the viewport
  3578. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3579. * @param transform defines the transform (view x projection) matrix to use
  3580. * @returns the new Vector3
  3581. */
  3582. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3583. var matrix = MathTmp.Matrix[0];
  3584. world.multiplyToRef(transform, matrix);
  3585. matrix.invert();
  3586. source.x = source.x / viewportWidth * 2 - 1;
  3587. source.y = -(source.y / viewportHeight * 2 - 1);
  3588. var vector = Vector3.TransformCoordinates(source, matrix);
  3589. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3590. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3591. vector = vector.scale(1.0 / num);
  3592. }
  3593. return vector;
  3594. };
  3595. /**
  3596. * Unproject from screen space to object space
  3597. * @param source defines the screen space Vector3 to use
  3598. * @param viewportWidth defines the current width of the viewport
  3599. * @param viewportHeight defines the current height of the viewport
  3600. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3601. * @param view defines the view matrix to use
  3602. * @param projection defines the projection matrix to use
  3603. * @returns the new Vector3
  3604. */
  3605. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3606. var result = Vector3.Zero();
  3607. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3608. return result;
  3609. };
  3610. /**
  3611. * Unproject from screen space to object space
  3612. * @param source defines the screen space Vector3 to use
  3613. * @param viewportWidth defines the current width of the viewport
  3614. * @param viewportHeight defines the current height of the viewport
  3615. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3616. * @param view defines the view matrix to use
  3617. * @param projection defines the projection matrix to use
  3618. * @param result defines the Vector3 where to store the result
  3619. */
  3620. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3621. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3622. };
  3623. /**
  3624. * Unproject from screen space to object space
  3625. * @param sourceX defines the screen space x coordinate to use
  3626. * @param sourceY defines the screen space y coordinate to use
  3627. * @param sourceZ defines the screen space z coordinate to use
  3628. * @param viewportWidth defines the current width of the viewport
  3629. * @param viewportHeight defines the current height of the viewport
  3630. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3631. * @param view defines the view matrix to use
  3632. * @param projection defines the projection matrix to use
  3633. * @param result defines the Vector3 where to store the result
  3634. */
  3635. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3636. var matrix = MathTmp.Matrix[0];
  3637. world.multiplyToRef(view, matrix);
  3638. matrix.multiplyToRef(projection, matrix);
  3639. matrix.invert();
  3640. var screenSource = MathTmp.Vector3[0];
  3641. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3642. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3643. screenSource.z = 2 * sourceZ - 1.0;
  3644. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3645. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3646. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3647. result.scaleInPlace(1.0 / num);
  3648. }
  3649. };
  3650. /**
  3651. * Gets the minimal coordinate values between two Vector3
  3652. * @param left defines the first operand
  3653. * @param right defines the second operand
  3654. * @returns the new Vector3
  3655. */
  3656. Vector3.Minimize = function (left, right) {
  3657. var min = left.clone();
  3658. min.minimizeInPlace(right);
  3659. return min;
  3660. };
  3661. /**
  3662. * Gets the maximal coordinate values between two Vector3
  3663. * @param left defines the first operand
  3664. * @param right defines the second operand
  3665. * @returns the new Vector3
  3666. */
  3667. Vector3.Maximize = function (left, right) {
  3668. var max = left.clone();
  3669. max.maximizeInPlace(right);
  3670. return max;
  3671. };
  3672. /**
  3673. * Returns the distance between the vectors "value1" and "value2"
  3674. * @param value1 defines the first operand
  3675. * @param value2 defines the second operand
  3676. * @returns the distance
  3677. */
  3678. Vector3.Distance = function (value1, value2) {
  3679. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3680. };
  3681. /**
  3682. * Returns the squared distance between the vectors "value1" and "value2"
  3683. * @param value1 defines the first operand
  3684. * @param value2 defines the second operand
  3685. * @returns the squared distance
  3686. */
  3687. Vector3.DistanceSquared = function (value1, value2) {
  3688. var x = value1.x - value2.x;
  3689. var y = value1.y - value2.y;
  3690. var z = value1.z - value2.z;
  3691. return (x * x) + (y * y) + (z * z);
  3692. };
  3693. /**
  3694. * Returns a new Vector3 located at the center between "value1" and "value2"
  3695. * @param value1 defines the first operand
  3696. * @param value2 defines the second operand
  3697. * @returns the new Vector3
  3698. */
  3699. Vector3.Center = function (value1, value2) {
  3700. var center = value1.add(value2);
  3701. center.scaleInPlace(0.5);
  3702. return center;
  3703. };
  3704. /**
  3705. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3706. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3707. * to something in order to rotate it from its local system to the given target system
  3708. * Note: axis1, axis2 and axis3 are normalized during this operation
  3709. * @param axis1 defines the first axis
  3710. * @param axis2 defines the second axis
  3711. * @param axis3 defines the third axis
  3712. * @returns a new Vector3
  3713. */
  3714. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3715. var rotation = Vector3.Zero();
  3716. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3717. return rotation;
  3718. };
  3719. /**
  3720. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3721. * @param axis1 defines the first axis
  3722. * @param axis2 defines the second axis
  3723. * @param axis3 defines the third axis
  3724. * @param ref defines the Vector3 where to store the result
  3725. */
  3726. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3727. var quat = MathTmp.Quaternion[0];
  3728. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3729. quat.toEulerAnglesToRef(ref);
  3730. };
  3731. return Vector3;
  3732. }());
  3733. BABYLON.Vector3 = Vector3;
  3734. //Vector4 class created for EulerAngle class conversion to Quaternion
  3735. var Vector4 = /** @class */ (function () {
  3736. /**
  3737. * Creates a Vector4 object from the passed floats.
  3738. */
  3739. function Vector4(x, y, z, w) {
  3740. this.x = x;
  3741. this.y = y;
  3742. this.z = z;
  3743. this.w = w;
  3744. }
  3745. /**
  3746. * Returns the string with the Vector4 coordinates.
  3747. */
  3748. Vector4.prototype.toString = function () {
  3749. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3750. };
  3751. /**
  3752. * Returns the string "Vector4".
  3753. */
  3754. Vector4.prototype.getClassName = function () {
  3755. return "Vector4";
  3756. };
  3757. /**
  3758. * Returns the Vector4 hash code.
  3759. */
  3760. Vector4.prototype.getHashCode = function () {
  3761. var hash = this.x || 0;
  3762. hash = (hash * 397) ^ (this.y || 0);
  3763. hash = (hash * 397) ^ (this.z || 0);
  3764. hash = (hash * 397) ^ (this.w || 0);
  3765. return hash;
  3766. };
  3767. // Operators
  3768. /**
  3769. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3770. */
  3771. Vector4.prototype.asArray = function () {
  3772. var result = new Array();
  3773. this.toArray(result, 0);
  3774. return result;
  3775. };
  3776. /**
  3777. * Populates the passed array from the passed index with the Vector4 coordinates.
  3778. * Returns the Vector4.
  3779. */
  3780. Vector4.prototype.toArray = function (array, index) {
  3781. if (index === undefined) {
  3782. index = 0;
  3783. }
  3784. array[index] = this.x;
  3785. array[index + 1] = this.y;
  3786. array[index + 2] = this.z;
  3787. array[index + 3] = this.w;
  3788. return this;
  3789. };
  3790. /**
  3791. * Adds the passed vector to the current Vector4.
  3792. * Returns the updated Vector4.
  3793. */
  3794. Vector4.prototype.addInPlace = function (otherVector) {
  3795. this.x += otherVector.x;
  3796. this.y += otherVector.y;
  3797. this.z += otherVector.z;
  3798. this.w += otherVector.w;
  3799. return this;
  3800. };
  3801. /**
  3802. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3803. */
  3804. Vector4.prototype.add = function (otherVector) {
  3805. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3806. };
  3807. /**
  3808. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3809. * Returns the current Vector4.
  3810. */
  3811. Vector4.prototype.addToRef = function (otherVector, result) {
  3812. result.x = this.x + otherVector.x;
  3813. result.y = this.y + otherVector.y;
  3814. result.z = this.z + otherVector.z;
  3815. result.w = this.w + otherVector.w;
  3816. return this;
  3817. };
  3818. /**
  3819. * Subtract in place the passed vector from the current Vector4.
  3820. * Returns the updated Vector4.
  3821. */
  3822. Vector4.prototype.subtractInPlace = function (otherVector) {
  3823. this.x -= otherVector.x;
  3824. this.y -= otherVector.y;
  3825. this.z -= otherVector.z;
  3826. this.w -= otherVector.w;
  3827. return this;
  3828. };
  3829. /**
  3830. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3831. */
  3832. Vector4.prototype.subtract = function (otherVector) {
  3833. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3834. };
  3835. /**
  3836. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3837. * Returns the current Vector4.
  3838. */
  3839. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3840. result.x = this.x - otherVector.x;
  3841. result.y = this.y - otherVector.y;
  3842. result.z = this.z - otherVector.z;
  3843. result.w = this.w - otherVector.w;
  3844. return this;
  3845. };
  3846. /**
  3847. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3848. */
  3849. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3850. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3851. };
  3852. /**
  3853. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3854. * Returns the current Vector4.
  3855. */
  3856. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3857. result.x = this.x - x;
  3858. result.y = this.y - y;
  3859. result.z = this.z - z;
  3860. result.w = this.w - w;
  3861. return this;
  3862. };
  3863. /**
  3864. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3865. */
  3866. Vector4.prototype.negate = function () {
  3867. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3868. };
  3869. /**
  3870. * Multiplies the current Vector4 coordinates by scale (float).
  3871. * Returns the updated Vector4.
  3872. */
  3873. Vector4.prototype.scaleInPlace = function (scale) {
  3874. this.x *= scale;
  3875. this.y *= scale;
  3876. this.z *= scale;
  3877. this.w *= scale;
  3878. return this;
  3879. };
  3880. /**
  3881. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3882. */
  3883. Vector4.prototype.scale = function (scale) {
  3884. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3885. };
  3886. /**
  3887. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3888. * Returns the current Vector4.
  3889. */
  3890. Vector4.prototype.scaleToRef = function (scale, result) {
  3891. result.x = this.x * scale;
  3892. result.y = this.y * scale;
  3893. result.z = this.z * scale;
  3894. result.w = this.w * scale;
  3895. return this;
  3896. };
  3897. /**
  3898. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3899. * @param scale defines the scale factor
  3900. * @param result defines the Vector4 object where to store the result
  3901. * @returns the unmodified current Vector4
  3902. */
  3903. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3904. result.x += this.x * scale;
  3905. result.y += this.y * scale;
  3906. result.z += this.z * scale;
  3907. result.w += this.w * scale;
  3908. return this;
  3909. };
  3910. /**
  3911. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3912. */
  3913. Vector4.prototype.equals = function (otherVector) {
  3914. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3915. };
  3916. /**
  3917. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3918. */
  3919. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3920. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3921. return otherVector
  3922. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3923. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3924. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3925. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3926. };
  3927. /**
  3928. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3929. */
  3930. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3931. return this.x === x && this.y === y && this.z === z && this.w === w;
  3932. };
  3933. /**
  3934. * Multiplies in place the current Vector4 by the passed one.
  3935. * Returns the updated Vector4.
  3936. */
  3937. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3938. this.x *= otherVector.x;
  3939. this.y *= otherVector.y;
  3940. this.z *= otherVector.z;
  3941. this.w *= otherVector.w;
  3942. return this;
  3943. };
  3944. /**
  3945. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3946. */
  3947. Vector4.prototype.multiply = function (otherVector) {
  3948. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3949. };
  3950. /**
  3951. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3952. * Returns the current Vector4.
  3953. */
  3954. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3955. result.x = this.x * otherVector.x;
  3956. result.y = this.y * otherVector.y;
  3957. result.z = this.z * otherVector.z;
  3958. result.w = this.w * otherVector.w;
  3959. return this;
  3960. };
  3961. /**
  3962. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3963. */
  3964. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3965. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3966. };
  3967. /**
  3968. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3969. */
  3970. Vector4.prototype.divide = function (otherVector) {
  3971. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3972. };
  3973. /**
  3974. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3975. * Returns the current Vector4.
  3976. */
  3977. Vector4.prototype.divideToRef = function (otherVector, result) {
  3978. result.x = this.x / otherVector.x;
  3979. result.y = this.y / otherVector.y;
  3980. result.z = this.z / otherVector.z;
  3981. result.w = this.w / otherVector.w;
  3982. return this;
  3983. };
  3984. /**
  3985. * Divides the current Vector3 coordinates by the passed ones.
  3986. * @returns the updated Vector3.
  3987. */
  3988. Vector4.prototype.divideInPlace = function (otherVector) {
  3989. return this.divideToRef(otherVector, this);
  3990. };
  3991. /**
  3992. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3993. * @param other defines the second operand
  3994. * @returns the current updated Vector4
  3995. */
  3996. Vector4.prototype.minimizeInPlace = function (other) {
  3997. if (other.x < this.x)
  3998. this.x = other.x;
  3999. if (other.y < this.y)
  4000. this.y = other.y;
  4001. if (other.z < this.z)
  4002. this.z = other.z;
  4003. if (other.w < this.w)
  4004. this.w = other.w;
  4005. return this;
  4006. };
  4007. /**
  4008. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  4009. * @param other defines the second operand
  4010. * @returns the current updated Vector4
  4011. */
  4012. Vector4.prototype.maximizeInPlace = function (other) {
  4013. if (other.x > this.x)
  4014. this.x = other.x;
  4015. if (other.y > this.y)
  4016. this.y = other.y;
  4017. if (other.z > this.z)
  4018. this.z = other.z;
  4019. if (other.w > this.w)
  4020. this.w = other.w;
  4021. return this;
  4022. };
  4023. // Properties
  4024. /**
  4025. * Returns the Vector4 length (float).
  4026. */
  4027. Vector4.prototype.length = function () {
  4028. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4029. };
  4030. /**
  4031. * Returns the Vector4 squared length (float).
  4032. */
  4033. Vector4.prototype.lengthSquared = function () {
  4034. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4035. };
  4036. // Methods
  4037. /**
  4038. * Normalizes in place the Vector4.
  4039. * Returns the updated Vector4.
  4040. */
  4041. Vector4.prototype.normalize = function () {
  4042. var len = this.length();
  4043. if (len === 0)
  4044. return this;
  4045. var num = 1.0 / len;
  4046. this.x *= num;
  4047. this.y *= num;
  4048. this.z *= num;
  4049. this.w *= num;
  4050. return this;
  4051. };
  4052. /**
  4053. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4054. */
  4055. Vector4.prototype.toVector3 = function () {
  4056. return new Vector3(this.x, this.y, this.z);
  4057. };
  4058. /**
  4059. * Returns a new Vector4 copied from the current one.
  4060. */
  4061. Vector4.prototype.clone = function () {
  4062. return new Vector4(this.x, this.y, this.z, this.w);
  4063. };
  4064. /**
  4065. * Updates the current Vector4 with the passed one coordinates.
  4066. * Returns the updated Vector4.
  4067. */
  4068. Vector4.prototype.copyFrom = function (source) {
  4069. this.x = source.x;
  4070. this.y = source.y;
  4071. this.z = source.z;
  4072. this.w = source.w;
  4073. return this;
  4074. };
  4075. /**
  4076. * Updates the current Vector4 coordinates with the passed floats.
  4077. * Returns the updated Vector4.
  4078. */
  4079. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4080. this.x = x;
  4081. this.y = y;
  4082. this.z = z;
  4083. this.w = w;
  4084. return this;
  4085. };
  4086. /**
  4087. * Updates the current Vector4 coordinates with the passed floats.
  4088. * Returns the updated Vector4.
  4089. */
  4090. Vector4.prototype.set = function (x, y, z, w) {
  4091. return this.copyFromFloats(x, y, z, w);
  4092. };
  4093. // Statics
  4094. /**
  4095. * Returns a new Vector4 set from the starting index of the passed array.
  4096. */
  4097. Vector4.FromArray = function (array, offset) {
  4098. if (!offset) {
  4099. offset = 0;
  4100. }
  4101. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4102. };
  4103. /**
  4104. * Updates the passed vector "result" from the starting index of the passed array.
  4105. */
  4106. Vector4.FromArrayToRef = function (array, offset, result) {
  4107. result.x = array[offset];
  4108. result.y = array[offset + 1];
  4109. result.z = array[offset + 2];
  4110. result.w = array[offset + 3];
  4111. };
  4112. /**
  4113. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  4114. */
  4115. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4116. Vector4.FromArrayToRef(array, offset, result);
  4117. };
  4118. /**
  4119. * Updates the passed vector "result" coordinates from the passed floats.
  4120. */
  4121. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4122. result.x = x;
  4123. result.y = y;
  4124. result.z = z;
  4125. result.w = w;
  4126. };
  4127. /**
  4128. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4129. */
  4130. Vector4.Zero = function () {
  4131. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4132. };
  4133. /**
  4134. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4135. */
  4136. Vector4.One = function () {
  4137. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4138. };
  4139. /**
  4140. * Returns a new normalized Vector4 from the passed one.
  4141. */
  4142. Vector4.Normalize = function (vector) {
  4143. var result = Vector4.Zero();
  4144. Vector4.NormalizeToRef(vector, result);
  4145. return result;
  4146. };
  4147. /**
  4148. * Updates the passed vector "result" from the normalization of the passed one.
  4149. */
  4150. Vector4.NormalizeToRef = function (vector, result) {
  4151. result.copyFrom(vector);
  4152. result.normalize();
  4153. };
  4154. Vector4.Minimize = function (left, right) {
  4155. var min = left.clone();
  4156. min.minimizeInPlace(right);
  4157. return min;
  4158. };
  4159. Vector4.Maximize = function (left, right) {
  4160. var max = left.clone();
  4161. max.maximizeInPlace(right);
  4162. return max;
  4163. };
  4164. /**
  4165. * Returns the distance (float) between the vectors "value1" and "value2".
  4166. */
  4167. Vector4.Distance = function (value1, value2) {
  4168. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4169. };
  4170. /**
  4171. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4172. */
  4173. Vector4.DistanceSquared = function (value1, value2) {
  4174. var x = value1.x - value2.x;
  4175. var y = value1.y - value2.y;
  4176. var z = value1.z - value2.z;
  4177. var w = value1.w - value2.w;
  4178. return (x * x) + (y * y) + (z * z) + (w * w);
  4179. };
  4180. /**
  4181. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4182. */
  4183. Vector4.Center = function (value1, value2) {
  4184. var center = value1.add(value2);
  4185. center.scaleInPlace(0.5);
  4186. return center;
  4187. };
  4188. /**
  4189. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  4190. * This methods computes transformed normalized direction vectors only.
  4191. */
  4192. Vector4.TransformNormal = function (vector, transformation) {
  4193. var result = Vector4.Zero();
  4194. Vector4.TransformNormalToRef(vector, transformation, result);
  4195. return result;
  4196. };
  4197. /**
  4198. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  4199. * This methods computes transformed normalized direction vectors only.
  4200. */
  4201. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4202. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4203. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4204. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4205. result.x = x;
  4206. result.y = y;
  4207. result.z = z;
  4208. result.w = vector.w;
  4209. };
  4210. /**
  4211. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4212. * This methods computes transformed normalized direction vectors only.
  4213. */
  4214. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4215. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4216. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4217. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4218. result.w = w;
  4219. };
  4220. return Vector4;
  4221. }());
  4222. BABYLON.Vector4 = Vector4;
  4223. var Size = /** @class */ (function () {
  4224. /**
  4225. * Creates a Size object from the passed width and height (floats).
  4226. */
  4227. function Size(width, height) {
  4228. this.width = width;
  4229. this.height = height;
  4230. }
  4231. // Returns a string with the Size width and height.
  4232. Size.prototype.toString = function () {
  4233. return "{W: " + this.width + ", H: " + this.height + "}";
  4234. };
  4235. /**
  4236. * Returns the string "Size"
  4237. */
  4238. Size.prototype.getClassName = function () {
  4239. return "Size";
  4240. };
  4241. /**
  4242. * Returns the Size hash code.
  4243. */
  4244. Size.prototype.getHashCode = function () {
  4245. var hash = this.width || 0;
  4246. hash = (hash * 397) ^ (this.height || 0);
  4247. return hash;
  4248. };
  4249. /**
  4250. * Updates the current size from the passed one.
  4251. * Returns the updated Size.
  4252. */
  4253. Size.prototype.copyFrom = function (src) {
  4254. this.width = src.width;
  4255. this.height = src.height;
  4256. };
  4257. /**
  4258. * Updates in place the current Size from the passed floats.
  4259. * Returns the updated Size.
  4260. */
  4261. Size.prototype.copyFromFloats = function (width, height) {
  4262. this.width = width;
  4263. this.height = height;
  4264. return this;
  4265. };
  4266. /**
  4267. * Updates in place the current Size from the passed floats.
  4268. * Returns the updated Size.
  4269. */
  4270. Size.prototype.set = function (width, height) {
  4271. return this.copyFromFloats(width, height);
  4272. };
  4273. /**
  4274. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4275. */
  4276. Size.prototype.multiplyByFloats = function (w, h) {
  4277. return new Size(this.width * w, this.height * h);
  4278. };
  4279. /**
  4280. * Returns a new Size copied from the passed one.
  4281. */
  4282. Size.prototype.clone = function () {
  4283. return new Size(this.width, this.height);
  4284. };
  4285. /**
  4286. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4287. */
  4288. Size.prototype.equals = function (other) {
  4289. if (!other) {
  4290. return false;
  4291. }
  4292. return (this.width === other.width) && (this.height === other.height);
  4293. };
  4294. Object.defineProperty(Size.prototype, "surface", {
  4295. /**
  4296. * Returns the surface of the Size : width * height (float).
  4297. */
  4298. get: function () {
  4299. return this.width * this.height;
  4300. },
  4301. enumerable: true,
  4302. configurable: true
  4303. });
  4304. /**
  4305. * Returns a new Size set to (0.0, 0.0)
  4306. */
  4307. Size.Zero = function () {
  4308. return new Size(0.0, 0.0);
  4309. };
  4310. /**
  4311. * Returns a new Size set as the addition result of the current Size and the passed one.
  4312. */
  4313. Size.prototype.add = function (otherSize) {
  4314. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4315. return r;
  4316. };
  4317. /**
  4318. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4319. */
  4320. Size.prototype.subtract = function (otherSize) {
  4321. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4322. return r;
  4323. };
  4324. /**
  4325. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4326. */
  4327. Size.Lerp = function (start, end, amount) {
  4328. var w = start.width + ((end.width - start.width) * amount);
  4329. var h = start.height + ((end.height - start.height) * amount);
  4330. return new Size(w, h);
  4331. };
  4332. return Size;
  4333. }());
  4334. BABYLON.Size = Size;
  4335. var Quaternion = /** @class */ (function () {
  4336. /**
  4337. * Creates a new Quaternion from the passed floats.
  4338. */
  4339. function Quaternion(x, y, z, w) {
  4340. if (x === void 0) { x = 0.0; }
  4341. if (y === void 0) { y = 0.0; }
  4342. if (z === void 0) { z = 0.0; }
  4343. if (w === void 0) { w = 1.0; }
  4344. this.x = x;
  4345. this.y = y;
  4346. this.z = z;
  4347. this.w = w;
  4348. }
  4349. /**
  4350. * Returns a string with the Quaternion coordinates.
  4351. */
  4352. Quaternion.prototype.toString = function () {
  4353. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4354. };
  4355. /**
  4356. * Returns the string "Quaternion".
  4357. */
  4358. Quaternion.prototype.getClassName = function () {
  4359. return "Quaternion";
  4360. };
  4361. /**
  4362. * Returns the Quaternion hash code.
  4363. */
  4364. Quaternion.prototype.getHashCode = function () {
  4365. var hash = this.x || 0;
  4366. hash = (hash * 397) ^ (this.y || 0);
  4367. hash = (hash * 397) ^ (this.z || 0);
  4368. hash = (hash * 397) ^ (this.w || 0);
  4369. return hash;
  4370. };
  4371. /**
  4372. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4373. */
  4374. Quaternion.prototype.asArray = function () {
  4375. return [this.x, this.y, this.z, this.w];
  4376. };
  4377. /**
  4378. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4379. */
  4380. Quaternion.prototype.equals = function (otherQuaternion) {
  4381. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4382. };
  4383. /**
  4384. * Returns a new Quaternion copied from the current one.
  4385. */
  4386. Quaternion.prototype.clone = function () {
  4387. return new Quaternion(this.x, this.y, this.z, this.w);
  4388. };
  4389. /**
  4390. * Updates the current Quaternion from the passed one coordinates.
  4391. * Returns the updated Quaterion.
  4392. */
  4393. Quaternion.prototype.copyFrom = function (other) {
  4394. this.x = other.x;
  4395. this.y = other.y;
  4396. this.z = other.z;
  4397. this.w = other.w;
  4398. return this;
  4399. };
  4400. /**
  4401. * Updates the current Quaternion from the passed float coordinates.
  4402. * Returns the updated Quaterion.
  4403. */
  4404. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4405. this.x = x;
  4406. this.y = y;
  4407. this.z = z;
  4408. this.w = w;
  4409. return this;
  4410. };
  4411. /**
  4412. * Updates the current Quaternion from the passed float coordinates.
  4413. * Returns the updated Quaterion.
  4414. */
  4415. Quaternion.prototype.set = function (x, y, z, w) {
  4416. return this.copyFromFloats(x, y, z, w);
  4417. };
  4418. /**
  4419. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4420. */
  4421. Quaternion.prototype.add = function (other) {
  4422. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4423. };
  4424. /**
  4425. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4426. */
  4427. Quaternion.prototype.subtract = function (other) {
  4428. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4429. };
  4430. /**
  4431. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4432. */
  4433. Quaternion.prototype.scale = function (value) {
  4434. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4435. };
  4436. /**
  4437. * Scale the current Quaternion values by a factor to a given Quaternion
  4438. * @param scale defines the scale factor
  4439. * @param result defines the Quaternion object where to store the result
  4440. * @returns the unmodified current Quaternion
  4441. */
  4442. Quaternion.prototype.scaleToRef = function (scale, result) {
  4443. result.x = this.x * scale;
  4444. result.y = this.y * scale;
  4445. result.z = this.z * scale;
  4446. result.w = this.w * scale;
  4447. return this;
  4448. };
  4449. /**
  4450. * Scale the current Quaternion values by a factor and add the result to a given Quaternion
  4451. * @param scale defines the scale factor
  4452. * @param result defines the Quaternion object where to store the result
  4453. * @returns the unmodified current Quaternion
  4454. */
  4455. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4456. result.x += this.x * scale;
  4457. result.y += this.y * scale;
  4458. result.z += this.z * scale;
  4459. result.w += this.w * scale;
  4460. return this;
  4461. };
  4462. /**
  4463. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4464. */
  4465. Quaternion.prototype.multiply = function (q1) {
  4466. var result = new Quaternion(0, 0, 0, 1.0);
  4467. this.multiplyToRef(q1, result);
  4468. return result;
  4469. };
  4470. /**
  4471. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4472. * Returns the current Quaternion.
  4473. */
  4474. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4475. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4476. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4477. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4478. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4479. result.copyFromFloats(x, y, z, w);
  4480. return this;
  4481. };
  4482. /**
  4483. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4484. * Returns the updated Quaternion.
  4485. */
  4486. Quaternion.prototype.multiplyInPlace = function (q1) {
  4487. this.multiplyToRef(q1, this);
  4488. return this;
  4489. };
  4490. /**
  4491. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4492. * Returns the current Quaternion.
  4493. */
  4494. Quaternion.prototype.conjugateToRef = function (ref) {
  4495. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4496. return this;
  4497. };
  4498. /**
  4499. * Conjugates in place the current Quaternion.
  4500. * Returns the updated Quaternion.
  4501. */
  4502. Quaternion.prototype.conjugateInPlace = function () {
  4503. this.x *= -1;
  4504. this.y *= -1;
  4505. this.z *= -1;
  4506. return this;
  4507. };
  4508. /**
  4509. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4510. */
  4511. Quaternion.prototype.conjugate = function () {
  4512. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4513. return result;
  4514. };
  4515. /**
  4516. * Returns the Quaternion length (float).
  4517. */
  4518. Quaternion.prototype.length = function () {
  4519. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4520. };
  4521. /**
  4522. * Normalize in place the current Quaternion.
  4523. * Returns the updated Quaternion.
  4524. */
  4525. Quaternion.prototype.normalize = function () {
  4526. var length = 1.0 / this.length();
  4527. this.x *= length;
  4528. this.y *= length;
  4529. this.z *= length;
  4530. this.w *= length;
  4531. return this;
  4532. };
  4533. /**
  4534. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion
  4535. * @param order is a reserved parameter and is ignore for now
  4536. * @returns the new Vector3
  4537. */
  4538. Quaternion.prototype.toEulerAngles = function (order) {
  4539. if (order === void 0) { order = "YZX"; }
  4540. var result = Vector3.Zero();
  4541. this.toEulerAnglesToRef(result, order);
  4542. return result;
  4543. };
  4544. /**
  4545. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion
  4546. * @param result defines the vector which will be filled with the Euler angles
  4547. * @param order is a reserved parameter and is ignore for now
  4548. * @returns the current Quaternion
  4549. */
  4550. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4551. if (order === void 0) { order = "YZX"; }
  4552. var qz = this.z;
  4553. var qx = this.x;
  4554. var qy = this.y;
  4555. var qw = this.w;
  4556. var sqw = qw * qw;
  4557. var sqz = qz * qz;
  4558. var sqx = qx * qx;
  4559. var sqy = qy * qy;
  4560. var zAxisY = qy * qz - qx * qw;
  4561. var limit = .4999999;
  4562. if (zAxisY < -limit) {
  4563. result.y = 2 * Math.atan2(qy, qw);
  4564. result.x = Math.PI / 2;
  4565. result.z = 0;
  4566. }
  4567. else if (zAxisY > limit) {
  4568. result.y = 2 * Math.atan2(qy, qw);
  4569. result.x = -Math.PI / 2;
  4570. result.z = 0;
  4571. }
  4572. else {
  4573. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4574. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4575. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4576. }
  4577. return this;
  4578. };
  4579. /**
  4580. * Updates the passed rotation matrix with the current Quaternion values.
  4581. * Returns the current Quaternion.
  4582. */
  4583. Quaternion.prototype.toRotationMatrix = function (result) {
  4584. var xx = this.x * this.x;
  4585. var yy = this.y * this.y;
  4586. var zz = this.z * this.z;
  4587. var xy = this.x * this.y;
  4588. var zw = this.z * this.w;
  4589. var zx = this.z * this.x;
  4590. var yw = this.y * this.w;
  4591. var yz = this.y * this.z;
  4592. var xw = this.x * this.w;
  4593. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4594. result.m[1] = 2.0 * (xy + zw);
  4595. result.m[2] = 2.0 * (zx - yw);
  4596. result.m[3] = 0;
  4597. result.m[4] = 2.0 * (xy - zw);
  4598. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4599. result.m[6] = 2.0 * (yz + xw);
  4600. result.m[7] = 0;
  4601. result.m[8] = 2.0 * (zx + yw);
  4602. result.m[9] = 2.0 * (yz - xw);
  4603. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4604. result.m[11] = 0;
  4605. result.m[12] = 0;
  4606. result.m[13] = 0;
  4607. result.m[14] = 0;
  4608. result.m[15] = 1.0;
  4609. result._markAsUpdated();
  4610. return this;
  4611. };
  4612. /**
  4613. * Updates the current Quaternion from the passed rotation matrix values.
  4614. * Returns the updated Quaternion.
  4615. */
  4616. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4617. Quaternion.FromRotationMatrixToRef(matrix, this);
  4618. return this;
  4619. };
  4620. // Statics
  4621. /**
  4622. * Returns a new Quaternion set from the passed rotation matrix values.
  4623. */
  4624. Quaternion.FromRotationMatrix = function (matrix) {
  4625. var result = new Quaternion();
  4626. Quaternion.FromRotationMatrixToRef(matrix, result);
  4627. return result;
  4628. };
  4629. /**
  4630. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4631. */
  4632. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4633. var data = matrix.m;
  4634. var m11 = data[0], m12 = data[4], m13 = data[8];
  4635. var m21 = data[1], m22 = data[5], m23 = data[9];
  4636. var m31 = data[2], m32 = data[6], m33 = data[10];
  4637. var trace = m11 + m22 + m33;
  4638. var s;
  4639. if (trace > 0) {
  4640. s = 0.5 / Math.sqrt(trace + 1.0);
  4641. result.w = 0.25 / s;
  4642. result.x = (m32 - m23) * s;
  4643. result.y = (m13 - m31) * s;
  4644. result.z = (m21 - m12) * s;
  4645. }
  4646. else if (m11 > m22 && m11 > m33) {
  4647. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4648. result.w = (m32 - m23) / s;
  4649. result.x = 0.25 * s;
  4650. result.y = (m12 + m21) / s;
  4651. result.z = (m13 + m31) / s;
  4652. }
  4653. else if (m22 > m33) {
  4654. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4655. result.w = (m13 - m31) / s;
  4656. result.x = (m12 + m21) / s;
  4657. result.y = 0.25 * s;
  4658. result.z = (m23 + m32) / s;
  4659. }
  4660. else {
  4661. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4662. result.w = (m21 - m12) / s;
  4663. result.x = (m13 + m31) / s;
  4664. result.y = (m23 + m32) / s;
  4665. result.z = 0.25 * s;
  4666. }
  4667. };
  4668. /**
  4669. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4670. */
  4671. Quaternion.Zero = function () {
  4672. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4673. };
  4674. /**
  4675. * Returns a new Quaternion as the inverted current Quaternion.
  4676. */
  4677. Quaternion.Inverse = function (q) {
  4678. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4679. };
  4680. /**
  4681. * Returns the identity Quaternion.
  4682. */
  4683. Quaternion.Identity = function () {
  4684. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4685. };
  4686. Quaternion.IsIdentity = function (quaternion) {
  4687. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4688. };
  4689. /**
  4690. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4691. */
  4692. Quaternion.RotationAxis = function (axis, angle) {
  4693. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4694. };
  4695. /**
  4696. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4697. */
  4698. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4699. var sin = Math.sin(angle / 2);
  4700. axis.normalize();
  4701. result.w = Math.cos(angle / 2);
  4702. result.x = axis.x * sin;
  4703. result.y = axis.y * sin;
  4704. result.z = axis.z * sin;
  4705. return result;
  4706. };
  4707. /**
  4708. * Retuns a new Quaternion set from the starting index of the passed array.
  4709. */
  4710. Quaternion.FromArray = function (array, offset) {
  4711. if (!offset) {
  4712. offset = 0;
  4713. }
  4714. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4715. };
  4716. /**
  4717. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4718. */
  4719. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4720. var q = new Quaternion();
  4721. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4722. return q;
  4723. };
  4724. /**
  4725. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4726. */
  4727. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4728. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4729. var halfRoll = roll * 0.5;
  4730. var halfPitch = pitch * 0.5;
  4731. var halfYaw = yaw * 0.5;
  4732. var sinRoll = Math.sin(halfRoll);
  4733. var cosRoll = Math.cos(halfRoll);
  4734. var sinPitch = Math.sin(halfPitch);
  4735. var cosPitch = Math.cos(halfPitch);
  4736. var sinYaw = Math.sin(halfYaw);
  4737. var cosYaw = Math.cos(halfYaw);
  4738. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4739. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4740. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4741. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4742. };
  4743. /**
  4744. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4745. */
  4746. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4747. var result = new Quaternion();
  4748. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4749. return result;
  4750. };
  4751. /**
  4752. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4753. */
  4754. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4755. // Produces a quaternion from Euler angles in the z-x-z orientation
  4756. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4757. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4758. var halfBeta = beta * 0.5;
  4759. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4760. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4761. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4762. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4763. };
  4764. /**
  4765. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4766. * cf to Vector3.RotationFromAxis() documentation.
  4767. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4768. */
  4769. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4770. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4771. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4772. return quat;
  4773. };
  4774. /**
  4775. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4776. * cf to Vector3.RotationFromAxis() documentation.
  4777. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4778. */
  4779. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4780. var rotMat = MathTmp.Matrix[0];
  4781. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4782. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4783. };
  4784. Quaternion.Slerp = function (left, right, amount) {
  4785. var result = Quaternion.Identity();
  4786. Quaternion.SlerpToRef(left, right, amount, result);
  4787. return result;
  4788. };
  4789. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4790. var num2;
  4791. var num3;
  4792. var num = amount;
  4793. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4794. var flag = false;
  4795. if (num4 < 0) {
  4796. flag = true;
  4797. num4 = -num4;
  4798. }
  4799. if (num4 > 0.999999) {
  4800. num3 = 1 - num;
  4801. num2 = flag ? -num : num;
  4802. }
  4803. else {
  4804. var num5 = Math.acos(num4);
  4805. var num6 = (1.0 / Math.sin(num5));
  4806. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4807. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4808. }
  4809. result.x = (num3 * left.x) + (num2 * right.x);
  4810. result.y = (num3 * left.y) + (num2 * right.y);
  4811. result.z = (num3 * left.z) + (num2 * right.z);
  4812. result.w = (num3 * left.w) + (num2 * right.w);
  4813. };
  4814. /**
  4815. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4816. */
  4817. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4818. var squared = amount * amount;
  4819. var cubed = amount * squared;
  4820. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4821. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4822. var part3 = (cubed - (2.0 * squared)) + amount;
  4823. var part4 = cubed - squared;
  4824. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4825. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4826. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4827. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4828. return new Quaternion(x, y, z, w);
  4829. };
  4830. return Quaternion;
  4831. }());
  4832. BABYLON.Quaternion = Quaternion;
  4833. var Matrix = /** @class */ (function () {
  4834. function Matrix() {
  4835. this._isIdentity = false;
  4836. this._isIdentityDirty = true;
  4837. this.m = new Float32Array(16);
  4838. this._markAsUpdated();
  4839. }
  4840. Matrix.prototype._markAsUpdated = function () {
  4841. this.updateFlag = Matrix._updateFlagSeed++;
  4842. this._isIdentityDirty = true;
  4843. };
  4844. // Properties
  4845. /**
  4846. * Boolean : True is the matrix is the identity matrix
  4847. */
  4848. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4849. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4850. if (this._isIdentityDirty) {
  4851. this._isIdentityDirty = false;
  4852. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4853. this._isIdentity = false;
  4854. }
  4855. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4856. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4857. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4858. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4859. this._isIdentity = false;
  4860. }
  4861. else {
  4862. this._isIdentity = true;
  4863. }
  4864. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4865. this._isIdentity = false;
  4866. }
  4867. }
  4868. return this._isIdentity;
  4869. };
  4870. /**
  4871. * Returns the matrix determinant (float).
  4872. */
  4873. Matrix.prototype.determinant = function () {
  4874. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4875. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4876. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4877. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4878. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4879. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4880. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4881. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4882. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4883. };
  4884. // Methods
  4885. /**
  4886. * Returns the matrix underlying array.
  4887. */
  4888. Matrix.prototype.toArray = function () {
  4889. return this.m;
  4890. };
  4891. /**
  4892. * Returns the matrix underlying array.
  4893. */
  4894. Matrix.prototype.asArray = function () {
  4895. return this.toArray();
  4896. };
  4897. /**
  4898. * Inverts in place the Matrix.
  4899. * Returns the Matrix inverted.
  4900. */
  4901. Matrix.prototype.invert = function () {
  4902. this.invertToRef(this);
  4903. return this;
  4904. };
  4905. /**
  4906. * Sets all the matrix elements to zero.
  4907. * Returns the Matrix.
  4908. */
  4909. Matrix.prototype.reset = function () {
  4910. for (var index = 0; index < 16; index++) {
  4911. this.m[index] = 0.0;
  4912. }
  4913. this._markAsUpdated();
  4914. return this;
  4915. };
  4916. /**
  4917. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4918. */
  4919. Matrix.prototype.add = function (other) {
  4920. var result = new Matrix();
  4921. this.addToRef(other, result);
  4922. return result;
  4923. };
  4924. /**
  4925. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4926. * Returns the Matrix.
  4927. */
  4928. Matrix.prototype.addToRef = function (other, result) {
  4929. for (var index = 0; index < 16; index++) {
  4930. result.m[index] = this.m[index] + other.m[index];
  4931. }
  4932. result._markAsUpdated();
  4933. return this;
  4934. };
  4935. /**
  4936. * Adds in place the passed matrix to the current Matrix.
  4937. * Returns the updated Matrix.
  4938. */
  4939. Matrix.prototype.addToSelf = function (other) {
  4940. for (var index = 0; index < 16; index++) {
  4941. this.m[index] += other.m[index];
  4942. }
  4943. this._markAsUpdated();
  4944. return this;
  4945. };
  4946. /**
  4947. * Sets the passed matrix with the current inverted Matrix.
  4948. * Returns the unmodified current Matrix.
  4949. */
  4950. Matrix.prototype.invertToRef = function (other) {
  4951. var l1 = this.m[0];
  4952. var l2 = this.m[1];
  4953. var l3 = this.m[2];
  4954. var l4 = this.m[3];
  4955. var l5 = this.m[4];
  4956. var l6 = this.m[5];
  4957. var l7 = this.m[6];
  4958. var l8 = this.m[7];
  4959. var l9 = this.m[8];
  4960. var l10 = this.m[9];
  4961. var l11 = this.m[10];
  4962. var l12 = this.m[11];
  4963. var l13 = this.m[12];
  4964. var l14 = this.m[13];
  4965. var l15 = this.m[14];
  4966. var l16 = this.m[15];
  4967. var l17 = (l11 * l16) - (l12 * l15);
  4968. var l18 = (l10 * l16) - (l12 * l14);
  4969. var l19 = (l10 * l15) - (l11 * l14);
  4970. var l20 = (l9 * l16) - (l12 * l13);
  4971. var l21 = (l9 * l15) - (l11 * l13);
  4972. var l22 = (l9 * l14) - (l10 * l13);
  4973. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4974. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4975. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4976. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4977. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4978. var l28 = (l7 * l16) - (l8 * l15);
  4979. var l29 = (l6 * l16) - (l8 * l14);
  4980. var l30 = (l6 * l15) - (l7 * l14);
  4981. var l31 = (l5 * l16) - (l8 * l13);
  4982. var l32 = (l5 * l15) - (l7 * l13);
  4983. var l33 = (l5 * l14) - (l6 * l13);
  4984. var l34 = (l7 * l12) - (l8 * l11);
  4985. var l35 = (l6 * l12) - (l8 * l10);
  4986. var l36 = (l6 * l11) - (l7 * l10);
  4987. var l37 = (l5 * l12) - (l8 * l9);
  4988. var l38 = (l5 * l11) - (l7 * l9);
  4989. var l39 = (l5 * l10) - (l6 * l9);
  4990. other.m[0] = l23 * l27;
  4991. other.m[4] = l24 * l27;
  4992. other.m[8] = l25 * l27;
  4993. other.m[12] = l26 * l27;
  4994. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4995. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4996. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4997. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4998. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4999. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5000. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5001. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5002. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5003. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5004. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5005. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5006. other._markAsUpdated();
  5007. return this;
  5008. };
  5009. /**
  5010. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  5011. * Returns the updated Matrix.
  5012. */
  5013. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5014. this.m[12] = x;
  5015. this.m[13] = y;
  5016. this.m[14] = z;
  5017. this._markAsUpdated();
  5018. return this;
  5019. };
  5020. /**
  5021. * Inserts the translation vector in the current Matrix.
  5022. * Returns the updated Matrix.
  5023. */
  5024. Matrix.prototype.setTranslation = function (vector3) {
  5025. this.m[12] = vector3.x;
  5026. this.m[13] = vector3.y;
  5027. this.m[14] = vector3.z;
  5028. this._markAsUpdated();
  5029. return this;
  5030. };
  5031. /**
  5032. * Returns a new Vector3 as the extracted translation from the Matrix.
  5033. */
  5034. Matrix.prototype.getTranslation = function () {
  5035. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5036. };
  5037. /**
  5038. * Fill a Vector3 with the extracted translation from the Matrix.
  5039. */
  5040. Matrix.prototype.getTranslationToRef = function (result) {
  5041. result.x = this.m[12];
  5042. result.y = this.m[13];
  5043. result.z = this.m[14];
  5044. return this;
  5045. };
  5046. /**
  5047. * Remove rotation and scaling part from the Matrix.
  5048. * Returns the updated Matrix.
  5049. */
  5050. Matrix.prototype.removeRotationAndScaling = function () {
  5051. this.setRowFromFloats(0, 1, 0, 0, 0);
  5052. this.setRowFromFloats(1, 0, 1, 0, 0);
  5053. this.setRowFromFloats(2, 0, 0, 1, 0);
  5054. return this;
  5055. };
  5056. /**
  5057. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  5058. */
  5059. Matrix.prototype.multiply = function (other) {
  5060. var result = new Matrix();
  5061. this.multiplyToRef(other, result);
  5062. return result;
  5063. };
  5064. /**
  5065. * Updates the current Matrix from the passed one values.
  5066. * Returns the updated Matrix.
  5067. */
  5068. Matrix.prototype.copyFrom = function (other) {
  5069. for (var index = 0; index < 16; index++) {
  5070. this.m[index] = other.m[index];
  5071. }
  5072. this._markAsUpdated();
  5073. return this;
  5074. };
  5075. /**
  5076. * Populates the passed array from the starting index with the Matrix values.
  5077. * Returns the Matrix.
  5078. */
  5079. Matrix.prototype.copyToArray = function (array, offset) {
  5080. if (offset === void 0) { offset = 0; }
  5081. for (var index = 0; index < 16; index++) {
  5082. array[offset + index] = this.m[index];
  5083. }
  5084. return this;
  5085. };
  5086. /**
  5087. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  5088. */
  5089. Matrix.prototype.multiplyToRef = function (other, result) {
  5090. this.multiplyToArray(other, result.m, 0);
  5091. result._markAsUpdated();
  5092. return this;
  5093. };
  5094. /**
  5095. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  5096. */
  5097. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5098. var tm0 = this.m[0];
  5099. var tm1 = this.m[1];
  5100. var tm2 = this.m[2];
  5101. var tm3 = this.m[3];
  5102. var tm4 = this.m[4];
  5103. var tm5 = this.m[5];
  5104. var tm6 = this.m[6];
  5105. var tm7 = this.m[7];
  5106. var tm8 = this.m[8];
  5107. var tm9 = this.m[9];
  5108. var tm10 = this.m[10];
  5109. var tm11 = this.m[11];
  5110. var tm12 = this.m[12];
  5111. var tm13 = this.m[13];
  5112. var tm14 = this.m[14];
  5113. var tm15 = this.m[15];
  5114. var om0 = other.m[0];
  5115. var om1 = other.m[1];
  5116. var om2 = other.m[2];
  5117. var om3 = other.m[3];
  5118. var om4 = other.m[4];
  5119. var om5 = other.m[5];
  5120. var om6 = other.m[6];
  5121. var om7 = other.m[7];
  5122. var om8 = other.m[8];
  5123. var om9 = other.m[9];
  5124. var om10 = other.m[10];
  5125. var om11 = other.m[11];
  5126. var om12 = other.m[12];
  5127. var om13 = other.m[13];
  5128. var om14 = other.m[14];
  5129. var om15 = other.m[15];
  5130. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5131. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5132. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5133. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5134. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5135. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5136. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5137. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5138. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5139. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5140. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5141. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5142. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5143. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5144. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5145. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5146. return this;
  5147. };
  5148. /**
  5149. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  5150. */
  5151. Matrix.prototype.equals = function (value) {
  5152. return value &&
  5153. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5154. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5155. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5156. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5157. };
  5158. /**
  5159. * Returns a new Matrix from the current Matrix.
  5160. */
  5161. Matrix.prototype.clone = function () {
  5162. 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]);
  5163. };
  5164. /**
  5165. * Returns the string "Matrix"
  5166. */
  5167. Matrix.prototype.getClassName = function () {
  5168. return "Matrix";
  5169. };
  5170. /**
  5171. * Returns the Matrix hash code.
  5172. */
  5173. Matrix.prototype.getHashCode = function () {
  5174. var hash = this.m[0] || 0;
  5175. for (var i = 1; i < 16; i++) {
  5176. hash = (hash * 397) ^ (this.m[i] || 0);
  5177. }
  5178. return hash;
  5179. };
  5180. /**
  5181. * Decomposes the current Matrix into :
  5182. * - a scale vector3 passed as a reference to update,
  5183. * - a rotation quaternion passed as a reference to update,
  5184. * - a translation vector3 passed as a reference to update.
  5185. * Returns the true if operation was successful.
  5186. */
  5187. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5188. translation.x = this.m[12];
  5189. translation.y = this.m[13];
  5190. translation.z = this.m[14];
  5191. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5192. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5193. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5194. if (this.determinant() <= 0) {
  5195. scale.y *= -1;
  5196. }
  5197. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5198. rotation.x = 0;
  5199. rotation.y = 0;
  5200. rotation.z = 0;
  5201. rotation.w = 1;
  5202. return false;
  5203. }
  5204. 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]);
  5205. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5206. return true;
  5207. };
  5208. /**
  5209. * Returns the index-th row of the current matrix as a new Vector4.
  5210. */
  5211. Matrix.prototype.getRow = function (index) {
  5212. if (index < 0 || index > 3) {
  5213. return null;
  5214. }
  5215. var i = index * 4;
  5216. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5217. };
  5218. /**
  5219. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5220. * Returns the updated Matrix.
  5221. */
  5222. Matrix.prototype.setRow = function (index, row) {
  5223. if (index < 0 || index > 3) {
  5224. return this;
  5225. }
  5226. var i = index * 4;
  5227. this.m[i + 0] = row.x;
  5228. this.m[i + 1] = row.y;
  5229. this.m[i + 2] = row.z;
  5230. this.m[i + 3] = row.w;
  5231. this._markAsUpdated();
  5232. return this;
  5233. };
  5234. /**
  5235. * Compute the transpose of the matrix.
  5236. * Returns a new Matrix.
  5237. */
  5238. Matrix.prototype.transpose = function () {
  5239. return Matrix.Transpose(this);
  5240. };
  5241. /**
  5242. * Compute the transpose of the matrix.
  5243. * Returns the current matrix.
  5244. */
  5245. Matrix.prototype.transposeToRef = function (result) {
  5246. Matrix.TransposeToRef(this, result);
  5247. return this;
  5248. };
  5249. /**
  5250. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5251. * Returns the updated Matrix.
  5252. */
  5253. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5254. if (index < 0 || index > 3) {
  5255. return this;
  5256. }
  5257. var i = index * 4;
  5258. this.m[i + 0] = x;
  5259. this.m[i + 1] = y;
  5260. this.m[i + 2] = z;
  5261. this.m[i + 3] = w;
  5262. this._markAsUpdated();
  5263. return this;
  5264. };
  5265. /**
  5266. * Compute a new Matrix set with the current Matrix values multiplied by scale (float)
  5267. * @param scale defines the scale factor
  5268. * @returns a new Matrix
  5269. */
  5270. Matrix.prototype.scale = function (scale) {
  5271. var result = new Matrix();
  5272. this.scaleToRef(scale, result);
  5273. return result;
  5274. };
  5275. /**
  5276. * Scale the current Matrix values by a factor to a given result Matrix
  5277. * @param scale defines the scale factor
  5278. * @param result defines the Matrix to store the result
  5279. * @returns the current Matrix
  5280. */
  5281. Matrix.prototype.scaleToRef = function (scale, result) {
  5282. for (var index = 0; index < 16; index++) {
  5283. result.m[index] = this.m[index] * scale;
  5284. }
  5285. result._markAsUpdated();
  5286. return this;
  5287. };
  5288. /**
  5289. * Scale the current Matrix values by a factor and add the result to a given Matrix
  5290. * @param scale defines the scale factor
  5291. * @param result defines the Matrix to store the result
  5292. * @returns the current Matrix
  5293. */
  5294. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5295. for (var index = 0; index < 16; index++) {
  5296. result.m[index] += this.m[index] * scale;
  5297. }
  5298. result._markAsUpdated();
  5299. return this;
  5300. };
  5301. /**
  5302. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5303. * @param ref matrix to store the result
  5304. */
  5305. Matrix.prototype.toNormalMatrix = function (ref) {
  5306. this.invertToRef(ref);
  5307. ref.transpose();
  5308. var m = ref.m;
  5309. 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);
  5310. };
  5311. /**
  5312. * Returns a new Matrix as the extracted rotation matrix from the current one.
  5313. */
  5314. Matrix.prototype.getRotationMatrix = function () {
  5315. var result = Matrix.Identity();
  5316. this.getRotationMatrixToRef(result);
  5317. return result;
  5318. };
  5319. /**
  5320. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  5321. * Returns the current Matrix.
  5322. */
  5323. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5324. var m = this.m;
  5325. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5326. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5327. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5328. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5329. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5330. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5331. 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);
  5332. return this;
  5333. };
  5334. // Statics
  5335. /**
  5336. * Returns a new Matrix set from the starting index of the passed array.
  5337. */
  5338. Matrix.FromArray = function (array, offset) {
  5339. var result = new Matrix();
  5340. if (!offset) {
  5341. offset = 0;
  5342. }
  5343. Matrix.FromArrayToRef(array, offset, result);
  5344. return result;
  5345. };
  5346. /**
  5347. * Sets the passed "result" matrix from the starting index of the passed array.
  5348. */
  5349. Matrix.FromArrayToRef = function (array, offset, result) {
  5350. for (var index = 0; index < 16; index++) {
  5351. result.m[index] = array[index + offset];
  5352. }
  5353. result._markAsUpdated();
  5354. };
  5355. /**
  5356. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5357. */
  5358. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5359. for (var index = 0; index < 16; index++) {
  5360. result.m[index] = array[index + offset] * scale;
  5361. }
  5362. result._markAsUpdated();
  5363. };
  5364. /**
  5365. * Sets the passed matrix "result" with the 16 passed floats.
  5366. */
  5367. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5368. result.m[0] = initialM11;
  5369. result.m[1] = initialM12;
  5370. result.m[2] = initialM13;
  5371. result.m[3] = initialM14;
  5372. result.m[4] = initialM21;
  5373. result.m[5] = initialM22;
  5374. result.m[6] = initialM23;
  5375. result.m[7] = initialM24;
  5376. result.m[8] = initialM31;
  5377. result.m[9] = initialM32;
  5378. result.m[10] = initialM33;
  5379. result.m[11] = initialM34;
  5380. result.m[12] = initialM41;
  5381. result.m[13] = initialM42;
  5382. result.m[14] = initialM43;
  5383. result.m[15] = initialM44;
  5384. result._markAsUpdated();
  5385. };
  5386. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5387. /**
  5388. * Static identity matrix to be used as readonly matrix
  5389. * Must not be updated.
  5390. */
  5391. get: function () {
  5392. return Matrix._identityReadOnly;
  5393. },
  5394. enumerable: true,
  5395. configurable: true
  5396. });
  5397. /**
  5398. * Returns a new Matrix set from the 16 passed floats.
  5399. */
  5400. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5401. var result = new Matrix();
  5402. result.m[0] = initialM11;
  5403. result.m[1] = initialM12;
  5404. result.m[2] = initialM13;
  5405. result.m[3] = initialM14;
  5406. result.m[4] = initialM21;
  5407. result.m[5] = initialM22;
  5408. result.m[6] = initialM23;
  5409. result.m[7] = initialM24;
  5410. result.m[8] = initialM31;
  5411. result.m[9] = initialM32;
  5412. result.m[10] = initialM33;
  5413. result.m[11] = initialM34;
  5414. result.m[12] = initialM41;
  5415. result.m[13] = initialM42;
  5416. result.m[14] = initialM43;
  5417. result.m[15] = initialM44;
  5418. return result;
  5419. };
  5420. /**
  5421. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5422. */
  5423. Matrix.Compose = function (scale, rotation, translation) {
  5424. var result = Matrix.Identity();
  5425. Matrix.ComposeToRef(scale, rotation, translation, result);
  5426. return result;
  5427. };
  5428. /**
  5429. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5430. */
  5431. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5432. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5433. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5434. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5435. result.setTranslation(translation);
  5436. };
  5437. /**
  5438. * Returns a new indentity Matrix.
  5439. */
  5440. Matrix.Identity = function () {
  5441. 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);
  5442. };
  5443. /**
  5444. * Sets the passed "result" as an identity matrix.
  5445. */
  5446. Matrix.IdentityToRef = function (result) {
  5447. 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);
  5448. };
  5449. /**
  5450. * Returns a new zero Matrix.
  5451. */
  5452. Matrix.Zero = function () {
  5453. 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);
  5454. };
  5455. /**
  5456. * Returns a new rotation matrix for "angle" radians around the X axis.
  5457. */
  5458. Matrix.RotationX = function (angle) {
  5459. var result = new Matrix();
  5460. Matrix.RotationXToRef(angle, result);
  5461. return result;
  5462. };
  5463. /**
  5464. * Returns a new Matrix as the passed inverted one.
  5465. */
  5466. Matrix.Invert = function (source) {
  5467. var result = new Matrix();
  5468. source.invertToRef(result);
  5469. return result;
  5470. };
  5471. /**
  5472. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5473. */
  5474. Matrix.RotationXToRef = function (angle, result) {
  5475. var s = Math.sin(angle);
  5476. var c = Math.cos(angle);
  5477. result.m[0] = 1.0;
  5478. result.m[15] = 1.0;
  5479. result.m[5] = c;
  5480. result.m[10] = c;
  5481. result.m[9] = -s;
  5482. result.m[6] = s;
  5483. result.m[1] = 0.0;
  5484. result.m[2] = 0.0;
  5485. result.m[3] = 0.0;
  5486. result.m[4] = 0.0;
  5487. result.m[7] = 0.0;
  5488. result.m[8] = 0.0;
  5489. result.m[11] = 0.0;
  5490. result.m[12] = 0.0;
  5491. result.m[13] = 0.0;
  5492. result.m[14] = 0.0;
  5493. result._markAsUpdated();
  5494. };
  5495. /**
  5496. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5497. */
  5498. Matrix.RotationY = function (angle) {
  5499. var result = new Matrix();
  5500. Matrix.RotationYToRef(angle, result);
  5501. return result;
  5502. };
  5503. /**
  5504. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5505. */
  5506. Matrix.RotationYToRef = function (angle, result) {
  5507. var s = Math.sin(angle);
  5508. var c = Math.cos(angle);
  5509. result.m[5] = 1.0;
  5510. result.m[15] = 1.0;
  5511. result.m[0] = c;
  5512. result.m[2] = -s;
  5513. result.m[8] = s;
  5514. result.m[10] = c;
  5515. result.m[1] = 0.0;
  5516. result.m[3] = 0.0;
  5517. result.m[4] = 0.0;
  5518. result.m[6] = 0.0;
  5519. result.m[7] = 0.0;
  5520. result.m[9] = 0.0;
  5521. result.m[11] = 0.0;
  5522. result.m[12] = 0.0;
  5523. result.m[13] = 0.0;
  5524. result.m[14] = 0.0;
  5525. result._markAsUpdated();
  5526. };
  5527. /**
  5528. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5529. */
  5530. Matrix.RotationZ = function (angle) {
  5531. var result = new Matrix();
  5532. Matrix.RotationZToRef(angle, result);
  5533. return result;
  5534. };
  5535. /**
  5536. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5537. */
  5538. Matrix.RotationZToRef = function (angle, result) {
  5539. var s = Math.sin(angle);
  5540. var c = Math.cos(angle);
  5541. result.m[10] = 1.0;
  5542. result.m[15] = 1.0;
  5543. result.m[0] = c;
  5544. result.m[1] = s;
  5545. result.m[4] = -s;
  5546. result.m[5] = c;
  5547. result.m[2] = 0.0;
  5548. result.m[3] = 0.0;
  5549. result.m[6] = 0.0;
  5550. result.m[7] = 0.0;
  5551. result.m[8] = 0.0;
  5552. result.m[9] = 0.0;
  5553. result.m[11] = 0.0;
  5554. result.m[12] = 0.0;
  5555. result.m[13] = 0.0;
  5556. result.m[14] = 0.0;
  5557. result._markAsUpdated();
  5558. };
  5559. /**
  5560. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5561. */
  5562. Matrix.RotationAxis = function (axis, angle) {
  5563. var result = Matrix.Zero();
  5564. Matrix.RotationAxisToRef(axis, angle, result);
  5565. return result;
  5566. };
  5567. /**
  5568. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5569. */
  5570. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5571. var s = Math.sin(-angle);
  5572. var c = Math.cos(-angle);
  5573. var c1 = 1 - c;
  5574. axis.normalize();
  5575. result.m[0] = (axis.x * axis.x) * c1 + c;
  5576. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5577. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5578. result.m[3] = 0.0;
  5579. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5580. result.m[5] = (axis.y * axis.y) * c1 + c;
  5581. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5582. result.m[7] = 0.0;
  5583. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5584. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5585. result.m[10] = (axis.z * axis.z) * c1 + c;
  5586. result.m[11] = 0.0;
  5587. result.m[15] = 1.0;
  5588. result._markAsUpdated();
  5589. };
  5590. /**
  5591. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5592. */
  5593. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5594. var result = new Matrix();
  5595. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5596. return result;
  5597. };
  5598. /**
  5599. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5600. */
  5601. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5602. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5603. this._tempQuaternion.toRotationMatrix(result);
  5604. };
  5605. /**
  5606. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5607. */
  5608. Matrix.Scaling = function (x, y, z) {
  5609. var result = Matrix.Zero();
  5610. Matrix.ScalingToRef(x, y, z, result);
  5611. return result;
  5612. };
  5613. /**
  5614. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5615. */
  5616. Matrix.ScalingToRef = function (x, y, z, result) {
  5617. result.m[0] = x;
  5618. result.m[1] = 0.0;
  5619. result.m[2] = 0.0;
  5620. result.m[3] = 0.0;
  5621. result.m[4] = 0.0;
  5622. result.m[5] = y;
  5623. result.m[6] = 0.0;
  5624. result.m[7] = 0.0;
  5625. result.m[8] = 0.0;
  5626. result.m[9] = 0.0;
  5627. result.m[10] = z;
  5628. result.m[11] = 0.0;
  5629. result.m[12] = 0.0;
  5630. result.m[13] = 0.0;
  5631. result.m[14] = 0.0;
  5632. result.m[15] = 1.0;
  5633. result._markAsUpdated();
  5634. };
  5635. /**
  5636. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5637. */
  5638. Matrix.Translation = function (x, y, z) {
  5639. var result = Matrix.Identity();
  5640. Matrix.TranslationToRef(x, y, z, result);
  5641. return result;
  5642. };
  5643. /**
  5644. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5645. */
  5646. Matrix.TranslationToRef = function (x, y, z, result) {
  5647. 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);
  5648. };
  5649. /**
  5650. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5651. * @param startValue defines the start value
  5652. * @param endValue defines the end value
  5653. * @param gradient defines the gradient factor
  5654. * @returns the new matrix
  5655. */
  5656. Matrix.Lerp = function (startValue, endValue, gradient) {
  5657. var result = Matrix.Zero();
  5658. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5659. return result;
  5660. };
  5661. /**
  5662. * Set the passed matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5663. * @param startValue defines the start value
  5664. * @param endValue defines the end value
  5665. * @param gradient defines the gradient factor
  5666. * @param result defines the Matrix object where to store data
  5667. */
  5668. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5669. for (var index = 0; index < 16; index++) {
  5670. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5671. }
  5672. result._markAsUpdated();
  5673. };
  5674. /**
  5675. * Returns a new Matrix whose values are computed by :
  5676. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5677. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5678. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5679. */
  5680. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5681. var startScale = new Vector3(0, 0, 0);
  5682. var startRotation = new Quaternion();
  5683. var startTranslation = new Vector3(0, 0, 0);
  5684. startValue.decompose(startScale, startRotation, startTranslation);
  5685. var endScale = new Vector3(0, 0, 0);
  5686. var endRotation = new Quaternion();
  5687. var endTranslation = new Vector3(0, 0, 0);
  5688. endValue.decompose(endScale, endRotation, endTranslation);
  5689. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5690. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5691. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5692. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5693. };
  5694. /**
  5695. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5696. * This methods works for a Left-Handed system.
  5697. */
  5698. Matrix.LookAtLH = function (eye, target, up) {
  5699. var result = Matrix.Zero();
  5700. Matrix.LookAtLHToRef(eye, target, up, result);
  5701. return result;
  5702. };
  5703. /**
  5704. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5705. * This methods works for a Left-Handed system.
  5706. */
  5707. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5708. // Z axis
  5709. target.subtractToRef(eye, this._zAxis);
  5710. this._zAxis.normalize();
  5711. // X axis
  5712. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5713. if (this._xAxis.lengthSquared() === 0) {
  5714. this._xAxis.x = 1.0;
  5715. }
  5716. else {
  5717. this._xAxis.normalize();
  5718. }
  5719. // Y axis
  5720. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5721. this._yAxis.normalize();
  5722. // Eye angles
  5723. var ex = -Vector3.Dot(this._xAxis, eye);
  5724. var ey = -Vector3.Dot(this._yAxis, eye);
  5725. var ez = -Vector3.Dot(this._zAxis, eye);
  5726. 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);
  5727. };
  5728. /**
  5729. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5730. * This methods works for a Right-Handed system.
  5731. */
  5732. Matrix.LookAtRH = function (eye, target, up) {
  5733. var result = Matrix.Zero();
  5734. Matrix.LookAtRHToRef(eye, target, up, result);
  5735. return result;
  5736. };
  5737. /**
  5738. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5739. * This methods works for a Left-Handed system.
  5740. */
  5741. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5742. // Z axis
  5743. eye.subtractToRef(target, this._zAxis);
  5744. this._zAxis.normalize();
  5745. // X axis
  5746. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5747. if (this._xAxis.lengthSquared() === 0) {
  5748. this._xAxis.x = 1.0;
  5749. }
  5750. else {
  5751. this._xAxis.normalize();
  5752. }
  5753. // Y axis
  5754. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5755. this._yAxis.normalize();
  5756. // Eye angles
  5757. var ex = -Vector3.Dot(this._xAxis, eye);
  5758. var ey = -Vector3.Dot(this._yAxis, eye);
  5759. var ez = -Vector3.Dot(this._zAxis, eye);
  5760. 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);
  5761. };
  5762. /**
  5763. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5764. */
  5765. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5766. var matrix = Matrix.Zero();
  5767. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5768. return matrix;
  5769. };
  5770. /**
  5771. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5772. */
  5773. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5774. var n = znear;
  5775. var f = zfar;
  5776. var a = 2.0 / width;
  5777. var b = 2.0 / height;
  5778. var c = 2.0 / (f - n);
  5779. var d = -(f + n) / (f - n);
  5780. 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);
  5781. };
  5782. /**
  5783. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5784. */
  5785. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5786. var matrix = Matrix.Zero();
  5787. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5788. return matrix;
  5789. };
  5790. /**
  5791. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5792. */
  5793. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5794. var n = znear;
  5795. var f = zfar;
  5796. var a = 2.0 / (right - left);
  5797. var b = 2.0 / (top - bottom);
  5798. var c = 2.0 / (f - n);
  5799. var d = -(f + n) / (f - n);
  5800. var i0 = (left + right) / (left - right);
  5801. var i1 = (top + bottom) / (bottom - top);
  5802. 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);
  5803. };
  5804. /**
  5805. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5806. */
  5807. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5808. var matrix = Matrix.Zero();
  5809. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5810. return matrix;
  5811. };
  5812. /**
  5813. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5814. */
  5815. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5816. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5817. result.m[10] *= -1.0;
  5818. };
  5819. /**
  5820. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5821. */
  5822. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5823. var matrix = Matrix.Zero();
  5824. var n = znear;
  5825. var f = zfar;
  5826. var a = 2.0 * n / width;
  5827. var b = 2.0 * n / height;
  5828. var c = (f + n) / (f - n);
  5829. var d = -2.0 * f * n / (f - n);
  5830. 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);
  5831. return matrix;
  5832. };
  5833. /**
  5834. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5835. */
  5836. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5837. var matrix = Matrix.Zero();
  5838. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5839. return matrix;
  5840. };
  5841. /**
  5842. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5843. */
  5844. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5845. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5846. var n = znear;
  5847. var f = zfar;
  5848. var t = 1.0 / (Math.tan(fov * 0.5));
  5849. var a = isVerticalFovFixed ? (t / aspect) : t;
  5850. var b = isVerticalFovFixed ? t : (t * aspect);
  5851. var c = (f + n) / (f - n);
  5852. var d = -2.0 * f * n / (f - n);
  5853. 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);
  5854. };
  5855. /**
  5856. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5857. */
  5858. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5859. var matrix = Matrix.Zero();
  5860. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5861. return matrix;
  5862. };
  5863. /**
  5864. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5865. */
  5866. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5867. //alternatively this could be expressed as:
  5868. // m = PerspectiveFovLHToRef
  5869. // m[10] *= -1.0;
  5870. // m[11] *= -1.0;
  5871. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5872. var n = znear;
  5873. var f = zfar;
  5874. var t = 1.0 / (Math.tan(fov * 0.5));
  5875. var a = isVerticalFovFixed ? (t / aspect) : t;
  5876. var b = isVerticalFovFixed ? t : (t * aspect);
  5877. var c = -(f + n) / (f - n);
  5878. var d = -2 * f * n / (f - n);
  5879. 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);
  5880. };
  5881. /**
  5882. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5883. */
  5884. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5885. if (rightHanded === void 0) { rightHanded = false; }
  5886. var rightHandedFactor = rightHanded ? -1 : 1;
  5887. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5888. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5889. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5890. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5891. var xScale = 2.0 / (leftTan + rightTan);
  5892. var yScale = 2.0 / (upTan + downTan);
  5893. result.m[0] = xScale;
  5894. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5895. result.m[5] = yScale;
  5896. result.m[6] = result.m[7] = 0.0;
  5897. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5898. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5899. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5900. result.m[10] = -zfar / (znear - zfar);
  5901. result.m[11] = 1.0 * rightHandedFactor;
  5902. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5903. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5904. // result.m[14] = (znear * zfar) / (znear - zfar);
  5905. result._markAsUpdated();
  5906. };
  5907. /**
  5908. * Returns the final transformation matrix : world * view * projection * viewport
  5909. */
  5910. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5911. var cw = viewport.width;
  5912. var ch = viewport.height;
  5913. var cx = viewport.x;
  5914. var cy = viewport.y;
  5915. 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);
  5916. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5917. };
  5918. /**
  5919. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5920. */
  5921. Matrix.GetAsMatrix2x2 = function (matrix) {
  5922. return new Float32Array([
  5923. matrix.m[0], matrix.m[1],
  5924. matrix.m[4], matrix.m[5]
  5925. ]);
  5926. };
  5927. /**
  5928. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5929. */
  5930. Matrix.GetAsMatrix3x3 = function (matrix) {
  5931. return new Float32Array([
  5932. matrix.m[0], matrix.m[1], matrix.m[2],
  5933. matrix.m[4], matrix.m[5], matrix.m[6],
  5934. matrix.m[8], matrix.m[9], matrix.m[10]
  5935. ]);
  5936. };
  5937. /**
  5938. * Compute the transpose of the passed Matrix.
  5939. * Returns a new Matrix.
  5940. */
  5941. Matrix.Transpose = function (matrix) {
  5942. var result = new Matrix();
  5943. Matrix.TransposeToRef(matrix, result);
  5944. return result;
  5945. };
  5946. /**
  5947. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5948. */
  5949. Matrix.TransposeToRef = function (matrix, result) {
  5950. result.m[0] = matrix.m[0];
  5951. result.m[1] = matrix.m[4];
  5952. result.m[2] = matrix.m[8];
  5953. result.m[3] = matrix.m[12];
  5954. result.m[4] = matrix.m[1];
  5955. result.m[5] = matrix.m[5];
  5956. result.m[6] = matrix.m[9];
  5957. result.m[7] = matrix.m[13];
  5958. result.m[8] = matrix.m[2];
  5959. result.m[9] = matrix.m[6];
  5960. result.m[10] = matrix.m[10];
  5961. result.m[11] = matrix.m[14];
  5962. result.m[12] = matrix.m[3];
  5963. result.m[13] = matrix.m[7];
  5964. result.m[14] = matrix.m[11];
  5965. result.m[15] = matrix.m[15];
  5966. };
  5967. /**
  5968. * Returns a new Matrix as the reflection matrix across the passed plane.
  5969. */
  5970. Matrix.Reflection = function (plane) {
  5971. var matrix = new Matrix();
  5972. Matrix.ReflectionToRef(plane, matrix);
  5973. return matrix;
  5974. };
  5975. /**
  5976. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5977. */
  5978. Matrix.ReflectionToRef = function (plane, result) {
  5979. plane.normalize();
  5980. var x = plane.normal.x;
  5981. var y = plane.normal.y;
  5982. var z = plane.normal.z;
  5983. var temp = -2 * x;
  5984. var temp2 = -2 * y;
  5985. var temp3 = -2 * z;
  5986. result.m[0] = (temp * x) + 1;
  5987. result.m[1] = temp2 * x;
  5988. result.m[2] = temp3 * x;
  5989. result.m[3] = 0.0;
  5990. result.m[4] = temp * y;
  5991. result.m[5] = (temp2 * y) + 1;
  5992. result.m[6] = temp3 * y;
  5993. result.m[7] = 0.0;
  5994. result.m[8] = temp * z;
  5995. result.m[9] = temp2 * z;
  5996. result.m[10] = (temp3 * z) + 1;
  5997. result.m[11] = 0.0;
  5998. result.m[12] = temp * plane.d;
  5999. result.m[13] = temp2 * plane.d;
  6000. result.m[14] = temp3 * plane.d;
  6001. result.m[15] = 1.0;
  6002. result._markAsUpdated();
  6003. };
  6004. /**
  6005. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  6006. */
  6007. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6008. result.m[0] = xaxis.x;
  6009. result.m[1] = xaxis.y;
  6010. result.m[2] = xaxis.z;
  6011. result.m[3] = 0.0;
  6012. result.m[4] = yaxis.x;
  6013. result.m[5] = yaxis.y;
  6014. result.m[6] = yaxis.z;
  6015. result.m[7] = 0.0;
  6016. result.m[8] = zaxis.x;
  6017. result.m[9] = zaxis.y;
  6018. result.m[10] = zaxis.z;
  6019. result.m[11] = 0.0;
  6020. result.m[12] = 0.0;
  6021. result.m[13] = 0.0;
  6022. result.m[14] = 0.0;
  6023. result.m[15] = 1.0;
  6024. result._markAsUpdated();
  6025. };
  6026. /**
  6027. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  6028. */
  6029. Matrix.FromQuaternionToRef = function (quat, result) {
  6030. var xx = quat.x * quat.x;
  6031. var yy = quat.y * quat.y;
  6032. var zz = quat.z * quat.z;
  6033. var xy = quat.x * quat.y;
  6034. var zw = quat.z * quat.w;
  6035. var zx = quat.z * quat.x;
  6036. var yw = quat.y * quat.w;
  6037. var yz = quat.y * quat.z;
  6038. var xw = quat.x * quat.w;
  6039. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6040. result.m[1] = 2.0 * (xy + zw);
  6041. result.m[2] = 2.0 * (zx - yw);
  6042. result.m[3] = 0.0;
  6043. result.m[4] = 2.0 * (xy - zw);
  6044. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6045. result.m[6] = 2.0 * (yz + xw);
  6046. result.m[7] = 0.0;
  6047. result.m[8] = 2.0 * (zx + yw);
  6048. result.m[9] = 2.0 * (yz - xw);
  6049. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6050. result.m[11] = 0.0;
  6051. result.m[12] = 0.0;
  6052. result.m[13] = 0.0;
  6053. result.m[14] = 0.0;
  6054. result.m[15] = 1.0;
  6055. result._markAsUpdated();
  6056. };
  6057. Matrix._tempQuaternion = new Quaternion();
  6058. Matrix._xAxis = Vector3.Zero();
  6059. Matrix._yAxis = Vector3.Zero();
  6060. Matrix._zAxis = Vector3.Zero();
  6061. Matrix._updateFlagSeed = 0;
  6062. Matrix._identityReadOnly = Matrix.Identity();
  6063. return Matrix;
  6064. }());
  6065. BABYLON.Matrix = Matrix;
  6066. var Plane = /** @class */ (function () {
  6067. /**
  6068. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6069. */
  6070. function Plane(a, b, c, d) {
  6071. this.normal = new Vector3(a, b, c);
  6072. this.d = d;
  6073. }
  6074. /**
  6075. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6076. */
  6077. Plane.prototype.asArray = function () {
  6078. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6079. };
  6080. // Methods
  6081. /**
  6082. * Returns a new plane copied from the current Plane.
  6083. */
  6084. Plane.prototype.clone = function () {
  6085. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6086. };
  6087. /**
  6088. * Returns the string "Plane".
  6089. */
  6090. Plane.prototype.getClassName = function () {
  6091. return "Plane";
  6092. };
  6093. /**
  6094. * Returns the Plane hash code.
  6095. */
  6096. Plane.prototype.getHashCode = function () {
  6097. var hash = this.normal.getHashCode();
  6098. hash = (hash * 397) ^ (this.d || 0);
  6099. return hash;
  6100. };
  6101. /**
  6102. * Normalize the current Plane in place.
  6103. * Returns the updated Plane.
  6104. */
  6105. Plane.prototype.normalize = function () {
  6106. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6107. var magnitude = 0.0;
  6108. if (norm !== 0) {
  6109. magnitude = 1.0 / norm;
  6110. }
  6111. this.normal.x *= magnitude;
  6112. this.normal.y *= magnitude;
  6113. this.normal.z *= magnitude;
  6114. this.d *= magnitude;
  6115. return this;
  6116. };
  6117. /**
  6118. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  6119. */
  6120. Plane.prototype.transform = function (transformation) {
  6121. var transposedMatrix = Matrix.Transpose(transformation);
  6122. var x = this.normal.x;
  6123. var y = this.normal.y;
  6124. var z = this.normal.z;
  6125. var d = this.d;
  6126. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6127. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6128. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6129. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6130. return new Plane(normalX, normalY, normalZ, finalD);
  6131. };
  6132. /**
  6133. * Returns the dot product (float) of the point coordinates and the plane normal.
  6134. */
  6135. Plane.prototype.dotCoordinate = function (point) {
  6136. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6137. };
  6138. /**
  6139. * Updates the current Plane from the plane defined by the three passed points.
  6140. * Returns the updated Plane.
  6141. */
  6142. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6143. var x1 = point2.x - point1.x;
  6144. var y1 = point2.y - point1.y;
  6145. var z1 = point2.z - point1.z;
  6146. var x2 = point3.x - point1.x;
  6147. var y2 = point3.y - point1.y;
  6148. var z2 = point3.z - point1.z;
  6149. var yz = (y1 * z2) - (z1 * y2);
  6150. var xz = (z1 * x2) - (x1 * z2);
  6151. var xy = (x1 * y2) - (y1 * x2);
  6152. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6153. var invPyth;
  6154. if (pyth !== 0) {
  6155. invPyth = 1.0 / pyth;
  6156. }
  6157. else {
  6158. invPyth = 0.0;
  6159. }
  6160. this.normal.x = yz * invPyth;
  6161. this.normal.y = xz * invPyth;
  6162. this.normal.z = xy * invPyth;
  6163. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6164. return this;
  6165. };
  6166. /**
  6167. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6168. */
  6169. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6170. var dot = Vector3.Dot(this.normal, direction);
  6171. return (dot <= epsilon);
  6172. };
  6173. /**
  6174. * Returns the signed distance (float) from the passed point to the Plane.
  6175. */
  6176. Plane.prototype.signedDistanceTo = function (point) {
  6177. return Vector3.Dot(point, this.normal) + this.d;
  6178. };
  6179. // Statics
  6180. /**
  6181. * Returns a new Plane from the passed array.
  6182. */
  6183. Plane.FromArray = function (array) {
  6184. return new Plane(array[0], array[1], array[2], array[3]);
  6185. };
  6186. /**
  6187. * Returns a new Plane defined by the three passed points.
  6188. */
  6189. Plane.FromPoints = function (point1, point2, point3) {
  6190. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6191. result.copyFromPoints(point1, point2, point3);
  6192. return result;
  6193. };
  6194. /**
  6195. * Returns a new Plane the normal vector to this plane at the passed origin point.
  6196. * Note : the vector "normal" is updated because normalized.
  6197. */
  6198. Plane.FromPositionAndNormal = function (origin, normal) {
  6199. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6200. normal.normalize();
  6201. result.normal = normal;
  6202. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6203. return result;
  6204. };
  6205. /**
  6206. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  6207. */
  6208. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6209. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6210. return Vector3.Dot(point, normal) + d;
  6211. };
  6212. return Plane;
  6213. }());
  6214. BABYLON.Plane = Plane;
  6215. var Viewport = /** @class */ (function () {
  6216. /**
  6217. * Creates a Viewport object located at (x, y) and sized (width, height).
  6218. */
  6219. function Viewport(x, y, width, height) {
  6220. this.x = x;
  6221. this.y = y;
  6222. this.width = width;
  6223. this.height = height;
  6224. }
  6225. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6226. if (renderWidthOrEngine.getRenderWidth) {
  6227. var engine = renderWidthOrEngine;
  6228. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6229. }
  6230. var renderWidth = renderWidthOrEngine;
  6231. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6232. };
  6233. /**
  6234. * Returns a new Viewport copied from the current one.
  6235. */
  6236. Viewport.prototype.clone = function () {
  6237. return new Viewport(this.x, this.y, this.width, this.height);
  6238. };
  6239. return Viewport;
  6240. }());
  6241. BABYLON.Viewport = Viewport;
  6242. var Frustum = /** @class */ (function () {
  6243. function Frustum() {
  6244. }
  6245. /**
  6246. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  6247. */
  6248. Frustum.GetPlanes = function (transform) {
  6249. var frustumPlanes = [];
  6250. for (var index = 0; index < 6; index++) {
  6251. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6252. }
  6253. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6254. return frustumPlanes;
  6255. };
  6256. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6257. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6258. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6259. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6260. frustumPlane.d = transform.m[15] + transform.m[14];
  6261. frustumPlane.normalize();
  6262. };
  6263. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6264. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6265. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6266. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6267. frustumPlane.d = transform.m[15] - transform.m[14];
  6268. frustumPlane.normalize();
  6269. };
  6270. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6271. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6272. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6273. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6274. frustumPlane.d = transform.m[15] + transform.m[12];
  6275. frustumPlane.normalize();
  6276. };
  6277. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6278. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6279. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6280. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6281. frustumPlane.d = transform.m[15] - transform.m[12];
  6282. frustumPlane.normalize();
  6283. };
  6284. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6285. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6286. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6287. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6288. frustumPlane.d = transform.m[15] - transform.m[13];
  6289. frustumPlane.normalize();
  6290. };
  6291. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6292. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6293. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6294. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6295. frustumPlane.d = transform.m[15] + transform.m[13];
  6296. frustumPlane.normalize();
  6297. };
  6298. /**
  6299. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6300. */
  6301. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6302. // Near
  6303. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6304. // Far
  6305. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6306. // Left
  6307. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6308. // Right
  6309. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6310. // Top
  6311. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6312. // Bottom
  6313. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6314. };
  6315. return Frustum;
  6316. }());
  6317. BABYLON.Frustum = Frustum;
  6318. var Space;
  6319. (function (Space) {
  6320. Space[Space["LOCAL"] = 0] = "LOCAL";
  6321. Space[Space["WORLD"] = 1] = "WORLD";
  6322. Space[Space["BONE"] = 2] = "BONE";
  6323. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6324. var Axis = /** @class */ (function () {
  6325. function Axis() {
  6326. }
  6327. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6328. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6329. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6330. return Axis;
  6331. }());
  6332. BABYLON.Axis = Axis;
  6333. ;
  6334. var BezierCurve = /** @class */ (function () {
  6335. function BezierCurve() {
  6336. }
  6337. /**
  6338. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6339. */
  6340. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6341. // Extract X (which is equal to time here)
  6342. var f0 = 1 - 3 * x2 + 3 * x1;
  6343. var f1 = 3 * x2 - 6 * x1;
  6344. var f2 = 3 * x1;
  6345. var refinedT = t;
  6346. for (var i = 0; i < 5; i++) {
  6347. var refinedT2 = refinedT * refinedT;
  6348. var refinedT3 = refinedT2 * refinedT;
  6349. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6350. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6351. refinedT -= (x - t) * slope;
  6352. refinedT = Math.min(1, Math.max(0, refinedT));
  6353. }
  6354. // Resolve cubic bezier for the given x
  6355. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6356. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6357. Math.pow(refinedT, 3);
  6358. };
  6359. return BezierCurve;
  6360. }());
  6361. BABYLON.BezierCurve = BezierCurve;
  6362. var Orientation;
  6363. (function (Orientation) {
  6364. Orientation[Orientation["CW"] = 0] = "CW";
  6365. Orientation[Orientation["CCW"] = 1] = "CCW";
  6366. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6367. var Angle = /** @class */ (function () {
  6368. /**
  6369. * Creates an Angle object of "radians" radians (float).
  6370. */
  6371. function Angle(radians) {
  6372. var _this = this;
  6373. /**
  6374. * Returns the Angle value in degrees (float).
  6375. */
  6376. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6377. /**
  6378. * Returns the Angle value in radians (float).
  6379. */
  6380. this.radians = function () { return _this._radians; };
  6381. this._radians = radians;
  6382. if (this._radians < 0.0)
  6383. this._radians += (2.0 * Math.PI);
  6384. }
  6385. /**
  6386. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6387. */
  6388. Angle.BetweenTwoPoints = function (a, b) {
  6389. var delta = b.subtract(a);
  6390. var theta = Math.atan2(delta.y, delta.x);
  6391. return new Angle(theta);
  6392. };
  6393. /**
  6394. * Returns a new Angle object from the passed float in radians.
  6395. */
  6396. Angle.FromRadians = function (radians) {
  6397. return new Angle(radians);
  6398. };
  6399. /**
  6400. * Returns a new Angle object from the passed float in degrees.
  6401. */
  6402. Angle.FromDegrees = function (degrees) {
  6403. return new Angle(degrees * Math.PI / 180.0);
  6404. };
  6405. return Angle;
  6406. }());
  6407. BABYLON.Angle = Angle;
  6408. var Arc2 = /** @class */ (function () {
  6409. /**
  6410. * Creates an Arc object from the three passed points : start, middle and end.
  6411. */
  6412. function Arc2(startPoint, midPoint, endPoint) {
  6413. this.startPoint = startPoint;
  6414. this.midPoint = midPoint;
  6415. this.endPoint = endPoint;
  6416. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6417. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6418. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6419. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6420. 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);
  6421. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6422. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6423. var a1 = this.startAngle.degrees();
  6424. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6425. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6426. // angles correction
  6427. if (a2 - a1 > +180.0)
  6428. a2 -= 360.0;
  6429. if (a2 - a1 < -180.0)
  6430. a2 += 360.0;
  6431. if (a3 - a2 > +180.0)
  6432. a3 -= 360.0;
  6433. if (a3 - a2 < -180.0)
  6434. a3 += 360.0;
  6435. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6436. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6437. }
  6438. return Arc2;
  6439. }());
  6440. BABYLON.Arc2 = Arc2;
  6441. var Path2 = /** @class */ (function () {
  6442. /**
  6443. * Creates a Path2 object from the starting 2D coordinates x and y.
  6444. */
  6445. function Path2(x, y) {
  6446. this._points = new Array();
  6447. this._length = 0.0;
  6448. this.closed = false;
  6449. this._points.push(new Vector2(x, y));
  6450. }
  6451. /**
  6452. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6453. * Returns the updated Path2.
  6454. */
  6455. Path2.prototype.addLineTo = function (x, y) {
  6456. if (this.closed) {
  6457. return this;
  6458. }
  6459. var newPoint = new Vector2(x, y);
  6460. var previousPoint = this._points[this._points.length - 1];
  6461. this._points.push(newPoint);
  6462. this._length += newPoint.subtract(previousPoint).length();
  6463. return this;
  6464. };
  6465. /**
  6466. * 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.
  6467. * Returns the updated Path2.
  6468. */
  6469. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6470. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6471. if (this.closed) {
  6472. return this;
  6473. }
  6474. var startPoint = this._points[this._points.length - 1];
  6475. var midPoint = new Vector2(midX, midY);
  6476. var endPoint = new Vector2(endX, endY);
  6477. var arc = new Arc2(startPoint, midPoint, endPoint);
  6478. var increment = arc.angle.radians() / numberOfSegments;
  6479. if (arc.orientation === Orientation.CW)
  6480. increment *= -1;
  6481. var currentAngle = arc.startAngle.radians() + increment;
  6482. for (var i = 0; i < numberOfSegments; i++) {
  6483. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6484. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6485. this.addLineTo(x, y);
  6486. currentAngle += increment;
  6487. }
  6488. return this;
  6489. };
  6490. /**
  6491. * Closes the Path2.
  6492. * Returns the Path2.
  6493. */
  6494. Path2.prototype.close = function () {
  6495. this.closed = true;
  6496. return this;
  6497. };
  6498. /**
  6499. * Returns the Path2 total length (float).
  6500. */
  6501. Path2.prototype.length = function () {
  6502. var result = this._length;
  6503. if (!this.closed) {
  6504. var lastPoint = this._points[this._points.length - 1];
  6505. var firstPoint = this._points[0];
  6506. result += (firstPoint.subtract(lastPoint).length());
  6507. }
  6508. return result;
  6509. };
  6510. /**
  6511. * Returns the Path2 internal array of points.
  6512. */
  6513. Path2.prototype.getPoints = function () {
  6514. return this._points;
  6515. };
  6516. /**
  6517. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6518. */
  6519. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6520. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6521. return Vector2.Zero();
  6522. }
  6523. var lengthPosition = normalizedLengthPosition * this.length();
  6524. var previousOffset = 0;
  6525. for (var i = 0; i < this._points.length; i++) {
  6526. var j = (i + 1) % this._points.length;
  6527. var a = this._points[i];
  6528. var b = this._points[j];
  6529. var bToA = b.subtract(a);
  6530. var nextOffset = (bToA.length() + previousOffset);
  6531. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6532. var dir = bToA.normalize();
  6533. var localOffset = lengthPosition - previousOffset;
  6534. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6535. }
  6536. previousOffset = nextOffset;
  6537. }
  6538. return Vector2.Zero();
  6539. };
  6540. /**
  6541. * Returns a new Path2 starting at the coordinates (x, y).
  6542. */
  6543. Path2.StartingAt = function (x, y) {
  6544. return new Path2(x, y);
  6545. };
  6546. return Path2;
  6547. }());
  6548. BABYLON.Path2 = Path2;
  6549. var Path3D = /** @class */ (function () {
  6550. /**
  6551. * new Path3D(path, normal, raw)
  6552. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6553. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6554. * path : an array of Vector3, the curve axis of the Path3D
  6555. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6556. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6557. */
  6558. function Path3D(path, firstNormal, raw) {
  6559. if (firstNormal === void 0) { firstNormal = null; }
  6560. this.path = path;
  6561. this._curve = new Array();
  6562. this._distances = new Array();
  6563. this._tangents = new Array();
  6564. this._normals = new Array();
  6565. this._binormals = new Array();
  6566. for (var p = 0; p < path.length; p++) {
  6567. this._curve[p] = path[p].clone(); // hard copy
  6568. }
  6569. this._raw = raw || false;
  6570. this._compute(firstNormal);
  6571. }
  6572. /**
  6573. * Returns the Path3D array of successive Vector3 designing its curve.
  6574. */
  6575. Path3D.prototype.getCurve = function () {
  6576. return this._curve;
  6577. };
  6578. /**
  6579. * Returns an array populated with tangent vectors on each Path3D curve point.
  6580. */
  6581. Path3D.prototype.getTangents = function () {
  6582. return this._tangents;
  6583. };
  6584. /**
  6585. * Returns an array populated with normal vectors on each Path3D curve point.
  6586. */
  6587. Path3D.prototype.getNormals = function () {
  6588. return this._normals;
  6589. };
  6590. /**
  6591. * Returns an array populated with binormal vectors on each Path3D curve point.
  6592. */
  6593. Path3D.prototype.getBinormals = function () {
  6594. return this._binormals;
  6595. };
  6596. /**
  6597. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6598. */
  6599. Path3D.prototype.getDistances = function () {
  6600. return this._distances;
  6601. };
  6602. /**
  6603. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6604. * Returns the same object updated.
  6605. */
  6606. Path3D.prototype.update = function (path, firstNormal) {
  6607. if (firstNormal === void 0) { firstNormal = null; }
  6608. for (var p = 0; p < path.length; p++) {
  6609. this._curve[p].x = path[p].x;
  6610. this._curve[p].y = path[p].y;
  6611. this._curve[p].z = path[p].z;
  6612. }
  6613. this._compute(firstNormal);
  6614. return this;
  6615. };
  6616. // private function compute() : computes tangents, normals and binormals
  6617. Path3D.prototype._compute = function (firstNormal) {
  6618. var l = this._curve.length;
  6619. // first and last tangents
  6620. this._tangents[0] = this._getFirstNonNullVector(0);
  6621. if (!this._raw) {
  6622. this._tangents[0].normalize();
  6623. }
  6624. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6625. if (!this._raw) {
  6626. this._tangents[l - 1].normalize();
  6627. }
  6628. // normals and binormals at first point : arbitrary vector with _normalVector()
  6629. var tg0 = this._tangents[0];
  6630. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6631. this._normals[0] = pp0;
  6632. if (!this._raw) {
  6633. this._normals[0].normalize();
  6634. }
  6635. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6636. if (!this._raw) {
  6637. this._binormals[0].normalize();
  6638. }
  6639. this._distances[0] = 0.0;
  6640. // normals and binormals : next points
  6641. var prev; // previous vector (segment)
  6642. var cur; // current vector (segment)
  6643. var curTang; // current tangent
  6644. // previous normal
  6645. var prevBinor; // previous binormal
  6646. for (var i = 1; i < l; i++) {
  6647. // tangents
  6648. prev = this._getLastNonNullVector(i);
  6649. if (i < l - 1) {
  6650. cur = this._getFirstNonNullVector(i);
  6651. this._tangents[i] = prev.add(cur);
  6652. this._tangents[i].normalize();
  6653. }
  6654. this._distances[i] = this._distances[i - 1] + prev.length();
  6655. // normals and binormals
  6656. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6657. curTang = this._tangents[i];
  6658. prevBinor = this._binormals[i - 1];
  6659. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6660. if (!this._raw) {
  6661. this._normals[i].normalize();
  6662. }
  6663. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6664. if (!this._raw) {
  6665. this._binormals[i].normalize();
  6666. }
  6667. }
  6668. };
  6669. // private function getFirstNonNullVector(index)
  6670. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6671. Path3D.prototype._getFirstNonNullVector = function (index) {
  6672. var i = 1;
  6673. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6674. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6675. i++;
  6676. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6677. }
  6678. return nNVector;
  6679. };
  6680. // private function getLastNonNullVector(index)
  6681. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6682. Path3D.prototype._getLastNonNullVector = function (index) {
  6683. var i = 1;
  6684. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6685. while (nLVector.length() === 0 && index > i + 1) {
  6686. i++;
  6687. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6688. }
  6689. return nLVector;
  6690. };
  6691. // private function normalVector(v0, vt, va) :
  6692. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6693. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6694. Path3D.prototype._normalVector = function (v0, vt, va) {
  6695. var normal0;
  6696. var tgl = vt.length();
  6697. if (tgl === 0.0) {
  6698. tgl = 1.0;
  6699. }
  6700. if (va === undefined || va === null) {
  6701. var point;
  6702. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6703. point = new Vector3(0.0, -1.0, 0.0);
  6704. }
  6705. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6706. point = new Vector3(1.0, 0.0, 0.0);
  6707. }
  6708. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6709. point = new Vector3(0.0, 0.0, 1.0);
  6710. }
  6711. else {
  6712. point = Vector3.Zero();
  6713. }
  6714. normal0 = Vector3.Cross(vt, point);
  6715. }
  6716. else {
  6717. normal0 = Vector3.Cross(vt, va);
  6718. Vector3.CrossToRef(normal0, vt, normal0);
  6719. }
  6720. normal0.normalize();
  6721. return normal0;
  6722. };
  6723. return Path3D;
  6724. }());
  6725. BABYLON.Path3D = Path3D;
  6726. var Curve3 = /** @class */ (function () {
  6727. /**
  6728. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6729. * A Curve3 is designed from a series of successive Vector3.
  6730. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6731. */
  6732. function Curve3(points) {
  6733. this._length = 0.0;
  6734. this._points = points;
  6735. this._length = this._computeLength(points);
  6736. }
  6737. /**
  6738. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6739. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6740. * @param v1 (Vector3) the control point
  6741. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6742. * @param nbPoints (integer) the wanted number of points in the curve
  6743. */
  6744. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6745. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6746. var bez = new Array();
  6747. var equation = function (t, val0, val1, val2) {
  6748. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6749. return res;
  6750. };
  6751. for (var i = 0; i <= nbPoints; i++) {
  6752. 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)));
  6753. }
  6754. return new Curve3(bez);
  6755. };
  6756. /**
  6757. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6758. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6759. * @param v1 (Vector3) the first control point
  6760. * @param v2 (Vector3) the second control point
  6761. * @param v3 (Vector3) the end point of the Cubic Bezier
  6762. * @param nbPoints (integer) the wanted number of points in the curve
  6763. */
  6764. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6765. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6766. var bez = new Array();
  6767. var equation = function (t, val0, val1, val2, val3) {
  6768. 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;
  6769. return res;
  6770. };
  6771. for (var i = 0; i <= nbPoints; i++) {
  6772. 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)));
  6773. }
  6774. return new Curve3(bez);
  6775. };
  6776. /**
  6777. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6778. * @param p1 (Vector3) the origin point of the Hermite Spline
  6779. * @param t1 (Vector3) the tangent vector at the origin point
  6780. * @param p2 (Vector3) the end point of the Hermite Spline
  6781. * @param t2 (Vector3) the tangent vector at the end point
  6782. * @param nbPoints (integer) the wanted number of points in the curve
  6783. */
  6784. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6785. var hermite = new Array();
  6786. var step = 1.0 / nbPoints;
  6787. for (var i = 0; i <= nbPoints; i++) {
  6788. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6789. }
  6790. return new Curve3(hermite);
  6791. };
  6792. /**
  6793. * Returns a Curve3 object along a CatmullRom Spline curve :
  6794. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6795. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6796. */
  6797. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6798. var totalPoints = new Array();
  6799. totalPoints.push(points[0].clone());
  6800. Array.prototype.push.apply(totalPoints, points);
  6801. totalPoints.push(points[points.length - 1].clone());
  6802. var catmullRom = new Array();
  6803. var step = 1.0 / nbPoints;
  6804. var amount = 0.0;
  6805. for (var i = 0; i < totalPoints.length - 3; i++) {
  6806. amount = 0;
  6807. for (var c = 0; c < nbPoints; c++) {
  6808. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6809. amount += step;
  6810. }
  6811. }
  6812. i--;
  6813. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6814. return new Curve3(catmullRom);
  6815. };
  6816. /**
  6817. * Returns the Curve3 stored array of successive Vector3
  6818. */
  6819. Curve3.prototype.getPoints = function () {
  6820. return this._points;
  6821. };
  6822. /**
  6823. * Returns the computed length (float) of the curve.
  6824. */
  6825. Curve3.prototype.length = function () {
  6826. return this._length;
  6827. };
  6828. /**
  6829. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6830. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6831. * curveA and curveB keep unchanged.
  6832. */
  6833. Curve3.prototype.continue = function (curve) {
  6834. var lastPoint = this._points[this._points.length - 1];
  6835. var continuedPoints = this._points.slice();
  6836. var curvePoints = curve.getPoints();
  6837. for (var i = 1; i < curvePoints.length; i++) {
  6838. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6839. }
  6840. var continuedCurve = new Curve3(continuedPoints);
  6841. return continuedCurve;
  6842. };
  6843. Curve3.prototype._computeLength = function (path) {
  6844. var l = 0;
  6845. for (var i = 1; i < path.length; i++) {
  6846. l += (path[i].subtract(path[i - 1])).length();
  6847. }
  6848. return l;
  6849. };
  6850. return Curve3;
  6851. }());
  6852. BABYLON.Curve3 = Curve3;
  6853. // Vertex formats
  6854. var PositionNormalVertex = /** @class */ (function () {
  6855. function PositionNormalVertex(position, normal) {
  6856. if (position === void 0) { position = Vector3.Zero(); }
  6857. if (normal === void 0) { normal = Vector3.Up(); }
  6858. this.position = position;
  6859. this.normal = normal;
  6860. }
  6861. PositionNormalVertex.prototype.clone = function () {
  6862. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6863. };
  6864. return PositionNormalVertex;
  6865. }());
  6866. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6867. var PositionNormalTextureVertex = /** @class */ (function () {
  6868. function PositionNormalTextureVertex(position, normal, uv) {
  6869. if (position === void 0) { position = Vector3.Zero(); }
  6870. if (normal === void 0) { normal = Vector3.Up(); }
  6871. if (uv === void 0) { uv = Vector2.Zero(); }
  6872. this.position = position;
  6873. this.normal = normal;
  6874. this.uv = uv;
  6875. }
  6876. PositionNormalTextureVertex.prototype.clone = function () {
  6877. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6878. };
  6879. return PositionNormalTextureVertex;
  6880. }());
  6881. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6882. // Temporary pre-allocated objects for engine internal use
  6883. // usage in any internal function :
  6884. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6885. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6886. var Tmp = /** @class */ (function () {
  6887. function Tmp() {
  6888. }
  6889. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6890. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6891. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6892. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6893. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6894. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6895. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6896. Matrix.Zero(), Matrix.Zero(),
  6897. Matrix.Zero(), Matrix.Zero(),
  6898. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6899. return Tmp;
  6900. }());
  6901. BABYLON.Tmp = Tmp;
  6902. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6903. var MathTmp = /** @class */ (function () {
  6904. function MathTmp() {
  6905. }
  6906. MathTmp.Vector3 = [Vector3.Zero()];
  6907. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6908. MathTmp.Quaternion = [Quaternion.Zero()];
  6909. return MathTmp;
  6910. }());
  6911. })(BABYLON || (BABYLON = {}));
  6912. //# sourceMappingURL=babylon.math.js.map
  6913. "use strict";
  6914. var BABYLON;
  6915. (function (BABYLON) {
  6916. var Scalar = /** @class */ (function () {
  6917. function Scalar() {
  6918. }
  6919. /**
  6920. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6921. */
  6922. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6923. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6924. var num = a - b;
  6925. return -epsilon <= num && num <= epsilon;
  6926. };
  6927. /**
  6928. * Returns a string : the upper case translation of the number i to hexadecimal.
  6929. */
  6930. Scalar.ToHex = function (i) {
  6931. var str = i.toString(16);
  6932. if (i <= 15) {
  6933. return ("0" + str).toUpperCase();
  6934. }
  6935. return str.toUpperCase();
  6936. };
  6937. /**
  6938. * Returns -1 if value is negative and +1 is value is positive.
  6939. * Returns the value itself if it's equal to zero.
  6940. */
  6941. Scalar.Sign = function (value) {
  6942. value = +value; // convert to a number
  6943. if (value === 0 || isNaN(value))
  6944. return value;
  6945. return value > 0 ? 1 : -1;
  6946. };
  6947. /**
  6948. * Returns the value itself if it's between min and max.
  6949. * Returns min if the value is lower than min.
  6950. * Returns max if the value is greater than max.
  6951. */
  6952. Scalar.Clamp = function (value, min, max) {
  6953. if (min === void 0) { min = 0; }
  6954. if (max === void 0) { max = 1; }
  6955. return Math.min(max, Math.max(min, value));
  6956. };
  6957. /**
  6958. * Returns the log2 of value.
  6959. */
  6960. Scalar.Log2 = function (value) {
  6961. return Math.log(value) * Math.LOG2E;
  6962. };
  6963. /**
  6964. * Loops the value, so that it is never larger than length and never smaller than 0.
  6965. *
  6966. * This is similar to the modulo operator but it works with floating point numbers.
  6967. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6968. * With t = 5 and length = 2.5, the result would be 0.0.
  6969. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6970. */
  6971. Scalar.Repeat = function (value, length) {
  6972. return value - Math.floor(value / length) * length;
  6973. };
  6974. /**
  6975. * Normalize the value between 0.0 and 1.0 using min and max values
  6976. */
  6977. Scalar.Normalize = function (value, min, max) {
  6978. return (value - min) / (max - min);
  6979. };
  6980. /**
  6981. * Denormalize the value from 0.0 and 1.0 using min and max values
  6982. */
  6983. Scalar.Denormalize = function (normalized, min, max) {
  6984. return (normalized * (max - min) + min);
  6985. };
  6986. /**
  6987. * Calculates the shortest difference between two given angles given in degrees.
  6988. */
  6989. Scalar.DeltaAngle = function (current, target) {
  6990. var num = Scalar.Repeat(target - current, 360.0);
  6991. if (num > 180.0) {
  6992. num -= 360.0;
  6993. }
  6994. return num;
  6995. };
  6996. /**
  6997. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6998. *
  6999. * The returned value will move back and forth between 0 and length
  7000. */
  7001. Scalar.PingPong = function (tx, length) {
  7002. var t = Scalar.Repeat(tx, length * 2.0);
  7003. return length - Math.abs(t - length);
  7004. };
  7005. /**
  7006. * Interpolates between min and max with smoothing at the limits.
  7007. *
  7008. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7009. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7010. */
  7011. Scalar.SmoothStep = function (from, to, tx) {
  7012. var t = Scalar.Clamp(tx);
  7013. t = -2.0 * t * t * t + 3.0 * t * t;
  7014. return to * t + from * (1.0 - t);
  7015. };
  7016. /**
  7017. * Moves a value current towards target.
  7018. *
  7019. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7020. * Negative values of maxDelta pushes the value away from target.
  7021. */
  7022. Scalar.MoveTowards = function (current, target, maxDelta) {
  7023. var result = 0;
  7024. if (Math.abs(target - current) <= maxDelta) {
  7025. result = target;
  7026. }
  7027. else {
  7028. result = current + Scalar.Sign(target - current) * maxDelta;
  7029. }
  7030. return result;
  7031. };
  7032. /**
  7033. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7034. *
  7035. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7036. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7037. */
  7038. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7039. var num = Scalar.DeltaAngle(current, target);
  7040. var result = 0;
  7041. if (-maxDelta < num && num < maxDelta) {
  7042. result = target;
  7043. }
  7044. else {
  7045. target = current + num;
  7046. result = Scalar.MoveTowards(current, target, maxDelta);
  7047. }
  7048. return result;
  7049. };
  7050. /**
  7051. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7052. */
  7053. Scalar.Lerp = function (start, end, amount) {
  7054. return start + ((end - start) * amount);
  7055. };
  7056. /**
  7057. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7058. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7059. */
  7060. Scalar.LerpAngle = function (start, end, amount) {
  7061. var num = Scalar.Repeat(end - start, 360.0);
  7062. if (num > 180.0) {
  7063. num -= 360.0;
  7064. }
  7065. return start + num * Scalar.Clamp(amount);
  7066. };
  7067. /**
  7068. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7069. */
  7070. Scalar.InverseLerp = function (a, b, value) {
  7071. var result = 0;
  7072. if (a != b) {
  7073. result = Scalar.Clamp((value - a) / (b - a));
  7074. }
  7075. else {
  7076. result = 0.0;
  7077. }
  7078. return result;
  7079. };
  7080. /**
  7081. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7082. */
  7083. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7084. var squared = amount * amount;
  7085. var cubed = amount * squared;
  7086. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7087. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7088. var part3 = (cubed - (2.0 * squared)) + amount;
  7089. var part4 = cubed - squared;
  7090. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7091. };
  7092. /**
  7093. * Returns a random float number between and min and max values
  7094. */
  7095. Scalar.RandomRange = function (min, max) {
  7096. if (min === max)
  7097. return min;
  7098. return ((Math.random() * (max - min)) + min);
  7099. };
  7100. /**
  7101. * This function returns percentage of a number in a given range.
  7102. *
  7103. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7104. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7105. */
  7106. Scalar.RangeToPercent = function (number, min, max) {
  7107. return ((number - min) / (max - min));
  7108. };
  7109. /**
  7110. * This function returns number that corresponds to the percentage in a given range.
  7111. *
  7112. * PercentToRange(0.34,0,100) will return 34.
  7113. */
  7114. Scalar.PercentToRange = function (percent, min, max) {
  7115. return ((max - min) * percent + min);
  7116. };
  7117. /**
  7118. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7119. * @param angle The angle to normalize in radian.
  7120. * @return The converted angle.
  7121. */
  7122. Scalar.NormalizeRadians = function (angle) {
  7123. // More precise but slower version kept for reference.
  7124. // angle = angle % Tools.TwoPi;
  7125. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7126. //if (angle > Math.PI) {
  7127. // angle -= Tools.TwoPi;
  7128. //}
  7129. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7130. return angle;
  7131. };
  7132. /**
  7133. * Two pi constants convenient for computation.
  7134. */
  7135. Scalar.TwoPi = Math.PI * 2;
  7136. return Scalar;
  7137. }());
  7138. BABYLON.Scalar = Scalar;
  7139. })(BABYLON || (BABYLON = {}));
  7140. //# sourceMappingURL=babylon.math.scalar.js.map
  7141. "use strict";
  7142. //# sourceMappingURL=babylon.mixins.js.map
  7143. "use strict";
  7144. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7145. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7146. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7147. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7148. //# sourceMappingURL=babylon.webgl2.js.map
  7149. "use strict";
  7150. var BABYLON;
  7151. (function (BABYLON) {
  7152. var __decoratorInitialStore = {};
  7153. var __mergedStore = {};
  7154. var _copySource = function (creationFunction, source, instanciate) {
  7155. var destination = creationFunction();
  7156. // Tags
  7157. if (BABYLON.Tags) {
  7158. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7159. }
  7160. var classStore = getMergedStore(destination);
  7161. // Properties
  7162. for (var property in classStore) {
  7163. var propertyDescriptor = classStore[property];
  7164. var sourceProperty = source[property];
  7165. var propertyType = propertyDescriptor.type;
  7166. if (sourceProperty !== undefined && sourceProperty !== null) {
  7167. switch (propertyType) {
  7168. case 0: // Value
  7169. case 6:// Mesh reference
  7170. destination[property] = sourceProperty;
  7171. break;
  7172. case 1:// Texture
  7173. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7174. break;
  7175. case 2: // Color3
  7176. case 3: // FresnelParameters
  7177. case 4: // Vector2
  7178. case 5: // Vector3
  7179. case 7: // Color Curves
  7180. case 10:// Quaternion
  7181. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7182. break;
  7183. }
  7184. }
  7185. }
  7186. return destination;
  7187. };
  7188. function getDirectStore(target) {
  7189. var classKey = target.getClassName();
  7190. if (!__decoratorInitialStore[classKey]) {
  7191. __decoratorInitialStore[classKey] = {};
  7192. }
  7193. return __decoratorInitialStore[classKey];
  7194. }
  7195. /**
  7196. * Return the list of properties flagged as serializable
  7197. * @param target: host object
  7198. */
  7199. function getMergedStore(target) {
  7200. var classKey = target.getClassName();
  7201. if (__mergedStore[classKey]) {
  7202. return __mergedStore[classKey];
  7203. }
  7204. __mergedStore[classKey] = {};
  7205. var store = __mergedStore[classKey];
  7206. var currentTarget = target;
  7207. var currentKey = classKey;
  7208. while (currentKey) {
  7209. var initialStore = __decoratorInitialStore[currentKey];
  7210. for (var property in initialStore) {
  7211. store[property] = initialStore[property];
  7212. }
  7213. var parent_1 = void 0;
  7214. var done = false;
  7215. do {
  7216. parent_1 = Object.getPrototypeOf(currentTarget);
  7217. if (!parent_1.getClassName) {
  7218. done = true;
  7219. break;
  7220. }
  7221. if (parent_1.getClassName() !== currentKey) {
  7222. break;
  7223. }
  7224. currentTarget = parent_1;
  7225. } while (parent_1);
  7226. if (done) {
  7227. break;
  7228. }
  7229. currentKey = parent_1.getClassName();
  7230. currentTarget = parent_1;
  7231. }
  7232. return store;
  7233. }
  7234. function generateSerializableMember(type, sourceName) {
  7235. return function (target, propertyKey) {
  7236. var classStore = getDirectStore(target);
  7237. if (!classStore[propertyKey]) {
  7238. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7239. }
  7240. };
  7241. }
  7242. function generateExpandMember(setCallback, targetKey) {
  7243. if (targetKey === void 0) { targetKey = null; }
  7244. return function (target, propertyKey) {
  7245. var key = targetKey || ("_" + propertyKey);
  7246. Object.defineProperty(target, propertyKey, {
  7247. get: function () {
  7248. return this[key];
  7249. },
  7250. set: function (value) {
  7251. if (this[key] === value) {
  7252. return;
  7253. }
  7254. this[key] = value;
  7255. target[setCallback].apply(this);
  7256. },
  7257. enumerable: true,
  7258. configurable: true
  7259. });
  7260. };
  7261. }
  7262. function expandToProperty(callback, targetKey) {
  7263. if (targetKey === void 0) { targetKey = null; }
  7264. return generateExpandMember(callback, targetKey);
  7265. }
  7266. BABYLON.expandToProperty = expandToProperty;
  7267. function serialize(sourceName) {
  7268. return generateSerializableMember(0, sourceName); // value member
  7269. }
  7270. BABYLON.serialize = serialize;
  7271. function serializeAsTexture(sourceName) {
  7272. return generateSerializableMember(1, sourceName); // texture member
  7273. }
  7274. BABYLON.serializeAsTexture = serializeAsTexture;
  7275. function serializeAsColor3(sourceName) {
  7276. return generateSerializableMember(2, sourceName); // color3 member
  7277. }
  7278. BABYLON.serializeAsColor3 = serializeAsColor3;
  7279. function serializeAsFresnelParameters(sourceName) {
  7280. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7281. }
  7282. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7283. function serializeAsVector2(sourceName) {
  7284. return generateSerializableMember(4, sourceName); // vector2 member
  7285. }
  7286. BABYLON.serializeAsVector2 = serializeAsVector2;
  7287. function serializeAsVector3(sourceName) {
  7288. return generateSerializableMember(5, sourceName); // vector3 member
  7289. }
  7290. BABYLON.serializeAsVector3 = serializeAsVector3;
  7291. function serializeAsMeshReference(sourceName) {
  7292. return generateSerializableMember(6, sourceName); // mesh reference member
  7293. }
  7294. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7295. function serializeAsColorCurves(sourceName) {
  7296. return generateSerializableMember(7, sourceName); // color curves
  7297. }
  7298. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7299. function serializeAsColor4(sourceName) {
  7300. return generateSerializableMember(8, sourceName); // color 4
  7301. }
  7302. BABYLON.serializeAsColor4 = serializeAsColor4;
  7303. function serializeAsImageProcessingConfiguration(sourceName) {
  7304. return generateSerializableMember(9, sourceName); // image processing
  7305. }
  7306. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7307. function serializeAsQuaternion(sourceName) {
  7308. return generateSerializableMember(10, sourceName); // quaternion member
  7309. }
  7310. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7311. var SerializationHelper = /** @class */ (function () {
  7312. function SerializationHelper() {
  7313. }
  7314. SerializationHelper.Serialize = function (entity, serializationObject) {
  7315. if (!serializationObject) {
  7316. serializationObject = {};
  7317. }
  7318. // Tags
  7319. if (BABYLON.Tags) {
  7320. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7321. }
  7322. var serializedProperties = getMergedStore(entity);
  7323. // Properties
  7324. for (var property in serializedProperties) {
  7325. var propertyDescriptor = serializedProperties[property];
  7326. var targetPropertyName = propertyDescriptor.sourceName || property;
  7327. var propertyType = propertyDescriptor.type;
  7328. var sourceProperty = entity[property];
  7329. if (sourceProperty !== undefined && sourceProperty !== null) {
  7330. switch (propertyType) {
  7331. case 0:// Value
  7332. serializationObject[targetPropertyName] = sourceProperty;
  7333. break;
  7334. case 1:// Texture
  7335. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7336. break;
  7337. case 2:// Color3
  7338. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7339. break;
  7340. case 3:// FresnelParameters
  7341. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7342. break;
  7343. case 4:// Vector2
  7344. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7345. break;
  7346. case 5:// Vector3
  7347. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7348. break;
  7349. case 6:// Mesh reference
  7350. serializationObject[targetPropertyName] = sourceProperty.id;
  7351. break;
  7352. case 7:// Color Curves
  7353. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7354. break;
  7355. case 8:// Color 4
  7356. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7357. break;
  7358. case 9:// Image Processing
  7359. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7360. break;
  7361. }
  7362. }
  7363. }
  7364. return serializationObject;
  7365. };
  7366. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7367. if (rootUrl === void 0) { rootUrl = null; }
  7368. var destination = creationFunction();
  7369. if (!rootUrl) {
  7370. rootUrl = "";
  7371. }
  7372. // Tags
  7373. if (BABYLON.Tags) {
  7374. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7375. }
  7376. var classStore = getMergedStore(destination);
  7377. // Properties
  7378. for (var property in classStore) {
  7379. var propertyDescriptor = classStore[property];
  7380. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7381. var propertyType = propertyDescriptor.type;
  7382. if (sourceProperty !== undefined && sourceProperty !== null) {
  7383. var dest = destination;
  7384. switch (propertyType) {
  7385. case 0:// Value
  7386. dest[property] = sourceProperty;
  7387. break;
  7388. case 1:// Texture
  7389. if (scene) {
  7390. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7391. }
  7392. break;
  7393. case 2:// Color3
  7394. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7395. break;
  7396. case 3:// FresnelParameters
  7397. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7398. break;
  7399. case 4:// Vector2
  7400. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7401. break;
  7402. case 5:// Vector3
  7403. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7404. break;
  7405. case 6:// Mesh reference
  7406. if (scene) {
  7407. dest[property] = scene.getLastMeshByID(sourceProperty);
  7408. }
  7409. break;
  7410. case 7:// Color Curves
  7411. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7412. break;
  7413. case 8:// Color 4
  7414. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7415. break;
  7416. case 9:// Image Processing
  7417. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7418. break;
  7419. }
  7420. }
  7421. }
  7422. return destination;
  7423. };
  7424. SerializationHelper.Clone = function (creationFunction, source) {
  7425. return _copySource(creationFunction, source, false);
  7426. };
  7427. SerializationHelper.Instanciate = function (creationFunction, source) {
  7428. return _copySource(creationFunction, source, true);
  7429. };
  7430. return SerializationHelper;
  7431. }());
  7432. BABYLON.SerializationHelper = SerializationHelper;
  7433. })(BABYLON || (BABYLON = {}));
  7434. //# sourceMappingURL=babylon.decorators.js.map
  7435. "use strict";
  7436. var BABYLON;
  7437. (function (BABYLON) {
  7438. /**
  7439. * Wrapper class for promise with external resolve and reject.
  7440. */
  7441. var Deferred = /** @class */ (function () {
  7442. /**
  7443. * Constructor for this deferred object.
  7444. */
  7445. function Deferred() {
  7446. var _this = this;
  7447. this.promise = new Promise(function (resolve, reject) {
  7448. _this._resolve = resolve;
  7449. _this._reject = reject;
  7450. });
  7451. }
  7452. Object.defineProperty(Deferred.prototype, "resolve", {
  7453. /**
  7454. * The resolve method of the promise associated with this deferred object.
  7455. */
  7456. get: function () {
  7457. return this._resolve;
  7458. },
  7459. enumerable: true,
  7460. configurable: true
  7461. });
  7462. Object.defineProperty(Deferred.prototype, "reject", {
  7463. /**
  7464. * The reject method of the promise associated with this deferred object.
  7465. */
  7466. get: function () {
  7467. return this._reject;
  7468. },
  7469. enumerable: true,
  7470. configurable: true
  7471. });
  7472. return Deferred;
  7473. }());
  7474. BABYLON.Deferred = Deferred;
  7475. })(BABYLON || (BABYLON = {}));
  7476. //# sourceMappingURL=babylon.deferred.js.map
  7477. "use strict";
  7478. var BABYLON;
  7479. (function (BABYLON) {
  7480. /**
  7481. * A class serves as a medium between the observable and its observers
  7482. */
  7483. var EventState = /** @class */ (function () {
  7484. /**
  7485. * Create a new EventState
  7486. * @param mask defines the mask associated with this state
  7487. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7488. * @param target defines the original target of the state
  7489. * @param currentTarget defines the current target of the state
  7490. */
  7491. function EventState(mask, skipNextObservers, target, currentTarget) {
  7492. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7493. this.initalize(mask, skipNextObservers, target, currentTarget);
  7494. }
  7495. /**
  7496. * Initialize the current event state
  7497. * @param mask defines the mask associated with this state
  7498. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7499. * @param target defines the original target of the state
  7500. * @param currentTarget defines the current target of the state
  7501. * @returns the current event state
  7502. */
  7503. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7504. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7505. this.mask = mask;
  7506. this.skipNextObservers = skipNextObservers;
  7507. this.target = target;
  7508. this.currentTarget = currentTarget;
  7509. return this;
  7510. };
  7511. return EventState;
  7512. }());
  7513. BABYLON.EventState = EventState;
  7514. /**
  7515. * Represent an Observer registered to a given Observable object.
  7516. */
  7517. var Observer = /** @class */ (function () {
  7518. /**
  7519. * Creates a new observer
  7520. * @param callback defines the callback to call when the observer is notified
  7521. * @param mask defines the mask of the observer (used to filter notifications)
  7522. * @param scope defines the current scope used to restore the JS context
  7523. */
  7524. function Observer(
  7525. /**
  7526. * Defines the callback to call when the observer is notified
  7527. */
  7528. callback,
  7529. /**
  7530. * Defines the mask of the observer (used to filter notifications)
  7531. */
  7532. mask,
  7533. /**
  7534. * Defines the current scope used to restore the JS context
  7535. */
  7536. scope) {
  7537. if (scope === void 0) { scope = null; }
  7538. this.callback = callback;
  7539. this.mask = mask;
  7540. this.scope = scope;
  7541. /** @ignore */
  7542. this._willBeUnregistered = false;
  7543. /**
  7544. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7545. */
  7546. this.unregisterOnNextCall = false;
  7547. }
  7548. return Observer;
  7549. }());
  7550. BABYLON.Observer = Observer;
  7551. /**
  7552. * Represent a list of observers registered to multiple Observables object.
  7553. */
  7554. var MultiObserver = /** @class */ (function () {
  7555. function MultiObserver() {
  7556. }
  7557. /**
  7558. * Release associated resources
  7559. */
  7560. MultiObserver.prototype.dispose = function () {
  7561. if (this._observers && this._observables) {
  7562. for (var index = 0; index < this._observers.length; index++) {
  7563. this._observables[index].remove(this._observers[index]);
  7564. }
  7565. }
  7566. this._observers = null;
  7567. this._observables = null;
  7568. };
  7569. /**
  7570. * Raise a callback when one of the observable will notify
  7571. * @param observables defines a list of observables to watch
  7572. * @param callback defines the callback to call on notification
  7573. * @param mask defines the mask used to filter notifications
  7574. * @param scope defines the current scope used to restore the JS context
  7575. * @returns the new MultiObserver
  7576. */
  7577. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7578. if (mask === void 0) { mask = -1; }
  7579. if (scope === void 0) { scope = null; }
  7580. var result = new MultiObserver();
  7581. result._observers = new Array();
  7582. result._observables = observables;
  7583. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7584. var observable = observables_1[_i];
  7585. var observer = observable.add(callback, mask, false, scope);
  7586. if (observer) {
  7587. result._observers.push(observer);
  7588. }
  7589. }
  7590. return result;
  7591. };
  7592. return MultiObserver;
  7593. }());
  7594. BABYLON.MultiObserver = MultiObserver;
  7595. /**
  7596. * The Observable class is a simple implementation of the Observable pattern.
  7597. *
  7598. * 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.
  7599. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7600. * 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).
  7601. * 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.
  7602. */
  7603. var Observable = /** @class */ (function () {
  7604. /**
  7605. * Creates a new observable
  7606. * @param onObserverAdded defines a callback to call when a new observer is added
  7607. */
  7608. function Observable(onObserverAdded) {
  7609. this._observers = new Array();
  7610. this._eventState = new EventState(0);
  7611. if (onObserverAdded) {
  7612. this._onObserverAdded = onObserverAdded;
  7613. }
  7614. }
  7615. /**
  7616. * Create a new Observer with the specified callback
  7617. * @param callback the callback that will be executed for that Observer
  7618. * @param mask the mask used to filter observers
  7619. * @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.
  7620. * @param scope optional scope for the callback to be called from
  7621. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7622. * @returns the new observer created for the callback
  7623. */
  7624. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7625. if (mask === void 0) { mask = -1; }
  7626. if (insertFirst === void 0) { insertFirst = false; }
  7627. if (scope === void 0) { scope = null; }
  7628. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7629. if (!callback) {
  7630. return null;
  7631. }
  7632. var observer = new Observer(callback, mask, scope);
  7633. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7634. if (insertFirst) {
  7635. this._observers.unshift(observer);
  7636. }
  7637. else {
  7638. this._observers.push(observer);
  7639. }
  7640. if (this._onObserverAdded) {
  7641. this._onObserverAdded(observer);
  7642. }
  7643. return observer;
  7644. };
  7645. /**
  7646. * Remove an Observer from the Observable object
  7647. * @param observer the instance of the Observer to remove
  7648. * @returns false if it doesn't belong to this Observable
  7649. */
  7650. Observable.prototype.remove = function (observer) {
  7651. if (!observer) {
  7652. return false;
  7653. }
  7654. var index = this._observers.indexOf(observer);
  7655. if (index !== -1) {
  7656. this._observers.splice(index, 1);
  7657. return true;
  7658. }
  7659. return false;
  7660. };
  7661. /**
  7662. * Remove a callback from the Observable object
  7663. * @param callback the callback to remove
  7664. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7665. * @returns false if it doesn't belong to this Observable
  7666. */
  7667. Observable.prototype.removeCallback = function (callback, scope) {
  7668. for (var index = 0; index < this._observers.length; index++) {
  7669. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7670. this._observers.splice(index, 1);
  7671. return true;
  7672. }
  7673. }
  7674. return false;
  7675. };
  7676. Observable.prototype._deferUnregister = function (observer) {
  7677. var _this = this;
  7678. observer.unregisterOnNextCall = false;
  7679. observer._willBeUnregistered = true;
  7680. BABYLON.Tools.SetImmediate(function () {
  7681. _this.remove(observer);
  7682. });
  7683. };
  7684. /**
  7685. * Notify all Observers by calling their respective callback with the given data
  7686. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7687. * @param eventData defines the data to send to all observers
  7688. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7689. * @param target defines the original target of the state
  7690. * @param currentTarget defines the current target of the state
  7691. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7692. */
  7693. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7694. if (mask === void 0) { mask = -1; }
  7695. if (!this._observers.length) {
  7696. return true;
  7697. }
  7698. var state = this._eventState;
  7699. state.mask = mask;
  7700. state.target = target;
  7701. state.currentTarget = currentTarget;
  7702. state.skipNextObservers = false;
  7703. state.lastReturnValue = eventData;
  7704. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7705. var obs = _a[_i];
  7706. if (obs._willBeUnregistered) {
  7707. continue;
  7708. }
  7709. if (obs.mask & mask) {
  7710. if (obs.scope) {
  7711. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7712. }
  7713. else {
  7714. state.lastReturnValue = obs.callback(eventData, state);
  7715. }
  7716. if (obs.unregisterOnNextCall) {
  7717. this._deferUnregister(obs);
  7718. }
  7719. }
  7720. if (state.skipNextObservers) {
  7721. return false;
  7722. }
  7723. }
  7724. return true;
  7725. };
  7726. /**
  7727. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7728. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7729. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7730. * and it is crucial that all callbacks will be executed.
  7731. * The order of the callbacks is kept, callbacks are not executed parallel.
  7732. *
  7733. * @param eventData The data to be sent to each callback
  7734. * @param mask is used to filter observers defaults to -1
  7735. * @param target defines the callback target (see EventState)
  7736. * @param currentTarget defines he current object in the bubbling phase
  7737. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7738. */
  7739. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7740. var _this = this;
  7741. if (mask === void 0) { mask = -1; }
  7742. // create an empty promise
  7743. var p = Promise.resolve(eventData);
  7744. // no observers? return this promise.
  7745. if (!this._observers.length) {
  7746. return p;
  7747. }
  7748. var state = this._eventState;
  7749. state.mask = mask;
  7750. state.target = target;
  7751. state.currentTarget = currentTarget;
  7752. state.skipNextObservers = false;
  7753. // execute one callback after another (not using Promise.all, the order is important)
  7754. this._observers.forEach(function (obs) {
  7755. if (state.skipNextObservers) {
  7756. return;
  7757. }
  7758. if (obs._willBeUnregistered) {
  7759. return;
  7760. }
  7761. if (obs.mask & mask) {
  7762. if (obs.scope) {
  7763. p = p.then(function (lastReturnedValue) {
  7764. state.lastReturnValue = lastReturnedValue;
  7765. return obs.callback.apply(obs.scope, [eventData, state]);
  7766. });
  7767. }
  7768. else {
  7769. p = p.then(function (lastReturnedValue) {
  7770. state.lastReturnValue = lastReturnedValue;
  7771. return obs.callback(eventData, state);
  7772. });
  7773. }
  7774. if (obs.unregisterOnNextCall) {
  7775. _this._deferUnregister(obs);
  7776. }
  7777. }
  7778. });
  7779. // return the eventData
  7780. return p.then(function () { return eventData; });
  7781. };
  7782. /**
  7783. * Notify a specific observer
  7784. * @param observer defines the observer to notify
  7785. * @param eventData defines the data to be sent to each callback
  7786. * @param mask is used to filter observers defaults to -1
  7787. */
  7788. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7789. if (mask === void 0) { mask = -1; }
  7790. var state = this._eventState;
  7791. state.mask = mask;
  7792. state.skipNextObservers = false;
  7793. observer.callback(eventData, state);
  7794. };
  7795. /**
  7796. * Gets a boolean indicating if the observable has at least one observer
  7797. * @returns true is the Observable has at least one Observer registered
  7798. */
  7799. Observable.prototype.hasObservers = function () {
  7800. return this._observers.length > 0;
  7801. };
  7802. /**
  7803. * Clear the list of observers
  7804. */
  7805. Observable.prototype.clear = function () {
  7806. this._observers = new Array();
  7807. this._onObserverAdded = null;
  7808. };
  7809. /**
  7810. * Clone the current observable
  7811. * @returns a new observable
  7812. */
  7813. Observable.prototype.clone = function () {
  7814. var result = new Observable();
  7815. result._observers = this._observers.slice(0);
  7816. return result;
  7817. };
  7818. /**
  7819. * Does this observable handles observer registered with a given mask
  7820. * @param mask defines the mask to be tested
  7821. * @return whether or not one observer registered with the given mask is handeled
  7822. **/
  7823. Observable.prototype.hasSpecificMask = function (mask) {
  7824. if (mask === void 0) { mask = -1; }
  7825. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7826. var obs = _a[_i];
  7827. if (obs.mask & mask || obs.mask === mask) {
  7828. return true;
  7829. }
  7830. }
  7831. return false;
  7832. };
  7833. return Observable;
  7834. }());
  7835. BABYLON.Observable = Observable;
  7836. })(BABYLON || (BABYLON = {}));
  7837. //# sourceMappingURL=babylon.observable.js.map
  7838. "use strict";
  7839. var BABYLON;
  7840. (function (BABYLON) {
  7841. var SmartArray = /** @class */ (function () {
  7842. function SmartArray(capacity) {
  7843. this.length = 0;
  7844. this.data = new Array(capacity);
  7845. this._id = SmartArray._GlobalId++;
  7846. }
  7847. SmartArray.prototype.push = function (value) {
  7848. this.data[this.length++] = value;
  7849. if (this.length > this.data.length) {
  7850. this.data.length *= 2;
  7851. }
  7852. };
  7853. SmartArray.prototype.forEach = function (func) {
  7854. for (var index = 0; index < this.length; index++) {
  7855. func(this.data[index]);
  7856. }
  7857. };
  7858. SmartArray.prototype.sort = function (compareFn) {
  7859. this.data.sort(compareFn);
  7860. };
  7861. SmartArray.prototype.reset = function () {
  7862. this.length = 0;
  7863. };
  7864. SmartArray.prototype.dispose = function () {
  7865. this.reset();
  7866. if (this.data) {
  7867. this.data.length = 0;
  7868. this.data = [];
  7869. }
  7870. };
  7871. SmartArray.prototype.concat = function (array) {
  7872. if (array.length === 0) {
  7873. return;
  7874. }
  7875. if (this.length + array.length > this.data.length) {
  7876. this.data.length = (this.length + array.length) * 2;
  7877. }
  7878. for (var index = 0; index < array.length; index++) {
  7879. this.data[this.length++] = (array.data || array)[index];
  7880. }
  7881. };
  7882. SmartArray.prototype.indexOf = function (value) {
  7883. var position = this.data.indexOf(value);
  7884. if (position >= this.length) {
  7885. return -1;
  7886. }
  7887. return position;
  7888. };
  7889. SmartArray.prototype.contains = function (value) {
  7890. return this.data.indexOf(value) !== -1;
  7891. };
  7892. // Statics
  7893. SmartArray._GlobalId = 0;
  7894. return SmartArray;
  7895. }());
  7896. BABYLON.SmartArray = SmartArray;
  7897. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7898. __extends(SmartArrayNoDuplicate, _super);
  7899. function SmartArrayNoDuplicate() {
  7900. var _this = _super !== null && _super.apply(this, arguments) || this;
  7901. _this._duplicateId = 0;
  7902. return _this;
  7903. }
  7904. SmartArrayNoDuplicate.prototype.push = function (value) {
  7905. _super.prototype.push.call(this, value);
  7906. if (!value.__smartArrayFlags) {
  7907. value.__smartArrayFlags = {};
  7908. }
  7909. value.__smartArrayFlags[this._id] = this._duplicateId;
  7910. };
  7911. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7912. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7913. return false;
  7914. }
  7915. this.push(value);
  7916. return true;
  7917. };
  7918. SmartArrayNoDuplicate.prototype.reset = function () {
  7919. _super.prototype.reset.call(this);
  7920. this._duplicateId++;
  7921. };
  7922. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7923. if (array.length === 0) {
  7924. return;
  7925. }
  7926. if (this.length + array.length > this.data.length) {
  7927. this.data.length = (this.length + array.length) * 2;
  7928. }
  7929. for (var index = 0; index < array.length; index++) {
  7930. var item = (array.data || array)[index];
  7931. this.pushNoDuplicate(item);
  7932. }
  7933. };
  7934. return SmartArrayNoDuplicate;
  7935. }(SmartArray));
  7936. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7937. })(BABYLON || (BABYLON = {}));
  7938. //# sourceMappingURL=babylon.smartArray.js.map
  7939. "use strict";
  7940. var BABYLON;
  7941. (function (BABYLON) {
  7942. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7943. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7944. var LoadFileError = /** @class */ (function (_super) {
  7945. __extends(LoadFileError, _super);
  7946. function LoadFileError(message, request) {
  7947. var _this = _super.call(this, message) || this;
  7948. _this.request = request;
  7949. _this.name = "LoadFileError";
  7950. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7951. return _this;
  7952. }
  7953. // Polyfill for Object.setPrototypeOf if necessary.
  7954. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7955. return LoadFileError;
  7956. }(Error));
  7957. BABYLON.LoadFileError = LoadFileError;
  7958. var RetryStrategy = /** @class */ (function () {
  7959. function RetryStrategy() {
  7960. }
  7961. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7962. if (maxRetries === void 0) { maxRetries = 3; }
  7963. if (baseInterval === void 0) { baseInterval = 500; }
  7964. return function (url, request, retryIndex) {
  7965. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7966. return -1;
  7967. }
  7968. return Math.pow(2, retryIndex) * baseInterval;
  7969. };
  7970. };
  7971. return RetryStrategy;
  7972. }());
  7973. BABYLON.RetryStrategy = RetryStrategy;
  7974. // Screenshots
  7975. var screenshotCanvas;
  7976. var cloneValue = function (source, destinationObject) {
  7977. if (!source)
  7978. return null;
  7979. if (source instanceof BABYLON.Mesh) {
  7980. return null;
  7981. }
  7982. if (source instanceof BABYLON.SubMesh) {
  7983. return source.clone(destinationObject);
  7984. }
  7985. else if (source.clone) {
  7986. return source.clone();
  7987. }
  7988. return null;
  7989. };
  7990. var Tools = /** @class */ (function () {
  7991. function Tools() {
  7992. }
  7993. /**
  7994. * Interpolates between a and b via alpha
  7995. * @param a The lower value (returned when alpha = 0)
  7996. * @param b The upper value (returned when alpha = 1)
  7997. * @param alpha The interpolation-factor
  7998. * @return The mixed value
  7999. */
  8000. Tools.Mix = function (a, b, alpha) {
  8001. return a * (1 - alpha) + b * alpha;
  8002. };
  8003. Tools.Instantiate = function (className) {
  8004. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8005. return Tools.RegisteredExternalClasses[className];
  8006. }
  8007. var arr = className.split(".");
  8008. var fn = (window || this);
  8009. for (var i = 0, len = arr.length; i < len; i++) {
  8010. fn = fn[arr[i]];
  8011. }
  8012. if (typeof fn !== "function") {
  8013. return null;
  8014. }
  8015. return fn;
  8016. };
  8017. /**
  8018. * Provides a slice function that will work even on IE
  8019. * @param data defines the array to slice
  8020. * @returns the new sliced array
  8021. */
  8022. Tools.Slice = function (data) {
  8023. if (data.slice) {
  8024. return data.slice();
  8025. }
  8026. return Array.prototype.slice.call(data);
  8027. };
  8028. Tools.SetImmediate = function (action) {
  8029. if (window.setImmediate) {
  8030. window.setImmediate(action);
  8031. }
  8032. else {
  8033. setTimeout(action, 1);
  8034. }
  8035. };
  8036. Tools.IsExponentOfTwo = function (value) {
  8037. var count = 1;
  8038. do {
  8039. count *= 2;
  8040. } while (count < value);
  8041. return count === value;
  8042. };
  8043. /**
  8044. * Find the next highest power of two.
  8045. * @param x Number to start search from.
  8046. * @return Next highest power of two.
  8047. */
  8048. Tools.CeilingPOT = function (x) {
  8049. x--;
  8050. x |= x >> 1;
  8051. x |= x >> 2;
  8052. x |= x >> 4;
  8053. x |= x >> 8;
  8054. x |= x >> 16;
  8055. x++;
  8056. return x;
  8057. };
  8058. /**
  8059. * Find the next lowest power of two.
  8060. * @param x Number to start search from.
  8061. * @return Next lowest power of two.
  8062. */
  8063. Tools.FloorPOT = function (x) {
  8064. x = x | (x >> 1);
  8065. x = x | (x >> 2);
  8066. x = x | (x >> 4);
  8067. x = x | (x >> 8);
  8068. x = x | (x >> 16);
  8069. return x - (x >> 1);
  8070. };
  8071. /**
  8072. * Find the nearest power of two.
  8073. * @param x Number to start search from.
  8074. * @return Next nearest power of two.
  8075. */
  8076. Tools.NearestPOT = function (x) {
  8077. var c = Tools.CeilingPOT(x);
  8078. var f = Tools.FloorPOT(x);
  8079. return (c - x) > (x - f) ? f : c;
  8080. };
  8081. Tools.GetExponentOfTwo = function (value, max, mode) {
  8082. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8083. var pot;
  8084. switch (mode) {
  8085. case BABYLON.Engine.SCALEMODE_FLOOR:
  8086. pot = Tools.FloorPOT(value);
  8087. break;
  8088. case BABYLON.Engine.SCALEMODE_NEAREST:
  8089. pot = Tools.NearestPOT(value);
  8090. break;
  8091. case BABYLON.Engine.SCALEMODE_CEILING:
  8092. default:
  8093. pot = Tools.CeilingPOT(value);
  8094. break;
  8095. }
  8096. return Math.min(pot, max);
  8097. };
  8098. Tools.GetFilename = function (path) {
  8099. var index = path.lastIndexOf("/");
  8100. if (index < 0)
  8101. return path;
  8102. return path.substring(index + 1);
  8103. };
  8104. /**
  8105. * Extracts the "folder" part of a path (everything before the filename).
  8106. * @param uri The URI to extract the info from
  8107. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8108. * @returns The "folder" part of the path
  8109. */
  8110. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8111. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8112. var index = uri.lastIndexOf("/");
  8113. if (index < 0) {
  8114. if (returnUnchangedIfNoSlash) {
  8115. return uri;
  8116. }
  8117. return "";
  8118. }
  8119. return uri.substring(0, index + 1);
  8120. };
  8121. Tools.GetDOMTextContent = function (element) {
  8122. var result = "";
  8123. var child = element.firstChild;
  8124. while (child) {
  8125. if (child.nodeType === 3) {
  8126. result += child.textContent;
  8127. }
  8128. child = child.nextSibling;
  8129. }
  8130. return result;
  8131. };
  8132. Tools.ToDegrees = function (angle) {
  8133. return angle * 180 / Math.PI;
  8134. };
  8135. Tools.ToRadians = function (angle) {
  8136. return angle * Math.PI / 180;
  8137. };
  8138. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8139. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8140. var output = "";
  8141. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8142. var i = 0;
  8143. var bytes = new Uint8Array(buffer);
  8144. while (i < bytes.length) {
  8145. chr1 = bytes[i++];
  8146. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8147. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8148. enc1 = chr1 >> 2;
  8149. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8150. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8151. enc4 = chr3 & 63;
  8152. if (isNaN(chr2)) {
  8153. enc3 = enc4 = 64;
  8154. }
  8155. else if (isNaN(chr3)) {
  8156. enc4 = 64;
  8157. }
  8158. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8159. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8160. }
  8161. return "data:image/png;base64," + output;
  8162. };
  8163. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8164. if (bias === void 0) { bias = null; }
  8165. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8166. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8167. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8168. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8169. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8170. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8171. }
  8172. if (bias) {
  8173. minimum.x -= minimum.x * bias.x + bias.y;
  8174. minimum.y -= minimum.y * bias.x + bias.y;
  8175. minimum.z -= minimum.z * bias.x + bias.y;
  8176. maximum.x += maximum.x * bias.x + bias.y;
  8177. maximum.y += maximum.y * bias.x + bias.y;
  8178. maximum.z += maximum.z * bias.x + bias.y;
  8179. }
  8180. return {
  8181. minimum: minimum,
  8182. maximum: maximum
  8183. };
  8184. };
  8185. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8186. if (bias === void 0) { bias = null; }
  8187. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8188. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8189. if (!stride) {
  8190. stride = 3;
  8191. }
  8192. for (var index = start; index < start + count; index++) {
  8193. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8194. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8195. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8196. }
  8197. if (bias) {
  8198. minimum.x -= minimum.x * bias.x + bias.y;
  8199. minimum.y -= minimum.y * bias.x + bias.y;
  8200. minimum.z -= minimum.z * bias.x + bias.y;
  8201. maximum.x += maximum.x * bias.x + bias.y;
  8202. maximum.y += maximum.y * bias.x + bias.y;
  8203. maximum.z += maximum.z * bias.x + bias.y;
  8204. }
  8205. return {
  8206. minimum: minimum,
  8207. maximum: maximum
  8208. };
  8209. };
  8210. Tools.Vector2ArrayFeeder = function (array) {
  8211. return function (index) {
  8212. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8213. var length = isFloatArray ? array.length / 2 : array.length;
  8214. if (index >= length) {
  8215. return null;
  8216. }
  8217. if (isFloatArray) {
  8218. var fa = array;
  8219. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8220. }
  8221. var a = array;
  8222. return a[index];
  8223. };
  8224. };
  8225. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8226. if (bias === void 0) { bias = null; }
  8227. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8228. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8229. var i = 0;
  8230. var cur = feeder(i++);
  8231. while (cur) {
  8232. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8233. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8234. cur = feeder(i++);
  8235. }
  8236. if (bias) {
  8237. minimum.x -= minimum.x * bias.x + bias.y;
  8238. minimum.y -= minimum.y * bias.x + bias.y;
  8239. maximum.x += maximum.x * bias.x + bias.y;
  8240. maximum.y += maximum.y * bias.x + bias.y;
  8241. }
  8242. return {
  8243. minimum: minimum,
  8244. maximum: maximum
  8245. };
  8246. };
  8247. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8248. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8249. return null;
  8250. return Array.isArray(obj) ? obj : [obj];
  8251. };
  8252. // Misc.
  8253. Tools.GetPointerPrefix = function () {
  8254. var eventPrefix = "pointer";
  8255. // Check if pointer events are supported
  8256. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8257. eventPrefix = "mouse";
  8258. }
  8259. return eventPrefix;
  8260. };
  8261. /**
  8262. * @param func - the function to be called
  8263. * @param requester - the object that will request the next frame. Falls back to window.
  8264. */
  8265. Tools.QueueNewFrame = function (func, requester) {
  8266. if (!Tools.IsWindowObjectExist()) {
  8267. return setTimeout(func, 16);
  8268. }
  8269. if (!requester) {
  8270. requester = window;
  8271. }
  8272. if (requester.requestAnimationFrame) {
  8273. return requester.requestAnimationFrame(func);
  8274. }
  8275. else if (requester.msRequestAnimationFrame) {
  8276. return requester.msRequestAnimationFrame(func);
  8277. }
  8278. else if (requester.webkitRequestAnimationFrame) {
  8279. return requester.webkitRequestAnimationFrame(func);
  8280. }
  8281. else if (requester.mozRequestAnimationFrame) {
  8282. return requester.mozRequestAnimationFrame(func);
  8283. }
  8284. else if (requester.oRequestAnimationFrame) {
  8285. return requester.oRequestAnimationFrame(func);
  8286. }
  8287. else {
  8288. return window.setTimeout(func, 16);
  8289. }
  8290. };
  8291. Tools.RequestFullscreen = function (element) {
  8292. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8293. if (!requestFunction)
  8294. return;
  8295. requestFunction.call(element);
  8296. };
  8297. Tools.ExitFullscreen = function () {
  8298. if (document.exitFullscreen) {
  8299. document.exitFullscreen();
  8300. }
  8301. else if (document.mozCancelFullScreen) {
  8302. document.mozCancelFullScreen();
  8303. }
  8304. else if (document.webkitCancelFullScreen) {
  8305. document.webkitCancelFullScreen();
  8306. }
  8307. else if (document.msCancelFullScreen) {
  8308. document.msCancelFullScreen();
  8309. }
  8310. };
  8311. Tools.SetCorsBehavior = function (url, element) {
  8312. if (url && url.indexOf("data:") === 0) {
  8313. return;
  8314. }
  8315. if (Tools.CorsBehavior) {
  8316. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8317. element.crossOrigin = Tools.CorsBehavior;
  8318. }
  8319. else {
  8320. var result = Tools.CorsBehavior(url);
  8321. if (result) {
  8322. element.crossOrigin = result;
  8323. }
  8324. }
  8325. }
  8326. };
  8327. // External files
  8328. Tools.CleanUrl = function (url) {
  8329. url = url.replace(/#/mg, "%23");
  8330. return url;
  8331. };
  8332. Tools.LoadImage = function (url, onLoad, onError, database) {
  8333. if (url instanceof ArrayBuffer) {
  8334. url = Tools.EncodeArrayBufferTobase64(url);
  8335. }
  8336. url = Tools.CleanUrl(url);
  8337. url = Tools.PreprocessUrl(url);
  8338. var img = new Image();
  8339. Tools.SetCorsBehavior(url, img);
  8340. var loadHandler = function () {
  8341. img.removeEventListener("load", loadHandler);
  8342. img.removeEventListener("error", errorHandler);
  8343. onLoad(img);
  8344. };
  8345. var errorHandler = function (err) {
  8346. img.removeEventListener("load", loadHandler);
  8347. img.removeEventListener("error", errorHandler);
  8348. Tools.Error("Error while trying to load image: " + url);
  8349. if (onError) {
  8350. onError("Error while trying to load image: " + url, err);
  8351. }
  8352. };
  8353. img.addEventListener("load", loadHandler);
  8354. img.addEventListener("error", errorHandler);
  8355. var noIndexedDB = function () {
  8356. img.src = url;
  8357. };
  8358. var loadFromIndexedDB = function () {
  8359. if (database) {
  8360. database.loadImageFromDB(url, img);
  8361. }
  8362. };
  8363. //ANY database to do!
  8364. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8365. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8366. }
  8367. else {
  8368. if (url.indexOf("file:") !== -1) {
  8369. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8370. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8371. try {
  8372. var blobURL;
  8373. try {
  8374. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8375. }
  8376. catch (ex) {
  8377. // Chrome doesn't support oneTimeOnly parameter
  8378. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8379. }
  8380. img.src = blobURL;
  8381. }
  8382. catch (e) {
  8383. img.src = "";
  8384. }
  8385. return img;
  8386. }
  8387. }
  8388. noIndexedDB();
  8389. }
  8390. return img;
  8391. };
  8392. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8393. url = Tools.CleanUrl(url);
  8394. url = Tools.PreprocessUrl(url);
  8395. // If file and file input are set
  8396. if (url.indexOf("file:") !== -1) {
  8397. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8398. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8399. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8400. }
  8401. }
  8402. var loadUrl = Tools.BaseUrl + url;
  8403. var aborted = false;
  8404. var fileRequest = {
  8405. onCompleteObservable: new BABYLON.Observable(),
  8406. abort: function () { return aborted = true; },
  8407. };
  8408. var requestFile = function () {
  8409. var request = new XMLHttpRequest();
  8410. var retryHandle = null;
  8411. fileRequest.abort = function () {
  8412. aborted = true;
  8413. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8414. request.abort();
  8415. }
  8416. if (retryHandle !== null) {
  8417. clearTimeout(retryHandle);
  8418. retryHandle = null;
  8419. }
  8420. };
  8421. var retryLoop = function (retryIndex) {
  8422. request.open('GET', loadUrl, true);
  8423. if (useArrayBuffer) {
  8424. request.responseType = "arraybuffer";
  8425. }
  8426. if (onProgress) {
  8427. request.addEventListener("progress", onProgress);
  8428. }
  8429. var onLoadEnd = function () {
  8430. request.removeEventListener("loadend", onLoadEnd);
  8431. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8432. fileRequest.onCompleteObservable.clear();
  8433. };
  8434. request.addEventListener("loadend", onLoadEnd);
  8435. var onReadyStateChange = function () {
  8436. if (aborted) {
  8437. return;
  8438. }
  8439. // In case of undefined state in some browsers.
  8440. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8441. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8442. request.removeEventListener("readystatechange", onReadyStateChange);
  8443. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8444. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8445. return;
  8446. }
  8447. var retryStrategy = Tools.DefaultRetryStrategy;
  8448. if (retryStrategy) {
  8449. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8450. if (waitTime !== -1) {
  8451. // Prevent the request from completing for retry.
  8452. request.removeEventListener("loadend", onLoadEnd);
  8453. request = new XMLHttpRequest();
  8454. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8455. return;
  8456. }
  8457. }
  8458. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8459. if (onError) {
  8460. onError(request, e);
  8461. }
  8462. else {
  8463. throw e;
  8464. }
  8465. }
  8466. };
  8467. request.addEventListener("readystatechange", onReadyStateChange);
  8468. request.send();
  8469. };
  8470. retryLoop(0);
  8471. };
  8472. // Caching all files
  8473. if (database && database.enableSceneOffline) {
  8474. var noIndexedDB_1 = function () {
  8475. if (!aborted) {
  8476. requestFile();
  8477. }
  8478. };
  8479. var loadFromIndexedDB = function () {
  8480. // TODO: database needs to support aborting and should return a IFileRequest
  8481. if (aborted) {
  8482. return;
  8483. }
  8484. if (database) {
  8485. database.loadFileFromDB(url, function (data) {
  8486. if (!aborted) {
  8487. onSuccess(data);
  8488. }
  8489. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8490. }, onProgress ? function (event) {
  8491. if (!aborted) {
  8492. onProgress(event);
  8493. }
  8494. } : undefined, noIndexedDB_1, useArrayBuffer);
  8495. }
  8496. };
  8497. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8498. }
  8499. else {
  8500. requestFile();
  8501. }
  8502. return fileRequest;
  8503. };
  8504. /**
  8505. * Load a script (identified by an url). When the url returns, the
  8506. * content of this file is added into a new script element, attached to the DOM (body element)
  8507. */
  8508. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8509. var head = document.getElementsByTagName('head')[0];
  8510. var script = document.createElement('script');
  8511. script.type = 'text/javascript';
  8512. script.src = scriptUrl;
  8513. script.onload = function () {
  8514. if (onSuccess) {
  8515. onSuccess();
  8516. }
  8517. };
  8518. script.onerror = function (e) {
  8519. if (onError) {
  8520. onError("Unable to load script", e);
  8521. }
  8522. };
  8523. head.appendChild(script);
  8524. };
  8525. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8526. var reader = new FileReader();
  8527. var request = {
  8528. onCompleteObservable: new BABYLON.Observable(),
  8529. abort: function () { return reader.abort(); },
  8530. };
  8531. reader.onloadend = function (e) {
  8532. request.onCompleteObservable.notifyObservers(request);
  8533. };
  8534. reader.onload = function (e) {
  8535. //target doesn't have result from ts 1.3
  8536. callback(e.target['result']);
  8537. };
  8538. reader.onprogress = progressCallback;
  8539. reader.readAsDataURL(fileToLoad);
  8540. return request;
  8541. };
  8542. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8543. var reader = new FileReader();
  8544. var request = {
  8545. onCompleteObservable: new BABYLON.Observable(),
  8546. abort: function () { return reader.abort(); },
  8547. };
  8548. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8549. reader.onerror = function (e) {
  8550. Tools.Log("Error while reading file: " + fileToLoad.name);
  8551. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8552. };
  8553. reader.onload = function (e) {
  8554. //target doesn't have result from ts 1.3
  8555. callback(e.target['result']);
  8556. };
  8557. if (progressCallBack) {
  8558. reader.onprogress = progressCallBack;
  8559. }
  8560. if (!useArrayBuffer) {
  8561. // Asynchronous read
  8562. reader.readAsText(fileToLoad);
  8563. }
  8564. else {
  8565. reader.readAsArrayBuffer(fileToLoad);
  8566. }
  8567. return request;
  8568. };
  8569. //returns a downloadable url to a file content.
  8570. Tools.FileAsURL = function (content) {
  8571. var fileBlob = new Blob([content]);
  8572. var url = window.URL || window.webkitURL;
  8573. var link = url.createObjectURL(fileBlob);
  8574. return link;
  8575. };
  8576. // Misc.
  8577. Tools.Format = function (value, decimals) {
  8578. if (decimals === void 0) { decimals = 2; }
  8579. return value.toFixed(decimals);
  8580. };
  8581. Tools.CheckExtends = function (v, min, max) {
  8582. if (v.x < min.x)
  8583. min.x = v.x;
  8584. if (v.y < min.y)
  8585. min.y = v.y;
  8586. if (v.z < min.z)
  8587. min.z = v.z;
  8588. if (v.x > max.x)
  8589. max.x = v.x;
  8590. if (v.y > max.y)
  8591. max.y = v.y;
  8592. if (v.z > max.z)
  8593. max.z = v.z;
  8594. };
  8595. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8596. for (var prop in source) {
  8597. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8598. continue;
  8599. }
  8600. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8601. continue;
  8602. }
  8603. var sourceValue = source[prop];
  8604. var typeOfSourceValue = typeof sourceValue;
  8605. if (typeOfSourceValue === "function") {
  8606. continue;
  8607. }
  8608. try {
  8609. if (typeOfSourceValue === "object") {
  8610. if (sourceValue instanceof Array) {
  8611. destination[prop] = [];
  8612. if (sourceValue.length > 0) {
  8613. if (typeof sourceValue[0] == "object") {
  8614. for (var index = 0; index < sourceValue.length; index++) {
  8615. var clonedValue = cloneValue(sourceValue[index], destination);
  8616. if (destination[prop].indexOf(clonedValue) === -1) {
  8617. destination[prop].push(clonedValue);
  8618. }
  8619. }
  8620. }
  8621. else {
  8622. destination[prop] = sourceValue.slice(0);
  8623. }
  8624. }
  8625. }
  8626. else {
  8627. destination[prop] = cloneValue(sourceValue, destination);
  8628. }
  8629. }
  8630. else {
  8631. destination[prop] = sourceValue;
  8632. }
  8633. }
  8634. catch (e) {
  8635. // Just ignore error (it could be because of a read-only property)
  8636. }
  8637. }
  8638. };
  8639. Tools.IsEmpty = function (obj) {
  8640. for (var i in obj) {
  8641. if (obj.hasOwnProperty(i)) {
  8642. return false;
  8643. }
  8644. }
  8645. return true;
  8646. };
  8647. Tools.RegisterTopRootEvents = function (events) {
  8648. for (var index = 0; index < events.length; index++) {
  8649. var event = events[index];
  8650. window.addEventListener(event.name, event.handler, false);
  8651. try {
  8652. if (window.parent) {
  8653. window.parent.addEventListener(event.name, event.handler, false);
  8654. }
  8655. }
  8656. catch (e) {
  8657. // Silently fails...
  8658. }
  8659. }
  8660. };
  8661. Tools.UnregisterTopRootEvents = function (events) {
  8662. for (var index = 0; index < events.length; index++) {
  8663. var event = events[index];
  8664. window.removeEventListener(event.name, event.handler);
  8665. try {
  8666. if (window.parent) {
  8667. window.parent.removeEventListener(event.name, event.handler);
  8668. }
  8669. }
  8670. catch (e) {
  8671. // Silently fails...
  8672. }
  8673. }
  8674. };
  8675. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8676. if (mimeType === void 0) { mimeType = "image/png"; }
  8677. // Read the contents of the framebuffer
  8678. var numberOfChannelsByLine = width * 4;
  8679. var halfHeight = height / 2;
  8680. //Reading datas from WebGL
  8681. var data = engine.readPixels(0, 0, width, height);
  8682. //To flip image on Y axis.
  8683. for (var i = 0; i < halfHeight; i++) {
  8684. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8685. var currentCell = j + i * numberOfChannelsByLine;
  8686. var targetLine = height - i - 1;
  8687. var targetCell = j + targetLine * numberOfChannelsByLine;
  8688. var temp = data[currentCell];
  8689. data[currentCell] = data[targetCell];
  8690. data[targetCell] = temp;
  8691. }
  8692. }
  8693. // Create a 2D canvas to store the result
  8694. if (!screenshotCanvas) {
  8695. screenshotCanvas = document.createElement('canvas');
  8696. }
  8697. screenshotCanvas.width = width;
  8698. screenshotCanvas.height = height;
  8699. var context = screenshotCanvas.getContext('2d');
  8700. if (context) {
  8701. // Copy the pixels to a 2D canvas
  8702. var imageData = context.createImageData(width, height);
  8703. var castData = (imageData.data);
  8704. castData.set(data);
  8705. context.putImageData(imageData, 0, 0);
  8706. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8707. }
  8708. };
  8709. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8710. if (mimeType === void 0) { mimeType = "image/png"; }
  8711. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8712. if (successCallback) {
  8713. successCallback(base64Image);
  8714. }
  8715. else {
  8716. // We need HTMLCanvasElement.toBlob for HD screenshots
  8717. if (!screenshotCanvas.toBlob) {
  8718. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8719. screenshotCanvas.toBlob = function (callback, type, quality) {
  8720. var _this = this;
  8721. setTimeout(function () {
  8722. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8723. for (var i = 0; i < len; i++) {
  8724. arr[i] = binStr.charCodeAt(i);
  8725. }
  8726. callback(new Blob([arr], { type: type || 'image/png' }));
  8727. });
  8728. };
  8729. }
  8730. screenshotCanvas.toBlob(function (blob) {
  8731. var url = URL.createObjectURL(blob);
  8732. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8733. if (("download" in document.createElement("a"))) {
  8734. var a = window.document.createElement("a");
  8735. a.href = url;
  8736. if (fileName) {
  8737. a.setAttribute("download", fileName);
  8738. }
  8739. else {
  8740. var date = new Date();
  8741. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8742. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8743. }
  8744. window.document.body.appendChild(a);
  8745. a.addEventListener("click", function () {
  8746. if (a.parentElement) {
  8747. a.parentElement.removeChild(a);
  8748. }
  8749. });
  8750. a.click();
  8751. }
  8752. else {
  8753. var newWindow = window.open("");
  8754. if (!newWindow)
  8755. return;
  8756. var img = newWindow.document.createElement("img");
  8757. img.onload = function () {
  8758. // no longer need to read the blob so it's revoked
  8759. URL.revokeObjectURL(url);
  8760. };
  8761. img.src = url;
  8762. newWindow.document.body.appendChild(img);
  8763. }
  8764. });
  8765. }
  8766. };
  8767. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8768. if (mimeType === void 0) { mimeType = "image/png"; }
  8769. var width;
  8770. var height;
  8771. // If a precision value is specified
  8772. if (size.precision) {
  8773. width = Math.round(engine.getRenderWidth() * size.precision);
  8774. height = Math.round(width / engine.getAspectRatio(camera));
  8775. }
  8776. else if (size.width && size.height) {
  8777. width = size.width;
  8778. height = size.height;
  8779. }
  8780. else if (size.width && !size.height) {
  8781. width = size.width;
  8782. height = Math.round(width / engine.getAspectRatio(camera));
  8783. }
  8784. else if (size.height && !size.width) {
  8785. height = size.height;
  8786. width = Math.round(height * engine.getAspectRatio(camera));
  8787. }
  8788. else if (!isNaN(size)) {
  8789. height = size;
  8790. width = size;
  8791. }
  8792. else {
  8793. Tools.Error("Invalid 'size' parameter !");
  8794. return;
  8795. }
  8796. if (!screenshotCanvas) {
  8797. screenshotCanvas = document.createElement('canvas');
  8798. }
  8799. screenshotCanvas.width = width;
  8800. screenshotCanvas.height = height;
  8801. var renderContext = screenshotCanvas.getContext("2d");
  8802. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8803. var newWidth = width;
  8804. var newHeight = newWidth / ratio;
  8805. if (newHeight > height) {
  8806. newHeight = height;
  8807. newWidth = newHeight * ratio;
  8808. }
  8809. var offsetX = Math.max(0, width - newWidth) / 2;
  8810. var offsetY = Math.max(0, height - newHeight) / 2;
  8811. var renderingCanvas = engine.getRenderingCanvas();
  8812. if (renderContext && renderingCanvas) {
  8813. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8814. }
  8815. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8816. };
  8817. /**
  8818. * Generates an image screenshot from the specified camera.
  8819. *
  8820. * @param engine The engine to use for rendering
  8821. * @param camera The camera to use for rendering
  8822. * @param size This parameter can be set to a single number or to an object with the
  8823. * following (optional) properties: precision, width, height. If a single number is passed,
  8824. * it will be used for both width and height. If an object is passed, the screenshot size
  8825. * will be derived from the parameters. The precision property is a multiplier allowing
  8826. * rendering at a higher or lower resolution.
  8827. * @param successCallback The callback receives a single parameter which contains the
  8828. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8829. * src parameter of an <img> to display it.
  8830. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8831. * Check your browser for supported MIME types.
  8832. * @param samples Texture samples (default: 1)
  8833. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8834. * @param fileName A name for for the downloaded file.
  8835. * @constructor
  8836. */
  8837. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8838. if (mimeType === void 0) { mimeType = "image/png"; }
  8839. if (samples === void 0) { samples = 1; }
  8840. if (antialiasing === void 0) { antialiasing = false; }
  8841. var width;
  8842. var height;
  8843. //If a precision value is specified
  8844. if (size.precision) {
  8845. width = Math.round(engine.getRenderWidth() * size.precision);
  8846. height = Math.round(width / engine.getAspectRatio(camera));
  8847. size = { width: width, height: height };
  8848. }
  8849. else if (size.width && size.height) {
  8850. width = size.width;
  8851. height = size.height;
  8852. }
  8853. else if (size.width && !size.height) {
  8854. width = size.width;
  8855. height = Math.round(width / engine.getAspectRatio(camera));
  8856. size = { width: width, height: height };
  8857. }
  8858. else if (size.height && !size.width) {
  8859. height = size.height;
  8860. width = Math.round(height * engine.getAspectRatio(camera));
  8861. size = { width: width, height: height };
  8862. }
  8863. else if (!isNaN(size)) {
  8864. height = size;
  8865. width = size;
  8866. }
  8867. else {
  8868. Tools.Error("Invalid 'size' parameter !");
  8869. return;
  8870. }
  8871. var scene = camera.getScene();
  8872. var previousCamera = null;
  8873. if (scene.activeCamera !== camera) {
  8874. previousCamera = scene.activeCamera;
  8875. scene.activeCamera = camera;
  8876. }
  8877. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8878. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8879. texture.renderList = null;
  8880. texture.samples = samples;
  8881. if (antialiasing) {
  8882. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8883. }
  8884. texture.onAfterRenderObservable.add(function () {
  8885. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8886. });
  8887. scene.incrementRenderId();
  8888. scene.resetCachedMaterial();
  8889. texture.render(true);
  8890. texture.dispose();
  8891. if (previousCamera) {
  8892. scene.activeCamera = previousCamera;
  8893. }
  8894. camera.getProjectionMatrix(true); // Force cache refresh;
  8895. };
  8896. // XHR response validator for local file scenario
  8897. Tools.ValidateXHRData = function (xhr, dataType) {
  8898. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8899. if (dataType === void 0) { dataType = 7; }
  8900. try {
  8901. if (dataType & 1) {
  8902. if (xhr.responseText && xhr.responseText.length > 0) {
  8903. return true;
  8904. }
  8905. else if (dataType === 1) {
  8906. return false;
  8907. }
  8908. }
  8909. if (dataType & 2) {
  8910. // Check header width and height since there is no "TGA" magic number
  8911. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8912. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8913. return true;
  8914. }
  8915. else if (dataType === 2) {
  8916. return false;
  8917. }
  8918. }
  8919. if (dataType & 4) {
  8920. // Check for the "DDS" magic number
  8921. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8922. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8923. return true;
  8924. }
  8925. else {
  8926. return false;
  8927. }
  8928. }
  8929. }
  8930. catch (e) {
  8931. // Global protection
  8932. }
  8933. return false;
  8934. };
  8935. /**
  8936. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8937. * Be aware Math.random() could cause collisions, but:
  8938. * "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"
  8939. */
  8940. Tools.RandomId = function () {
  8941. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8942. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8943. return v.toString(16);
  8944. });
  8945. };
  8946. /**
  8947. * Test if the given uri is a base64 string.
  8948. * @param uri The uri to test
  8949. * @return True if the uri is a base64 string or false otherwise.
  8950. */
  8951. Tools.IsBase64 = function (uri) {
  8952. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8953. };
  8954. /**
  8955. * Decode the given base64 uri.
  8956. * @param uri The uri to decode
  8957. * @return The decoded base64 data.
  8958. */
  8959. Tools.DecodeBase64 = function (uri) {
  8960. var decodedString = atob(uri.split(",")[1]);
  8961. var bufferLength = decodedString.length;
  8962. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8963. for (var i = 0; i < bufferLength; i++) {
  8964. bufferView[i] = decodedString.charCodeAt(i);
  8965. }
  8966. return bufferView.buffer;
  8967. };
  8968. Object.defineProperty(Tools, "NoneLogLevel", {
  8969. get: function () {
  8970. return Tools._NoneLogLevel;
  8971. },
  8972. enumerable: true,
  8973. configurable: true
  8974. });
  8975. Object.defineProperty(Tools, "MessageLogLevel", {
  8976. get: function () {
  8977. return Tools._MessageLogLevel;
  8978. },
  8979. enumerable: true,
  8980. configurable: true
  8981. });
  8982. Object.defineProperty(Tools, "WarningLogLevel", {
  8983. get: function () {
  8984. return Tools._WarningLogLevel;
  8985. },
  8986. enumerable: true,
  8987. configurable: true
  8988. });
  8989. Object.defineProperty(Tools, "ErrorLogLevel", {
  8990. get: function () {
  8991. return Tools._ErrorLogLevel;
  8992. },
  8993. enumerable: true,
  8994. configurable: true
  8995. });
  8996. Object.defineProperty(Tools, "AllLogLevel", {
  8997. get: function () {
  8998. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8999. },
  9000. enumerable: true,
  9001. configurable: true
  9002. });
  9003. Tools._AddLogEntry = function (entry) {
  9004. Tools._LogCache = entry + Tools._LogCache;
  9005. if (Tools.OnNewCacheEntry) {
  9006. Tools.OnNewCacheEntry(entry);
  9007. }
  9008. };
  9009. Tools._FormatMessage = function (message) {
  9010. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9011. var date = new Date();
  9012. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9013. };
  9014. Tools._LogDisabled = function (message) {
  9015. // nothing to do
  9016. };
  9017. Tools._LogEnabled = function (message) {
  9018. var formattedMessage = Tools._FormatMessage(message);
  9019. console.log("BJS - " + formattedMessage);
  9020. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9021. Tools._AddLogEntry(entry);
  9022. };
  9023. Tools._WarnDisabled = function (message) {
  9024. // nothing to do
  9025. };
  9026. Tools._WarnEnabled = function (message) {
  9027. var formattedMessage = Tools._FormatMessage(message);
  9028. console.warn("BJS - " + formattedMessage);
  9029. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9030. Tools._AddLogEntry(entry);
  9031. };
  9032. Tools._ErrorDisabled = function (message) {
  9033. // nothing to do
  9034. };
  9035. Tools._ErrorEnabled = function (message) {
  9036. Tools.errorsCount++;
  9037. var formattedMessage = Tools._FormatMessage(message);
  9038. console.error("BJS - " + formattedMessage);
  9039. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9040. Tools._AddLogEntry(entry);
  9041. };
  9042. Object.defineProperty(Tools, "LogCache", {
  9043. get: function () {
  9044. return Tools._LogCache;
  9045. },
  9046. enumerable: true,
  9047. configurable: true
  9048. });
  9049. Tools.ClearLogCache = function () {
  9050. Tools._LogCache = "";
  9051. Tools.errorsCount = 0;
  9052. };
  9053. Object.defineProperty(Tools, "LogLevels", {
  9054. set: function (level) {
  9055. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9056. Tools.Log = Tools._LogEnabled;
  9057. }
  9058. else {
  9059. Tools.Log = Tools._LogDisabled;
  9060. }
  9061. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9062. Tools.Warn = Tools._WarnEnabled;
  9063. }
  9064. else {
  9065. Tools.Warn = Tools._WarnDisabled;
  9066. }
  9067. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9068. Tools.Error = Tools._ErrorEnabled;
  9069. }
  9070. else {
  9071. Tools.Error = Tools._ErrorDisabled;
  9072. }
  9073. },
  9074. enumerable: true,
  9075. configurable: true
  9076. });
  9077. Tools.IsWindowObjectExist = function () {
  9078. return (typeof window) !== "undefined";
  9079. };
  9080. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9081. get: function () {
  9082. return Tools._PerformanceNoneLogLevel;
  9083. },
  9084. enumerable: true,
  9085. configurable: true
  9086. });
  9087. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9088. get: function () {
  9089. return Tools._PerformanceUserMarkLogLevel;
  9090. },
  9091. enumerable: true,
  9092. configurable: true
  9093. });
  9094. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9095. get: function () {
  9096. return Tools._PerformanceConsoleLogLevel;
  9097. },
  9098. enumerable: true,
  9099. configurable: true
  9100. });
  9101. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9102. set: function (level) {
  9103. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9104. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9105. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9106. return;
  9107. }
  9108. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9109. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9110. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9111. return;
  9112. }
  9113. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9114. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9115. },
  9116. enumerable: true,
  9117. configurable: true
  9118. });
  9119. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9120. };
  9121. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9122. };
  9123. Tools._StartUserMark = function (counterName, condition) {
  9124. if (condition === void 0) { condition = true; }
  9125. if (!Tools._performance) {
  9126. if (!Tools.IsWindowObjectExist()) {
  9127. return;
  9128. }
  9129. Tools._performance = window.performance;
  9130. }
  9131. if (!condition || !Tools._performance.mark) {
  9132. return;
  9133. }
  9134. Tools._performance.mark(counterName + "-Begin");
  9135. };
  9136. Tools._EndUserMark = function (counterName, condition) {
  9137. if (condition === void 0) { condition = true; }
  9138. if (!condition || !Tools._performance.mark) {
  9139. return;
  9140. }
  9141. Tools._performance.mark(counterName + "-End");
  9142. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9143. };
  9144. Tools._StartPerformanceConsole = function (counterName, condition) {
  9145. if (condition === void 0) { condition = true; }
  9146. if (!condition) {
  9147. return;
  9148. }
  9149. Tools._StartUserMark(counterName, condition);
  9150. if (console.time) {
  9151. console.time(counterName);
  9152. }
  9153. };
  9154. Tools._EndPerformanceConsole = function (counterName, condition) {
  9155. if (condition === void 0) { condition = true; }
  9156. if (!condition) {
  9157. return;
  9158. }
  9159. Tools._EndUserMark(counterName, condition);
  9160. if (console.time) {
  9161. console.timeEnd(counterName);
  9162. }
  9163. };
  9164. Object.defineProperty(Tools, "Now", {
  9165. get: function () {
  9166. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9167. return window.performance.now();
  9168. }
  9169. return new Date().getTime();
  9170. },
  9171. enumerable: true,
  9172. configurable: true
  9173. });
  9174. /**
  9175. * This method will return the name of the class used to create the instance of the given object.
  9176. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9177. * @param object the object to get the class name from
  9178. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9179. */
  9180. Tools.GetClassName = function (object, isType) {
  9181. if (isType === void 0) { isType = false; }
  9182. var name = null;
  9183. if (!isType && object.getClassName) {
  9184. name = object.getClassName();
  9185. }
  9186. else {
  9187. if (object instanceof Object) {
  9188. var classObj = isType ? object : Object.getPrototypeOf(object);
  9189. name = classObj.constructor["__bjsclassName__"];
  9190. }
  9191. if (!name) {
  9192. name = typeof object;
  9193. }
  9194. }
  9195. return name;
  9196. };
  9197. Tools.First = function (array, predicate) {
  9198. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9199. var el = array_1[_i];
  9200. if (predicate(el)) {
  9201. return el;
  9202. }
  9203. }
  9204. return null;
  9205. };
  9206. /**
  9207. * This method will return the name of the full name of the class, including its owning module (if any).
  9208. * 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).
  9209. * @param object the object to get the class name from
  9210. * @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.
  9211. */
  9212. Tools.getFullClassName = function (object, isType) {
  9213. if (isType === void 0) { isType = false; }
  9214. var className = null;
  9215. var moduleName = null;
  9216. if (!isType && object.getClassName) {
  9217. className = object.getClassName();
  9218. }
  9219. else {
  9220. if (object instanceof Object) {
  9221. var classObj = isType ? object : Object.getPrototypeOf(object);
  9222. className = classObj.constructor["__bjsclassName__"];
  9223. moduleName = classObj.constructor["__bjsmoduleName__"];
  9224. }
  9225. if (!className) {
  9226. className = typeof object;
  9227. }
  9228. }
  9229. if (!className) {
  9230. return null;
  9231. }
  9232. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9233. };
  9234. /**
  9235. * 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.
  9236. * @param array
  9237. */
  9238. Tools.arrayOrStringFeeder = function (array) {
  9239. return function (index) {
  9240. if (index >= array.length) {
  9241. return null;
  9242. }
  9243. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9244. if (val && val.getHashCode) {
  9245. val = val.getHashCode();
  9246. }
  9247. if (typeof val === "string") {
  9248. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9249. }
  9250. return val;
  9251. };
  9252. };
  9253. /**
  9254. * Compute the hashCode of a stream of number
  9255. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9256. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9257. * @return the hash code computed
  9258. */
  9259. Tools.hashCodeFromStream = function (feeder) {
  9260. // Based from here: http://stackoverflow.com/a/7616484/802124
  9261. var hash = 0;
  9262. var index = 0;
  9263. var chr = feeder(index++);
  9264. while (chr != null) {
  9265. hash = ((hash << 5) - hash) + chr;
  9266. hash |= 0; // Convert to 32bit integer
  9267. chr = feeder(index++);
  9268. }
  9269. return hash;
  9270. };
  9271. /**
  9272. * Returns a promise that resolves after the given amount of time.
  9273. * @param delay Number of milliseconds to delay
  9274. * @returns Promise that resolves after the given amount of time
  9275. */
  9276. Tools.DelayAsync = function (delay) {
  9277. return new Promise(function (resolve) {
  9278. setTimeout(function () {
  9279. resolve();
  9280. }, delay);
  9281. });
  9282. };
  9283. Tools.BaseUrl = "";
  9284. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9285. /**
  9286. * Default behaviour for cors in the application.
  9287. * It can be a string if the expected behavior is identical in the entire app.
  9288. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9289. */
  9290. Tools.CorsBehavior = "anonymous";
  9291. Tools.UseFallbackTexture = true;
  9292. /**
  9293. * Use this object to register external classes like custom textures or material
  9294. * to allow the laoders to instantiate them
  9295. */
  9296. Tools.RegisteredExternalClasses = {};
  9297. // Used in case of a texture loading problem
  9298. Tools.fallbackTexture = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  9299. Tools.PreprocessUrl = function (url) {
  9300. return url;
  9301. };
  9302. // Logs
  9303. Tools._NoneLogLevel = 0;
  9304. Tools._MessageLogLevel = 1;
  9305. Tools._WarningLogLevel = 2;
  9306. Tools._ErrorLogLevel = 4;
  9307. Tools._LogCache = "";
  9308. Tools.errorsCount = 0;
  9309. Tools.Log = Tools._LogEnabled;
  9310. Tools.Warn = Tools._WarnEnabled;
  9311. Tools.Error = Tools._ErrorEnabled;
  9312. // Performances
  9313. Tools._PerformanceNoneLogLevel = 0;
  9314. Tools._PerformanceUserMarkLogLevel = 1;
  9315. Tools._PerformanceConsoleLogLevel = 2;
  9316. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9317. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9318. return Tools;
  9319. }());
  9320. BABYLON.Tools = Tools;
  9321. /**
  9322. * This class is used to track a performance counter which is number based.
  9323. * The user has access to many properties which give statistics of different nature
  9324. *
  9325. * The implementer can track two kinds of Performance Counter: time and count
  9326. * 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.
  9327. * 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.
  9328. */
  9329. var PerfCounter = /** @class */ (function () {
  9330. function PerfCounter() {
  9331. this._startMonitoringTime = 0;
  9332. this._min = 0;
  9333. this._max = 0;
  9334. this._average = 0;
  9335. this._lastSecAverage = 0;
  9336. this._current = 0;
  9337. this._totalValueCount = 0;
  9338. this._totalAccumulated = 0;
  9339. this._lastSecAccumulated = 0;
  9340. this._lastSecTime = 0;
  9341. this._lastSecValueCount = 0;
  9342. }
  9343. Object.defineProperty(PerfCounter.prototype, "min", {
  9344. /**
  9345. * Returns the smallest value ever
  9346. */
  9347. get: function () {
  9348. return this._min;
  9349. },
  9350. enumerable: true,
  9351. configurable: true
  9352. });
  9353. Object.defineProperty(PerfCounter.prototype, "max", {
  9354. /**
  9355. * Returns the biggest value ever
  9356. */
  9357. get: function () {
  9358. return this._max;
  9359. },
  9360. enumerable: true,
  9361. configurable: true
  9362. });
  9363. Object.defineProperty(PerfCounter.prototype, "average", {
  9364. /**
  9365. * Returns the average value since the performance counter is running
  9366. */
  9367. get: function () {
  9368. return this._average;
  9369. },
  9370. enumerable: true,
  9371. configurable: true
  9372. });
  9373. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9374. /**
  9375. * Returns the average value of the last second the counter was monitored
  9376. */
  9377. get: function () {
  9378. return this._lastSecAverage;
  9379. },
  9380. enumerable: true,
  9381. configurable: true
  9382. });
  9383. Object.defineProperty(PerfCounter.prototype, "current", {
  9384. /**
  9385. * Returns the current value
  9386. */
  9387. get: function () {
  9388. return this._current;
  9389. },
  9390. enumerable: true,
  9391. configurable: true
  9392. });
  9393. Object.defineProperty(PerfCounter.prototype, "total", {
  9394. get: function () {
  9395. return this._totalAccumulated;
  9396. },
  9397. enumerable: true,
  9398. configurable: true
  9399. });
  9400. Object.defineProperty(PerfCounter.prototype, "count", {
  9401. get: function () {
  9402. return this._totalValueCount;
  9403. },
  9404. enumerable: true,
  9405. configurable: true
  9406. });
  9407. /**
  9408. * Call this method to start monitoring a new frame.
  9409. * 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.
  9410. */
  9411. PerfCounter.prototype.fetchNewFrame = function () {
  9412. this._totalValueCount++;
  9413. this._current = 0;
  9414. this._lastSecValueCount++;
  9415. };
  9416. /**
  9417. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9418. * @param newCount the count value to add to the monitored count
  9419. * @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.
  9420. */
  9421. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9422. if (!PerfCounter.Enabled) {
  9423. return;
  9424. }
  9425. this._current += newCount;
  9426. if (fetchResult) {
  9427. this._fetchResult();
  9428. }
  9429. };
  9430. /**
  9431. * Start monitoring this performance counter
  9432. */
  9433. PerfCounter.prototype.beginMonitoring = function () {
  9434. if (!PerfCounter.Enabled) {
  9435. return;
  9436. }
  9437. this._startMonitoringTime = Tools.Now;
  9438. };
  9439. /**
  9440. * Compute the time lapsed since the previous beginMonitoring() call.
  9441. * @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
  9442. */
  9443. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9444. if (newFrame === void 0) { newFrame = true; }
  9445. if (!PerfCounter.Enabled) {
  9446. return;
  9447. }
  9448. if (newFrame) {
  9449. this.fetchNewFrame();
  9450. }
  9451. var currentTime = Tools.Now;
  9452. this._current = currentTime - this._startMonitoringTime;
  9453. if (newFrame) {
  9454. this._fetchResult();
  9455. }
  9456. };
  9457. PerfCounter.prototype._fetchResult = function () {
  9458. this._totalAccumulated += this._current;
  9459. this._lastSecAccumulated += this._current;
  9460. // Min/Max update
  9461. this._min = Math.min(this._min, this._current);
  9462. this._max = Math.max(this._max, this._current);
  9463. this._average = this._totalAccumulated / this._totalValueCount;
  9464. // Reset last sec?
  9465. var now = Tools.Now;
  9466. if ((now - this._lastSecTime) > 1000) {
  9467. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9468. this._lastSecTime = now;
  9469. this._lastSecAccumulated = 0;
  9470. this._lastSecValueCount = 0;
  9471. }
  9472. };
  9473. PerfCounter.Enabled = true;
  9474. return PerfCounter;
  9475. }());
  9476. BABYLON.PerfCounter = PerfCounter;
  9477. /**
  9478. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9479. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9480. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9481. * @param name The name of the class, case should be preserved
  9482. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9483. */
  9484. function className(name, module) {
  9485. return function (target) {
  9486. target["__bjsclassName__"] = name;
  9487. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9488. };
  9489. }
  9490. BABYLON.className = className;
  9491. /**
  9492. * An implementation of a loop for asynchronous functions.
  9493. */
  9494. var AsyncLoop = /** @class */ (function () {
  9495. /**
  9496. * Constroctor.
  9497. * @param iterations the number of iterations.
  9498. * @param _fn the function to run each iteration
  9499. * @param _successCallback the callback that will be called upon succesful execution
  9500. * @param offset starting offset.
  9501. */
  9502. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9503. if (offset === void 0) { offset = 0; }
  9504. this.iterations = iterations;
  9505. this._fn = _fn;
  9506. this._successCallback = _successCallback;
  9507. this.index = offset - 1;
  9508. this._done = false;
  9509. }
  9510. /**
  9511. * Execute the next iteration. Must be called after the last iteration was finished.
  9512. */
  9513. AsyncLoop.prototype.executeNext = function () {
  9514. if (!this._done) {
  9515. if (this.index + 1 < this.iterations) {
  9516. ++this.index;
  9517. this._fn(this);
  9518. }
  9519. else {
  9520. this.breakLoop();
  9521. }
  9522. }
  9523. };
  9524. /**
  9525. * Break the loop and run the success callback.
  9526. */
  9527. AsyncLoop.prototype.breakLoop = function () {
  9528. this._done = true;
  9529. this._successCallback();
  9530. };
  9531. /**
  9532. * Helper function
  9533. */
  9534. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9535. if (offset === void 0) { offset = 0; }
  9536. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9537. loop.executeNext();
  9538. return loop;
  9539. };
  9540. /**
  9541. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9542. * @param iterations total number of iterations
  9543. * @param syncedIterations number of synchronous iterations in each async iteration.
  9544. * @param fn the function to call each iteration.
  9545. * @param callback a success call back that will be called when iterating stops.
  9546. * @param breakFunction a break condition (optional)
  9547. * @param timeout timeout settings for the setTimeout function. default - 0.
  9548. * @constructor
  9549. */
  9550. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9551. if (timeout === void 0) { timeout = 0; }
  9552. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9553. if (breakFunction && breakFunction())
  9554. loop.breakLoop();
  9555. else {
  9556. setTimeout(function () {
  9557. for (var i = 0; i < syncedIterations; ++i) {
  9558. var iteration = (loop.index * syncedIterations) + i;
  9559. if (iteration >= iterations)
  9560. break;
  9561. fn(iteration);
  9562. if (breakFunction && breakFunction()) {
  9563. loop.breakLoop();
  9564. break;
  9565. }
  9566. }
  9567. loop.executeNext();
  9568. }, timeout);
  9569. }
  9570. }, callback);
  9571. };
  9572. return AsyncLoop;
  9573. }());
  9574. BABYLON.AsyncLoop = AsyncLoop;
  9575. })(BABYLON || (BABYLON = {}));
  9576. //# sourceMappingURL=babylon.tools.js.map
  9577. "use strict";
  9578. var BABYLON;
  9579. (function (BABYLON) {
  9580. var PromiseStates;
  9581. (function (PromiseStates) {
  9582. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9583. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9584. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9585. })(PromiseStates || (PromiseStates = {}));
  9586. var FulFillmentAgregator = /** @class */ (function () {
  9587. function FulFillmentAgregator() {
  9588. this.count = 0;
  9589. this.target = 0;
  9590. this.results = [];
  9591. }
  9592. return FulFillmentAgregator;
  9593. }());
  9594. var InternalPromise = /** @class */ (function () {
  9595. function InternalPromise(resolver) {
  9596. var _this = this;
  9597. this._state = PromiseStates.Pending;
  9598. this._children = new Array();
  9599. this._rejectWasConsumed = false;
  9600. if (!resolver) {
  9601. return;
  9602. }
  9603. try {
  9604. resolver(function (value) {
  9605. _this._resolve(value);
  9606. }, function (reason) {
  9607. _this._reject(reason);
  9608. });
  9609. }
  9610. catch (e) {
  9611. this._reject(e);
  9612. }
  9613. }
  9614. InternalPromise.prototype.catch = function (onRejected) {
  9615. return this.then(undefined, onRejected);
  9616. };
  9617. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9618. var _this = this;
  9619. var newPromise = new InternalPromise();
  9620. newPromise._onFulfilled = onFulfilled;
  9621. newPromise._onRejected = onRejected;
  9622. // Composition
  9623. this._children.push(newPromise);
  9624. if (this._state !== PromiseStates.Pending) {
  9625. BABYLON.Tools.SetImmediate(function () {
  9626. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9627. var returnedValue = newPromise._resolve(_this._result);
  9628. if (returnedValue !== undefined && returnedValue !== null) {
  9629. if (returnedValue._state !== undefined) {
  9630. var returnedPromise = returnedValue;
  9631. newPromise._children.push(returnedPromise);
  9632. newPromise = returnedPromise;
  9633. }
  9634. else {
  9635. newPromise._result = returnedValue;
  9636. }
  9637. }
  9638. }
  9639. else {
  9640. newPromise._reject(_this._reason);
  9641. }
  9642. });
  9643. }
  9644. return newPromise;
  9645. };
  9646. InternalPromise.prototype._moveChildren = function (children) {
  9647. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9648. if (this._state === PromiseStates.Fulfilled) {
  9649. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9650. var child = _b[_i];
  9651. child._resolve(this._result);
  9652. }
  9653. }
  9654. else if (this._state === PromiseStates.Rejected) {
  9655. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9656. var child = _d[_c];
  9657. child._reject(this._reason);
  9658. }
  9659. }
  9660. var _a;
  9661. };
  9662. InternalPromise.prototype._resolve = function (value) {
  9663. try {
  9664. this._state = PromiseStates.Fulfilled;
  9665. var returnedValue = null;
  9666. if (this._onFulfilled) {
  9667. returnedValue = this._onFulfilled(value);
  9668. }
  9669. if (returnedValue !== undefined && returnedValue !== null) {
  9670. if (returnedValue._state !== undefined) {
  9671. // Transmit children
  9672. var returnedPromise = returnedValue;
  9673. returnedPromise._moveChildren(this._children);
  9674. value = returnedPromise._result;
  9675. }
  9676. else {
  9677. value = returnedValue;
  9678. }
  9679. }
  9680. this._result = value;
  9681. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9682. var child = _a[_i];
  9683. child._resolve(value);
  9684. }
  9685. this._children.length = 0;
  9686. delete this._onFulfilled;
  9687. delete this._onRejected;
  9688. }
  9689. catch (e) {
  9690. this._reject(e, true);
  9691. }
  9692. };
  9693. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9694. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9695. this._state = PromiseStates.Rejected;
  9696. this._reason = reason;
  9697. if (this._onRejected && !onLocalThrow) {
  9698. try {
  9699. this._onRejected(reason);
  9700. this._rejectWasConsumed = true;
  9701. }
  9702. catch (e) {
  9703. reason = e;
  9704. }
  9705. }
  9706. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9707. var child = _a[_i];
  9708. if (this._rejectWasConsumed) {
  9709. child._resolve(null);
  9710. }
  9711. else {
  9712. child._reject(reason);
  9713. }
  9714. }
  9715. this._children.length = 0;
  9716. delete this._onFulfilled;
  9717. delete this._onRejected;
  9718. };
  9719. InternalPromise.resolve = function (value) {
  9720. var newPromise = new InternalPromise();
  9721. newPromise._resolve(value);
  9722. return newPromise;
  9723. };
  9724. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9725. promise.then(function (value) {
  9726. agregator.results[index] = value;
  9727. agregator.count++;
  9728. if (agregator.count === agregator.target) {
  9729. agregator.rootPromise._resolve(agregator.results);
  9730. }
  9731. return null;
  9732. }, function (reason) {
  9733. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9734. agregator.rootPromise._reject(reason);
  9735. }
  9736. });
  9737. };
  9738. InternalPromise.all = function (promises) {
  9739. var newPromise = new InternalPromise();
  9740. var agregator = new FulFillmentAgregator();
  9741. agregator.target = promises.length;
  9742. agregator.rootPromise = newPromise;
  9743. if (promises.length) {
  9744. for (var index = 0; index < promises.length; index++) {
  9745. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9746. }
  9747. }
  9748. else {
  9749. newPromise._resolve([]);
  9750. }
  9751. return newPromise;
  9752. };
  9753. InternalPromise.race = function (promises) {
  9754. var newPromise = new InternalPromise();
  9755. if (promises.length) {
  9756. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  9757. var promise = promises_1[_i];
  9758. promise.then(function (value) {
  9759. if (newPromise) {
  9760. newPromise._resolve(value);
  9761. newPromise = null;
  9762. }
  9763. return null;
  9764. }, function (reason) {
  9765. if (newPromise) {
  9766. newPromise._reject(reason);
  9767. newPromise = null;
  9768. }
  9769. });
  9770. }
  9771. }
  9772. return newPromise;
  9773. };
  9774. return InternalPromise;
  9775. }());
  9776. /**
  9777. * Helper class that provides a small promise polyfill
  9778. */
  9779. var PromisePolyfill = /** @class */ (function () {
  9780. function PromisePolyfill() {
  9781. }
  9782. /**
  9783. * Static function used to check if the polyfill is required
  9784. * If this is the case then the function will inject the polyfill to window.Promise
  9785. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9786. */
  9787. PromisePolyfill.Apply = function (force) {
  9788. if (force === void 0) { force = false; }
  9789. if (force || typeof Promise === 'undefined') {
  9790. var root = window;
  9791. root.Promise = InternalPromise;
  9792. }
  9793. };
  9794. return PromisePolyfill;
  9795. }());
  9796. BABYLON.PromisePolyfill = PromisePolyfill;
  9797. })(BABYLON || (BABYLON = {}));
  9798. //# sourceMappingURL=babylon.promise.js.map
  9799. "use strict";
  9800. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  9801. var BABYLON;
  9802. (function (BABYLON) {
  9803. /**
  9804. * Helper class to push actions to a pool of workers.
  9805. */
  9806. var WorkerPool = /** @class */ (function () {
  9807. /**
  9808. * Constructor
  9809. * @param workers Array of workers to use for actions
  9810. */
  9811. function WorkerPool(workers) {
  9812. this._pendingActions = new Array();
  9813. this._workerInfos = workers.map(function (worker) { return ({
  9814. worker: worker,
  9815. active: false
  9816. }); });
  9817. }
  9818. /**
  9819. * Terminates all workers and clears any pending actions.
  9820. */
  9821. WorkerPool.prototype.dispose = function () {
  9822. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9823. var workerInfo = _a[_i];
  9824. workerInfo.worker.terminate();
  9825. }
  9826. delete this._workerInfos;
  9827. delete this._pendingActions;
  9828. };
  9829. /**
  9830. * Pushes an action to the worker pool. If all the workers are active, the action will be
  9831. * pended until a worker has completed its action.
  9832. * @param action The action to perform. Call onComplete when the action is complete.
  9833. */
  9834. WorkerPool.prototype.push = function (action) {
  9835. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9836. var workerInfo = _a[_i];
  9837. if (!workerInfo.active) {
  9838. this._execute(workerInfo, action);
  9839. return;
  9840. }
  9841. }
  9842. this._pendingActions.push(action);
  9843. };
  9844. WorkerPool.prototype._execute = function (workerInfo, action) {
  9845. var _this = this;
  9846. workerInfo.active = true;
  9847. action(workerInfo.worker, function () {
  9848. workerInfo.active = false;
  9849. var nextAction = _this._pendingActions.shift();
  9850. if (nextAction) {
  9851. _this._execute(workerInfo, nextAction);
  9852. }
  9853. });
  9854. };
  9855. return WorkerPool;
  9856. }());
  9857. BABYLON.WorkerPool = WorkerPool;
  9858. })(BABYLON || (BABYLON = {}));
  9859. //# sourceMappingURL=babylon.workerPool.js.map
  9860. "use strict";
  9861. var BABYLON;
  9862. (function (BABYLON) {
  9863. var _AlphaState = /** @class */ (function () {
  9864. /**
  9865. * Initializes the state.
  9866. */
  9867. function _AlphaState() {
  9868. this._isAlphaBlendDirty = false;
  9869. this._isBlendFunctionParametersDirty = false;
  9870. this._isBlendEquationParametersDirty = false;
  9871. this._isBlendConstantsDirty = false;
  9872. this._alphaBlend = false;
  9873. this._blendFunctionParameters = new Array(4);
  9874. this._blendEquationParameters = new Array(2);
  9875. this._blendConstants = new Array(4);
  9876. this.reset();
  9877. }
  9878. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9879. get: function () {
  9880. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9881. },
  9882. enumerable: true,
  9883. configurable: true
  9884. });
  9885. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9886. get: function () {
  9887. return this._alphaBlend;
  9888. },
  9889. set: function (value) {
  9890. if (this._alphaBlend === value) {
  9891. return;
  9892. }
  9893. this._alphaBlend = value;
  9894. this._isAlphaBlendDirty = true;
  9895. },
  9896. enumerable: true,
  9897. configurable: true
  9898. });
  9899. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9900. if (this._blendConstants[0] === r &&
  9901. this._blendConstants[1] === g &&
  9902. this._blendConstants[2] === b &&
  9903. this._blendConstants[3] === a) {
  9904. return;
  9905. }
  9906. this._blendConstants[0] = r;
  9907. this._blendConstants[1] = g;
  9908. this._blendConstants[2] = b;
  9909. this._blendConstants[3] = a;
  9910. this._isBlendConstantsDirty = true;
  9911. };
  9912. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9913. if (this._blendFunctionParameters[0] === value0 &&
  9914. this._blendFunctionParameters[1] === value1 &&
  9915. this._blendFunctionParameters[2] === value2 &&
  9916. this._blendFunctionParameters[3] === value3) {
  9917. return;
  9918. }
  9919. this._blendFunctionParameters[0] = value0;
  9920. this._blendFunctionParameters[1] = value1;
  9921. this._blendFunctionParameters[2] = value2;
  9922. this._blendFunctionParameters[3] = value3;
  9923. this._isBlendFunctionParametersDirty = true;
  9924. };
  9925. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9926. if (this._blendEquationParameters[0] === rgb &&
  9927. this._blendEquationParameters[1] === alpha) {
  9928. return;
  9929. }
  9930. this._blendEquationParameters[0] = rgb;
  9931. this._blendEquationParameters[1] = alpha;
  9932. this._isBlendEquationParametersDirty = true;
  9933. };
  9934. _AlphaState.prototype.reset = function () {
  9935. this._alphaBlend = false;
  9936. this._blendFunctionParameters[0] = null;
  9937. this._blendFunctionParameters[1] = null;
  9938. this._blendFunctionParameters[2] = null;
  9939. this._blendFunctionParameters[3] = null;
  9940. this._blendEquationParameters[0] = null;
  9941. this._blendEquationParameters[1] = null;
  9942. this._blendConstants[0] = null;
  9943. this._blendConstants[1] = null;
  9944. this._blendConstants[2] = null;
  9945. this._blendConstants[3] = null;
  9946. this._isAlphaBlendDirty = true;
  9947. this._isBlendFunctionParametersDirty = false;
  9948. this._isBlendEquationParametersDirty = false;
  9949. this._isBlendConstantsDirty = false;
  9950. };
  9951. _AlphaState.prototype.apply = function (gl) {
  9952. if (!this.isDirty) {
  9953. return;
  9954. }
  9955. // Alpha blend
  9956. if (this._isAlphaBlendDirty) {
  9957. if (this._alphaBlend) {
  9958. gl.enable(gl.BLEND);
  9959. }
  9960. else {
  9961. gl.disable(gl.BLEND);
  9962. }
  9963. this._isAlphaBlendDirty = false;
  9964. }
  9965. // Alpha function
  9966. if (this._isBlendFunctionParametersDirty) {
  9967. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9968. this._isBlendFunctionParametersDirty = false;
  9969. }
  9970. // Alpha equation
  9971. if (this._isBlendEquationParametersDirty) {
  9972. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9973. this._isBlendEquationParametersDirty = false;
  9974. }
  9975. // Constants
  9976. if (this._isBlendConstantsDirty) {
  9977. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9978. this._isBlendConstantsDirty = false;
  9979. }
  9980. };
  9981. return _AlphaState;
  9982. }());
  9983. BABYLON._AlphaState = _AlphaState;
  9984. })(BABYLON || (BABYLON = {}));
  9985. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9986. "use strict";
  9987. var BABYLON;
  9988. (function (BABYLON) {
  9989. var _DepthCullingState = /** @class */ (function () {
  9990. /**
  9991. * Initializes the state.
  9992. */
  9993. function _DepthCullingState() {
  9994. this._isDepthTestDirty = false;
  9995. this._isDepthMaskDirty = false;
  9996. this._isDepthFuncDirty = false;
  9997. this._isCullFaceDirty = false;
  9998. this._isCullDirty = false;
  9999. this._isZOffsetDirty = false;
  10000. this._isFrontFaceDirty = false;
  10001. this.reset();
  10002. }
  10003. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10004. get: function () {
  10005. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10006. },
  10007. enumerable: true,
  10008. configurable: true
  10009. });
  10010. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10011. get: function () {
  10012. return this._zOffset;
  10013. },
  10014. set: function (value) {
  10015. if (this._zOffset === value) {
  10016. return;
  10017. }
  10018. this._zOffset = value;
  10019. this._isZOffsetDirty = true;
  10020. },
  10021. enumerable: true,
  10022. configurable: true
  10023. });
  10024. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10025. get: function () {
  10026. return this._cullFace;
  10027. },
  10028. set: function (value) {
  10029. if (this._cullFace === value) {
  10030. return;
  10031. }
  10032. this._cullFace = value;
  10033. this._isCullFaceDirty = true;
  10034. },
  10035. enumerable: true,
  10036. configurable: true
  10037. });
  10038. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10039. get: function () {
  10040. return this._cull;
  10041. },
  10042. set: function (value) {
  10043. if (this._cull === value) {
  10044. return;
  10045. }
  10046. this._cull = value;
  10047. this._isCullDirty = true;
  10048. },
  10049. enumerable: true,
  10050. configurable: true
  10051. });
  10052. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10053. get: function () {
  10054. return this._depthFunc;
  10055. },
  10056. set: function (value) {
  10057. if (this._depthFunc === value) {
  10058. return;
  10059. }
  10060. this._depthFunc = value;
  10061. this._isDepthFuncDirty = true;
  10062. },
  10063. enumerable: true,
  10064. configurable: true
  10065. });
  10066. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10067. get: function () {
  10068. return this._depthMask;
  10069. },
  10070. set: function (value) {
  10071. if (this._depthMask === value) {
  10072. return;
  10073. }
  10074. this._depthMask = value;
  10075. this._isDepthMaskDirty = true;
  10076. },
  10077. enumerable: true,
  10078. configurable: true
  10079. });
  10080. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10081. get: function () {
  10082. return this._depthTest;
  10083. },
  10084. set: function (value) {
  10085. if (this._depthTest === value) {
  10086. return;
  10087. }
  10088. this._depthTest = value;
  10089. this._isDepthTestDirty = true;
  10090. },
  10091. enumerable: true,
  10092. configurable: true
  10093. });
  10094. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10095. get: function () {
  10096. return this._frontFace;
  10097. },
  10098. set: function (value) {
  10099. if (this._frontFace === value) {
  10100. return;
  10101. }
  10102. this._frontFace = value;
  10103. this._isFrontFaceDirty = true;
  10104. },
  10105. enumerable: true,
  10106. configurable: true
  10107. });
  10108. _DepthCullingState.prototype.reset = function () {
  10109. this._depthMask = true;
  10110. this._depthTest = true;
  10111. this._depthFunc = null;
  10112. this._cullFace = null;
  10113. this._cull = null;
  10114. this._zOffset = 0;
  10115. this._frontFace = null;
  10116. this._isDepthTestDirty = true;
  10117. this._isDepthMaskDirty = true;
  10118. this._isDepthFuncDirty = false;
  10119. this._isCullFaceDirty = false;
  10120. this._isCullDirty = false;
  10121. this._isZOffsetDirty = false;
  10122. this._isFrontFaceDirty = false;
  10123. };
  10124. _DepthCullingState.prototype.apply = function (gl) {
  10125. if (!this.isDirty) {
  10126. return;
  10127. }
  10128. // Cull
  10129. if (this._isCullDirty) {
  10130. if (this.cull) {
  10131. gl.enable(gl.CULL_FACE);
  10132. }
  10133. else {
  10134. gl.disable(gl.CULL_FACE);
  10135. }
  10136. this._isCullDirty = false;
  10137. }
  10138. // Cull face
  10139. if (this._isCullFaceDirty) {
  10140. gl.cullFace(this.cullFace);
  10141. this._isCullFaceDirty = false;
  10142. }
  10143. // Depth mask
  10144. if (this._isDepthMaskDirty) {
  10145. gl.depthMask(this.depthMask);
  10146. this._isDepthMaskDirty = false;
  10147. }
  10148. // Depth test
  10149. if (this._isDepthTestDirty) {
  10150. if (this.depthTest) {
  10151. gl.enable(gl.DEPTH_TEST);
  10152. }
  10153. else {
  10154. gl.disable(gl.DEPTH_TEST);
  10155. }
  10156. this._isDepthTestDirty = false;
  10157. }
  10158. // Depth func
  10159. if (this._isDepthFuncDirty) {
  10160. gl.depthFunc(this.depthFunc);
  10161. this._isDepthFuncDirty = false;
  10162. }
  10163. // zOffset
  10164. if (this._isZOffsetDirty) {
  10165. if (this.zOffset) {
  10166. gl.enable(gl.POLYGON_OFFSET_FILL);
  10167. gl.polygonOffset(this.zOffset, 0);
  10168. }
  10169. else {
  10170. gl.disable(gl.POLYGON_OFFSET_FILL);
  10171. }
  10172. this._isZOffsetDirty = false;
  10173. }
  10174. // Front face
  10175. if (this._isFrontFaceDirty) {
  10176. gl.frontFace(this.frontFace);
  10177. this._isFrontFaceDirty = false;
  10178. }
  10179. };
  10180. return _DepthCullingState;
  10181. }());
  10182. BABYLON._DepthCullingState = _DepthCullingState;
  10183. })(BABYLON || (BABYLON = {}));
  10184. //# sourceMappingURL=babylon.depthCullingState.js.map
  10185. "use strict";
  10186. var BABYLON;
  10187. (function (BABYLON) {
  10188. var _StencilState = /** @class */ (function () {
  10189. function _StencilState() {
  10190. this._isStencilTestDirty = false;
  10191. this._isStencilMaskDirty = false;
  10192. this._isStencilFuncDirty = false;
  10193. this._isStencilOpDirty = false;
  10194. this.reset();
  10195. }
  10196. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10197. get: function () {
  10198. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10199. },
  10200. enumerable: true,
  10201. configurable: true
  10202. });
  10203. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10204. get: function () {
  10205. return this._stencilFunc;
  10206. },
  10207. set: function (value) {
  10208. if (this._stencilFunc === value) {
  10209. return;
  10210. }
  10211. this._stencilFunc = value;
  10212. this._isStencilFuncDirty = true;
  10213. },
  10214. enumerable: true,
  10215. configurable: true
  10216. });
  10217. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10218. get: function () {
  10219. return this._stencilFuncRef;
  10220. },
  10221. set: function (value) {
  10222. if (this._stencilFuncRef === value) {
  10223. return;
  10224. }
  10225. this._stencilFuncRef = value;
  10226. this._isStencilFuncDirty = true;
  10227. },
  10228. enumerable: true,
  10229. configurable: true
  10230. });
  10231. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10232. get: function () {
  10233. return this._stencilFuncMask;
  10234. },
  10235. set: function (value) {
  10236. if (this._stencilFuncMask === value) {
  10237. return;
  10238. }
  10239. this._stencilFuncMask = value;
  10240. this._isStencilFuncDirty = true;
  10241. },
  10242. enumerable: true,
  10243. configurable: true
  10244. });
  10245. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10246. get: function () {
  10247. return this._stencilOpStencilFail;
  10248. },
  10249. set: function (value) {
  10250. if (this._stencilOpStencilFail === value) {
  10251. return;
  10252. }
  10253. this._stencilOpStencilFail = value;
  10254. this._isStencilOpDirty = true;
  10255. },
  10256. enumerable: true,
  10257. configurable: true
  10258. });
  10259. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10260. get: function () {
  10261. return this._stencilOpDepthFail;
  10262. },
  10263. set: function (value) {
  10264. if (this._stencilOpDepthFail === value) {
  10265. return;
  10266. }
  10267. this._stencilOpDepthFail = value;
  10268. this._isStencilOpDirty = true;
  10269. },
  10270. enumerable: true,
  10271. configurable: true
  10272. });
  10273. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10274. get: function () {
  10275. return this._stencilOpStencilDepthPass;
  10276. },
  10277. set: function (value) {
  10278. if (this._stencilOpStencilDepthPass === value) {
  10279. return;
  10280. }
  10281. this._stencilOpStencilDepthPass = value;
  10282. this._isStencilOpDirty = true;
  10283. },
  10284. enumerable: true,
  10285. configurable: true
  10286. });
  10287. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10288. get: function () {
  10289. return this._stencilMask;
  10290. },
  10291. set: function (value) {
  10292. if (this._stencilMask === value) {
  10293. return;
  10294. }
  10295. this._stencilMask = value;
  10296. this._isStencilMaskDirty = true;
  10297. },
  10298. enumerable: true,
  10299. configurable: true
  10300. });
  10301. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10302. get: function () {
  10303. return this._stencilTest;
  10304. },
  10305. set: function (value) {
  10306. if (this._stencilTest === value) {
  10307. return;
  10308. }
  10309. this._stencilTest = value;
  10310. this._isStencilTestDirty = true;
  10311. },
  10312. enumerable: true,
  10313. configurable: true
  10314. });
  10315. _StencilState.prototype.reset = function () {
  10316. this._stencilTest = false;
  10317. this._stencilMask = 0xFF;
  10318. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10319. this._stencilFuncRef = 1;
  10320. this._stencilFuncMask = 0xFF;
  10321. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10322. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10323. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10324. this._isStencilTestDirty = true;
  10325. this._isStencilMaskDirty = true;
  10326. this._isStencilFuncDirty = true;
  10327. this._isStencilOpDirty = true;
  10328. };
  10329. _StencilState.prototype.apply = function (gl) {
  10330. if (!this.isDirty) {
  10331. return;
  10332. }
  10333. // Stencil test
  10334. if (this._isStencilTestDirty) {
  10335. if (this.stencilTest) {
  10336. gl.enable(gl.STENCIL_TEST);
  10337. }
  10338. else {
  10339. gl.disable(gl.STENCIL_TEST);
  10340. }
  10341. this._isStencilTestDirty = false;
  10342. }
  10343. // Stencil mask
  10344. if (this._isStencilMaskDirty) {
  10345. gl.stencilMask(this.stencilMask);
  10346. this._isStencilMaskDirty = false;
  10347. }
  10348. // Stencil func
  10349. if (this._isStencilFuncDirty) {
  10350. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10351. this._isStencilFuncDirty = false;
  10352. }
  10353. // Stencil op
  10354. if (this._isStencilOpDirty) {
  10355. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10356. this._isStencilOpDirty = false;
  10357. }
  10358. };
  10359. return _StencilState;
  10360. }());
  10361. BABYLON._StencilState = _StencilState;
  10362. })(BABYLON || (BABYLON = {}));
  10363. //# sourceMappingURL=babylon.stencilState.js.map
  10364. "use strict";
  10365. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10366. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10367. s = arguments[i];
  10368. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10369. t[p] = s[p];
  10370. }
  10371. return t;
  10372. };
  10373. var BABYLON;
  10374. (function (BABYLON) {
  10375. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10376. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10377. };
  10378. var compileRawShader = function (gl, source, type) {
  10379. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10380. gl.shaderSource(shader, source);
  10381. gl.compileShader(shader);
  10382. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10383. var log = gl.getShaderInfoLog(shader);
  10384. if (log) {
  10385. throw new Error(log);
  10386. }
  10387. }
  10388. if (!shader) {
  10389. throw new Error("Something went wrong while compile the shader.");
  10390. }
  10391. return shader;
  10392. };
  10393. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10394. var magFilter = gl.NEAREST;
  10395. var minFilter = gl.NEAREST;
  10396. switch (samplingMode) {
  10397. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10398. magFilter = gl.LINEAR;
  10399. if (generateMipMaps) {
  10400. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10401. }
  10402. else {
  10403. minFilter = gl.LINEAR;
  10404. }
  10405. break;
  10406. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10407. magFilter = gl.LINEAR;
  10408. if (generateMipMaps) {
  10409. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10410. }
  10411. else {
  10412. minFilter = gl.LINEAR;
  10413. }
  10414. break;
  10415. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10416. magFilter = gl.NEAREST;
  10417. if (generateMipMaps) {
  10418. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10419. }
  10420. else {
  10421. minFilter = gl.NEAREST;
  10422. }
  10423. break;
  10424. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10425. magFilter = gl.NEAREST;
  10426. if (generateMipMaps) {
  10427. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10428. }
  10429. else {
  10430. minFilter = gl.NEAREST;
  10431. }
  10432. break;
  10433. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10434. magFilter = gl.NEAREST;
  10435. if (generateMipMaps) {
  10436. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10437. }
  10438. else {
  10439. minFilter = gl.LINEAR;
  10440. }
  10441. break;
  10442. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10443. magFilter = gl.NEAREST;
  10444. if (generateMipMaps) {
  10445. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10446. }
  10447. else {
  10448. minFilter = gl.LINEAR;
  10449. }
  10450. break;
  10451. case BABYLON.Texture.NEAREST_LINEAR:
  10452. magFilter = gl.NEAREST;
  10453. minFilter = gl.LINEAR;
  10454. break;
  10455. case BABYLON.Texture.NEAREST_NEAREST:
  10456. magFilter = gl.NEAREST;
  10457. minFilter = gl.NEAREST;
  10458. break;
  10459. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10460. magFilter = gl.LINEAR;
  10461. if (generateMipMaps) {
  10462. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10463. }
  10464. else {
  10465. minFilter = gl.NEAREST;
  10466. }
  10467. break;
  10468. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10469. magFilter = gl.LINEAR;
  10470. if (generateMipMaps) {
  10471. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10472. }
  10473. else {
  10474. minFilter = gl.NEAREST;
  10475. }
  10476. break;
  10477. case BABYLON.Texture.LINEAR_LINEAR:
  10478. magFilter = gl.LINEAR;
  10479. minFilter = gl.LINEAR;
  10480. break;
  10481. case BABYLON.Texture.LINEAR_NEAREST:
  10482. magFilter = gl.LINEAR;
  10483. minFilter = gl.NEAREST;
  10484. break;
  10485. }
  10486. return {
  10487. min: minFilter,
  10488. mag: magFilter
  10489. };
  10490. };
  10491. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10492. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10493. var img;
  10494. var onload = function () {
  10495. loadedImages[index] = img;
  10496. loadedImages._internalCount++;
  10497. if (scene) {
  10498. scene._removePendingData(img);
  10499. }
  10500. if (loadedImages._internalCount === 6) {
  10501. onfinish(loadedImages);
  10502. }
  10503. };
  10504. var onerror = function (message, exception) {
  10505. if (scene) {
  10506. scene._removePendingData(img);
  10507. }
  10508. if (onErrorCallBack) {
  10509. onErrorCallBack(message, exception);
  10510. }
  10511. };
  10512. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10513. if (scene) {
  10514. scene._addPendingData(img);
  10515. }
  10516. };
  10517. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10518. if (onError === void 0) { onError = null; }
  10519. var loadedImages = [];
  10520. loadedImages._internalCount = 0;
  10521. for (var index = 0; index < 6; index++) {
  10522. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10523. }
  10524. };
  10525. var BufferPointer = /** @class */ (function () {
  10526. function BufferPointer() {
  10527. }
  10528. return BufferPointer;
  10529. }());
  10530. var InstancingAttributeInfo = /** @class */ (function () {
  10531. function InstancingAttributeInfo() {
  10532. }
  10533. return InstancingAttributeInfo;
  10534. }());
  10535. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10536. /**
  10537. * Define options used to create a render target texture
  10538. */
  10539. var RenderTargetCreationOptions = /** @class */ (function () {
  10540. function RenderTargetCreationOptions() {
  10541. }
  10542. return RenderTargetCreationOptions;
  10543. }());
  10544. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10545. /**
  10546. * Define options used to create a depth texture
  10547. */
  10548. var DepthTextureCreationOptions = /** @class */ (function () {
  10549. function DepthTextureCreationOptions() {
  10550. }
  10551. return DepthTextureCreationOptions;
  10552. }());
  10553. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10554. /**
  10555. * Regroup several parameters relative to the browser in use
  10556. */
  10557. var EngineCapabilities = /** @class */ (function () {
  10558. function EngineCapabilities() {
  10559. }
  10560. return EngineCapabilities;
  10561. }());
  10562. BABYLON.EngineCapabilities = EngineCapabilities;
  10563. /**
  10564. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10565. */
  10566. var Engine = /** @class */ (function () {
  10567. /**
  10568. * @constructor
  10569. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10570. * @param antialias defines enable antialiasing (default: false)
  10571. * @param options defines further options to be sent to the getContext() function
  10572. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10573. */
  10574. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10575. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10576. var _this = this;
  10577. // Public members
  10578. this.forcePOTTextures = false;
  10579. this.isFullscreen = false;
  10580. this.isPointerLock = false;
  10581. this.cullBackFaces = true;
  10582. this.renderEvenInBackground = true;
  10583. this.preventCacheWipeBetweenFrames = false;
  10584. /**
  10585. * To enable/disable IDB support and avoid XHR on .manifest
  10586. **/
  10587. this.enableOfflineSupport = false;
  10588. this.scenes = new Array();
  10589. this.postProcesses = new Array();
  10590. // Observables
  10591. /**
  10592. * Observable event triggered each time the rendering canvas is resized
  10593. */
  10594. this.onResizeObservable = new BABYLON.Observable();
  10595. /**
  10596. * Observable event triggered each time the canvas loses focus
  10597. */
  10598. this.onCanvasBlurObservable = new BABYLON.Observable();
  10599. /**
  10600. * Observable event triggered each time the canvas gains focus
  10601. */
  10602. this.onCanvasFocusObservable = new BABYLON.Observable();
  10603. /**
  10604. * Observable event triggered each time the canvas receives pointerout event
  10605. */
  10606. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10607. /**
  10608. * Observable event triggered before each texture is initialized
  10609. */
  10610. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10611. //WebVR
  10612. this._vrDisplay = undefined;
  10613. this._vrSupported = false;
  10614. this._vrExclusivePointerMode = false;
  10615. // Uniform buffers list
  10616. this.disableUniformBuffers = false;
  10617. this._uniformBuffers = new Array();
  10618. // Observables
  10619. /**
  10620. * Observable raised when the engine begins a new frame
  10621. */
  10622. this.onBeginFrameObservable = new BABYLON.Observable();
  10623. /**
  10624. * Observable raised when the engine ends the current frame
  10625. */
  10626. this.onEndFrameObservable = new BABYLON.Observable();
  10627. /**
  10628. * Observable raised when the engine is about to compile a shader
  10629. */
  10630. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10631. /**
  10632. * Observable raised when the engine has jsut compiled a shader
  10633. */
  10634. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10635. this._windowIsBackground = false;
  10636. this._webGLVersion = 1.0;
  10637. this._badOS = false;
  10638. this._badDesktopOS = false;
  10639. /**
  10640. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10641. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10642. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10643. */
  10644. this.disableTextureBindingOptimization = false;
  10645. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10646. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10647. this.onVRRequestPresentStart = new BABYLON.Observable();
  10648. this._colorWrite = true;
  10649. this._drawCalls = new BABYLON.PerfCounter();
  10650. this._textureCollisions = new BABYLON.PerfCounter();
  10651. this._renderingQueueLaunched = false;
  10652. this._activeRenderLoops = new Array();
  10653. // Deterministic lockstepMaxSteps
  10654. this._deterministicLockstep = false;
  10655. this._lockstepMaxSteps = 4;
  10656. // Lost context
  10657. this.onContextLostObservable = new BABYLON.Observable();
  10658. this.onContextRestoredObservable = new BABYLON.Observable();
  10659. this._contextWasLost = false;
  10660. this._doNotHandleContextLost = false;
  10661. // FPS
  10662. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10663. this._fps = 60;
  10664. this._deltaTime = 0;
  10665. /**
  10666. * Turn this value on if you want to pause FPS computation when in background
  10667. */
  10668. this.disablePerformanceMonitorInBackground = false;
  10669. // States
  10670. this._depthCullingState = new BABYLON._DepthCullingState();
  10671. this._stencilState = new BABYLON._StencilState();
  10672. this._alphaState = new BABYLON._AlphaState();
  10673. this._alphaMode = Engine.ALPHA_DISABLE;
  10674. // Cache
  10675. this._internalTexturesCache = new Array();
  10676. this._activeChannel = 0;
  10677. this._currentTextureChannel = -1;
  10678. this._boundTexturesCache = {};
  10679. this._compiledEffects = {};
  10680. this._vertexAttribArraysEnabled = [];
  10681. this._uintIndicesCurrentlySet = false;
  10682. this._currentBoundBuffer = new Array();
  10683. this._currentBufferPointers = new Array();
  10684. this._currentInstanceLocations = new Array();
  10685. this._currentInstanceBuffers = new Array();
  10686. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10687. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10688. this._vaoRecordInProgress = false;
  10689. this._mustWipeVertexAttributes = false;
  10690. this._nextFreeTextureSlots = new Array();
  10691. this._maxSimultaneousTextures = 0;
  10692. this._activeRequests = new Array();
  10693. // Hardware supported Compressed Textures
  10694. this._texturesSupported = new Array();
  10695. this._onVRFullScreenTriggered = function () {
  10696. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10697. //get the old size before we change
  10698. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10699. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10700. //get the width and height, change the render size
  10701. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10702. _this.setHardwareScalingLevel(1);
  10703. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10704. }
  10705. else {
  10706. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10707. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10708. }
  10709. };
  10710. this._boundUniforms = {};
  10711. // Register promises
  10712. BABYLON.PromisePolyfill.Apply();
  10713. var canvas = null;
  10714. Engine.Instances.push(this);
  10715. if (!canvasOrContext) {
  10716. return;
  10717. }
  10718. options = options || {};
  10719. if (canvasOrContext.getContext) {
  10720. canvas = canvasOrContext;
  10721. this._renderingCanvas = canvas;
  10722. if (antialias != null) {
  10723. options.antialias = antialias;
  10724. }
  10725. if (options.deterministicLockstep === undefined) {
  10726. options.deterministicLockstep = false;
  10727. }
  10728. if (options.lockstepMaxSteps === undefined) {
  10729. options.lockstepMaxSteps = 4;
  10730. }
  10731. if (options.preserveDrawingBuffer === undefined) {
  10732. options.preserveDrawingBuffer = false;
  10733. }
  10734. if (options.audioEngine === undefined) {
  10735. options.audioEngine = true;
  10736. }
  10737. if (options.stencil === undefined) {
  10738. options.stencil = true;
  10739. }
  10740. this._deterministicLockstep = options.deterministicLockstep;
  10741. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10742. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10743. // Exceptions
  10744. if (navigator && navigator.userAgent) {
  10745. var ua = navigator.userAgent;
  10746. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10747. var exception = _a[_i];
  10748. var key = exception.key;
  10749. var targets = exception.targets;
  10750. if (ua.indexOf(key) > -1) {
  10751. if (exception.capture && exception.captureConstraint) {
  10752. var capture = exception.capture;
  10753. var constraint = exception.captureConstraint;
  10754. var regex = new RegExp(capture);
  10755. var matches = regex.exec(ua);
  10756. if (matches && matches.length > 0) {
  10757. var capturedValue = parseInt(matches[matches.length - 1]);
  10758. if (capturedValue >= constraint) {
  10759. continue;
  10760. }
  10761. }
  10762. }
  10763. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10764. var target = targets_1[_b];
  10765. switch (target) {
  10766. case "uniformBuffer":
  10767. this.disableUniformBuffers = true;
  10768. break;
  10769. case "textureBindingOptimization":
  10770. this.disableTextureBindingOptimization = true;
  10771. break;
  10772. }
  10773. }
  10774. }
  10775. }
  10776. }
  10777. // GL
  10778. if (!options.disableWebGL2Support) {
  10779. try {
  10780. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10781. if (this._gl) {
  10782. this._webGLVersion = 2.0;
  10783. }
  10784. }
  10785. catch (e) {
  10786. // Do nothing
  10787. }
  10788. }
  10789. if (!this._gl) {
  10790. if (!canvas) {
  10791. throw new Error("The provided canvas is null or undefined.");
  10792. }
  10793. try {
  10794. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10795. }
  10796. catch (e) {
  10797. throw new Error("WebGL not supported");
  10798. }
  10799. }
  10800. if (!this._gl) {
  10801. throw new Error("WebGL not supported");
  10802. }
  10803. this._onCanvasFocus = function () {
  10804. _this.onCanvasFocusObservable.notifyObservers(_this);
  10805. };
  10806. this._onCanvasBlur = function () {
  10807. _this.onCanvasBlurObservable.notifyObservers(_this);
  10808. };
  10809. canvas.addEventListener("focus", this._onCanvasFocus);
  10810. canvas.addEventListener("blur", this._onCanvasBlur);
  10811. this._onBlur = function () {
  10812. if (_this.disablePerformanceMonitorInBackground) {
  10813. _this._performanceMonitor.disable();
  10814. }
  10815. _this._windowIsBackground = true;
  10816. };
  10817. this._onFocus = function () {
  10818. if (_this.disablePerformanceMonitorInBackground) {
  10819. _this._performanceMonitor.enable();
  10820. }
  10821. _this._windowIsBackground = false;
  10822. };
  10823. this._onCanvasPointerOut = function (ev) {
  10824. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  10825. };
  10826. window.addEventListener("blur", this._onBlur);
  10827. window.addEventListener("focus", this._onFocus);
  10828. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10829. // Context lost
  10830. if (!this._doNotHandleContextLost) {
  10831. this._onContextLost = function (evt) {
  10832. evt.preventDefault();
  10833. _this._contextWasLost = true;
  10834. BABYLON.Tools.Warn("WebGL context lost.");
  10835. _this.onContextLostObservable.notifyObservers(_this);
  10836. };
  10837. this._onContextRestored = function (evt) {
  10838. // Adding a timeout to avoid race condition at browser level
  10839. setTimeout(function () {
  10840. // Rebuild gl context
  10841. _this._initGLContext();
  10842. // Rebuild effects
  10843. _this._rebuildEffects();
  10844. // Rebuild textures
  10845. _this._rebuildInternalTextures();
  10846. // Rebuild buffers
  10847. _this._rebuildBuffers();
  10848. // Cache
  10849. _this.wipeCaches(true);
  10850. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10851. _this.onContextRestoredObservable.notifyObservers(_this);
  10852. _this._contextWasLost = false;
  10853. }, 0);
  10854. };
  10855. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10856. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10857. }
  10858. }
  10859. else {
  10860. this._gl = canvasOrContext;
  10861. this._renderingCanvas = this._gl.canvas;
  10862. if (this._gl.renderbufferStorageMultisample) {
  10863. this._webGLVersion = 2.0;
  10864. }
  10865. options.stencil = this._gl.getContextAttributes().stencil;
  10866. }
  10867. // Viewport
  10868. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10869. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10870. this.resize();
  10871. this._isStencilEnable = options.stencil ? true : false;
  10872. this._initGLContext();
  10873. if (canvas) {
  10874. // Fullscreen
  10875. this._onFullscreenChange = function () {
  10876. if (document.fullscreen !== undefined) {
  10877. _this.isFullscreen = document.fullscreen;
  10878. }
  10879. else if (document.mozFullScreen !== undefined) {
  10880. _this.isFullscreen = document.mozFullScreen;
  10881. }
  10882. else if (document.webkitIsFullScreen !== undefined) {
  10883. _this.isFullscreen = document.webkitIsFullScreen;
  10884. }
  10885. else if (document.msIsFullScreen !== undefined) {
  10886. _this.isFullscreen = document.msIsFullScreen;
  10887. }
  10888. // Pointer lock
  10889. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10890. canvas.requestPointerLock = canvas.requestPointerLock ||
  10891. canvas.msRequestPointerLock ||
  10892. canvas.mozRequestPointerLock ||
  10893. canvas.webkitRequestPointerLock;
  10894. if (canvas.requestPointerLock) {
  10895. canvas.requestPointerLock();
  10896. }
  10897. }
  10898. };
  10899. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10900. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10901. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10902. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10903. // Pointer lock
  10904. this._onPointerLockChange = function () {
  10905. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10906. document.webkitPointerLockElement === canvas ||
  10907. document.msPointerLockElement === canvas ||
  10908. document.pointerLockElement === canvas);
  10909. };
  10910. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10911. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10912. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10913. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10914. this._onVRDisplayPointerRestricted = function () {
  10915. if (canvas) {
  10916. canvas.requestPointerLock();
  10917. }
  10918. };
  10919. this._onVRDisplayPointerUnrestricted = function () {
  10920. document.exitPointerLock();
  10921. };
  10922. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10923. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10924. }
  10925. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10926. Engine.audioEngine = new BABYLON.AudioEngine();
  10927. }
  10928. // Prepare buffer pointers
  10929. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10930. this._currentBufferPointers[i] = new BufferPointer();
  10931. }
  10932. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10933. // Load WebVR Devices
  10934. if (options.autoEnableWebVR) {
  10935. this.initWebVR();
  10936. }
  10937. // Detect if we are running on a faulty buggy OS.
  10938. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10939. // Detect if we are running on a faulty buggy desktop OS.
  10940. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10941. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  10942. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10943. }
  10944. Object.defineProperty(Engine, "LastCreatedEngine", {
  10945. get: function () {
  10946. if (Engine.Instances.length === 0) {
  10947. return null;
  10948. }
  10949. return Engine.Instances[Engine.Instances.length - 1];
  10950. },
  10951. enumerable: true,
  10952. configurable: true
  10953. });
  10954. Object.defineProperty(Engine, "LastCreatedScene", {
  10955. get: function () {
  10956. var lastCreatedEngine = Engine.LastCreatedEngine;
  10957. if (!lastCreatedEngine) {
  10958. return null;
  10959. }
  10960. if (lastCreatedEngine.scenes.length === 0) {
  10961. return null;
  10962. }
  10963. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10964. },
  10965. enumerable: true,
  10966. configurable: true
  10967. });
  10968. /**
  10969. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10970. */
  10971. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10972. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10973. var engine = Engine.Instances[engineIndex];
  10974. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10975. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10976. }
  10977. }
  10978. };
  10979. Object.defineProperty(Engine, "NEVER", {
  10980. get: function () {
  10981. return Engine._NEVER;
  10982. },
  10983. enumerable: true,
  10984. configurable: true
  10985. });
  10986. Object.defineProperty(Engine, "ALWAYS", {
  10987. get: function () {
  10988. return Engine._ALWAYS;
  10989. },
  10990. enumerable: true,
  10991. configurable: true
  10992. });
  10993. Object.defineProperty(Engine, "LESS", {
  10994. get: function () {
  10995. return Engine._LESS;
  10996. },
  10997. enumerable: true,
  10998. configurable: true
  10999. });
  11000. Object.defineProperty(Engine, "EQUAL", {
  11001. get: function () {
  11002. return Engine._EQUAL;
  11003. },
  11004. enumerable: true,
  11005. configurable: true
  11006. });
  11007. Object.defineProperty(Engine, "LEQUAL", {
  11008. get: function () {
  11009. return Engine._LEQUAL;
  11010. },
  11011. enumerable: true,
  11012. configurable: true
  11013. });
  11014. Object.defineProperty(Engine, "GREATER", {
  11015. get: function () {
  11016. return Engine._GREATER;
  11017. },
  11018. enumerable: true,
  11019. configurable: true
  11020. });
  11021. Object.defineProperty(Engine, "GEQUAL", {
  11022. get: function () {
  11023. return Engine._GEQUAL;
  11024. },
  11025. enumerable: true,
  11026. configurable: true
  11027. });
  11028. Object.defineProperty(Engine, "NOTEQUAL", {
  11029. get: function () {
  11030. return Engine._NOTEQUAL;
  11031. },
  11032. enumerable: true,
  11033. configurable: true
  11034. });
  11035. Object.defineProperty(Engine, "KEEP", {
  11036. get: function () {
  11037. return Engine._KEEP;
  11038. },
  11039. enumerable: true,
  11040. configurable: true
  11041. });
  11042. Object.defineProperty(Engine, "REPLACE", {
  11043. get: function () {
  11044. return Engine._REPLACE;
  11045. },
  11046. enumerable: true,
  11047. configurable: true
  11048. });
  11049. Object.defineProperty(Engine, "INCR", {
  11050. get: function () {
  11051. return Engine._INCR;
  11052. },
  11053. enumerable: true,
  11054. configurable: true
  11055. });
  11056. Object.defineProperty(Engine, "DECR", {
  11057. get: function () {
  11058. return Engine._DECR;
  11059. },
  11060. enumerable: true,
  11061. configurable: true
  11062. });
  11063. Object.defineProperty(Engine, "INVERT", {
  11064. get: function () {
  11065. return Engine._INVERT;
  11066. },
  11067. enumerable: true,
  11068. configurable: true
  11069. });
  11070. Object.defineProperty(Engine, "INCR_WRAP", {
  11071. get: function () {
  11072. return Engine._INCR_WRAP;
  11073. },
  11074. enumerable: true,
  11075. configurable: true
  11076. });
  11077. Object.defineProperty(Engine, "DECR_WRAP", {
  11078. get: function () {
  11079. return Engine._DECR_WRAP;
  11080. },
  11081. enumerable: true,
  11082. configurable: true
  11083. });
  11084. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11085. get: function () {
  11086. return Engine._ALPHA_DISABLE;
  11087. },
  11088. enumerable: true,
  11089. configurable: true
  11090. });
  11091. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11092. get: function () {
  11093. return Engine._ALPHA_ONEONE;
  11094. },
  11095. enumerable: true,
  11096. configurable: true
  11097. });
  11098. Object.defineProperty(Engine, "ALPHA_ADD", {
  11099. get: function () {
  11100. return Engine._ALPHA_ADD;
  11101. },
  11102. enumerable: true,
  11103. configurable: true
  11104. });
  11105. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11106. get: function () {
  11107. return Engine._ALPHA_COMBINE;
  11108. },
  11109. enumerable: true,
  11110. configurable: true
  11111. });
  11112. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11113. get: function () {
  11114. return Engine._ALPHA_SUBTRACT;
  11115. },
  11116. enumerable: true,
  11117. configurable: true
  11118. });
  11119. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11120. get: function () {
  11121. return Engine._ALPHA_MULTIPLY;
  11122. },
  11123. enumerable: true,
  11124. configurable: true
  11125. });
  11126. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11127. get: function () {
  11128. return Engine._ALPHA_MAXIMIZED;
  11129. },
  11130. enumerable: true,
  11131. configurable: true
  11132. });
  11133. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11134. get: function () {
  11135. return Engine._ALPHA_PREMULTIPLIED;
  11136. },
  11137. enumerable: true,
  11138. configurable: true
  11139. });
  11140. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11141. get: function () {
  11142. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11143. },
  11144. enumerable: true,
  11145. configurable: true
  11146. });
  11147. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11148. get: function () {
  11149. return Engine._ALPHA_INTERPOLATE;
  11150. },
  11151. enumerable: true,
  11152. configurable: true
  11153. });
  11154. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11155. get: function () {
  11156. return Engine._ALPHA_SCREENMODE;
  11157. },
  11158. enumerable: true,
  11159. configurable: true
  11160. });
  11161. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11162. get: function () {
  11163. return Engine._DELAYLOADSTATE_NONE;
  11164. },
  11165. enumerable: true,
  11166. configurable: true
  11167. });
  11168. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11169. get: function () {
  11170. return Engine._DELAYLOADSTATE_LOADED;
  11171. },
  11172. enumerable: true,
  11173. configurable: true
  11174. });
  11175. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11176. get: function () {
  11177. return Engine._DELAYLOADSTATE_LOADING;
  11178. },
  11179. enumerable: true,
  11180. configurable: true
  11181. });
  11182. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11183. get: function () {
  11184. return Engine._DELAYLOADSTATE_NOTLOADED;
  11185. },
  11186. enumerable: true,
  11187. configurable: true
  11188. });
  11189. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11190. get: function () {
  11191. return Engine._TEXTUREFORMAT_ALPHA;
  11192. },
  11193. enumerable: true,
  11194. configurable: true
  11195. });
  11196. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11197. get: function () {
  11198. return Engine._TEXTUREFORMAT_LUMINANCE;
  11199. },
  11200. enumerable: true,
  11201. configurable: true
  11202. });
  11203. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11204. /**
  11205. * R32F
  11206. */
  11207. get: function () {
  11208. return Engine._TEXTUREFORMAT_R32F;
  11209. },
  11210. enumerable: true,
  11211. configurable: true
  11212. });
  11213. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11214. /**
  11215. * RG32F
  11216. */
  11217. get: function () {
  11218. return Engine._TEXTUREFORMAT_RG32F;
  11219. },
  11220. enumerable: true,
  11221. configurable: true
  11222. });
  11223. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11224. /**
  11225. * RGB32F
  11226. */
  11227. get: function () {
  11228. return Engine._TEXTUREFORMAT_RGB32F;
  11229. },
  11230. enumerable: true,
  11231. configurable: true
  11232. });
  11233. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11234. /**
  11235. * RGBA32F
  11236. */
  11237. get: function () {
  11238. return Engine._TEXTUREFORMAT_RGBA32F;
  11239. },
  11240. enumerable: true,
  11241. configurable: true
  11242. });
  11243. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11244. get: function () {
  11245. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11246. },
  11247. enumerable: true,
  11248. configurable: true
  11249. });
  11250. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11251. get: function () {
  11252. return Engine._TEXTUREFORMAT_RGB;
  11253. },
  11254. enumerable: true,
  11255. configurable: true
  11256. });
  11257. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11258. get: function () {
  11259. return Engine._TEXTUREFORMAT_RGBA;
  11260. },
  11261. enumerable: true,
  11262. configurable: true
  11263. });
  11264. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11265. get: function () {
  11266. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11267. },
  11268. enumerable: true,
  11269. configurable: true
  11270. });
  11271. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11272. get: function () {
  11273. return Engine._TEXTURETYPE_FLOAT;
  11274. },
  11275. enumerable: true,
  11276. configurable: true
  11277. });
  11278. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11279. get: function () {
  11280. return Engine._TEXTURETYPE_HALF_FLOAT;
  11281. },
  11282. enumerable: true,
  11283. configurable: true
  11284. });
  11285. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11286. get: function () {
  11287. return Engine._SCALEMODE_FLOOR;
  11288. },
  11289. enumerable: true,
  11290. configurable: true
  11291. });
  11292. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11293. get: function () {
  11294. return Engine._SCALEMODE_NEAREST;
  11295. },
  11296. enumerable: true,
  11297. configurable: true
  11298. });
  11299. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11300. get: function () {
  11301. return Engine._SCALEMODE_CEILING;
  11302. },
  11303. enumerable: true,
  11304. configurable: true
  11305. });
  11306. Object.defineProperty(Engine, "Version", {
  11307. get: function () {
  11308. return "3.2.0-beta.3";
  11309. },
  11310. enumerable: true,
  11311. configurable: true
  11312. });
  11313. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11314. get: function () {
  11315. return this._vrExclusivePointerMode;
  11316. },
  11317. enumerable: true,
  11318. configurable: true
  11319. });
  11320. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11321. get: function () {
  11322. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11323. },
  11324. enumerable: true,
  11325. configurable: true
  11326. });
  11327. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11328. get: function () {
  11329. return this._webGLVersion < 2 || this.forcePOTTextures;
  11330. },
  11331. enumerable: true,
  11332. configurable: true
  11333. });
  11334. Object.defineProperty(Engine.prototype, "badOS", {
  11335. get: function () {
  11336. return this._badOS;
  11337. },
  11338. enumerable: true,
  11339. configurable: true
  11340. });
  11341. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  11342. get: function () {
  11343. return this._badDesktopOS;
  11344. },
  11345. enumerable: true,
  11346. configurable: true
  11347. });
  11348. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11349. get: function () {
  11350. return this._performanceMonitor;
  11351. },
  11352. enumerable: true,
  11353. configurable: true
  11354. });
  11355. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11356. get: function () {
  11357. return this._texturesSupported;
  11358. },
  11359. enumerable: true,
  11360. configurable: true
  11361. });
  11362. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11363. get: function () {
  11364. return this._textureFormatInUse;
  11365. },
  11366. enumerable: true,
  11367. configurable: true
  11368. });
  11369. Object.defineProperty(Engine.prototype, "currentViewport", {
  11370. get: function () {
  11371. return this._cachedViewport;
  11372. },
  11373. enumerable: true,
  11374. configurable: true
  11375. });
  11376. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11377. // Empty texture
  11378. get: function () {
  11379. if (!this._emptyTexture) {
  11380. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11381. }
  11382. return this._emptyTexture;
  11383. },
  11384. enumerable: true,
  11385. configurable: true
  11386. });
  11387. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11388. get: function () {
  11389. if (!this._emptyTexture3D) {
  11390. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11391. }
  11392. return this._emptyTexture3D;
  11393. },
  11394. enumerable: true,
  11395. configurable: true
  11396. });
  11397. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11398. get: function () {
  11399. if (!this._emptyCubeTexture) {
  11400. var faceData = new Uint8Array(4);
  11401. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11402. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11403. }
  11404. return this._emptyCubeTexture;
  11405. },
  11406. enumerable: true,
  11407. configurable: true
  11408. });
  11409. Engine.prototype._rebuildInternalTextures = function () {
  11410. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11411. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11412. var internalTexture = currentState_1[_i];
  11413. internalTexture._rebuild();
  11414. }
  11415. };
  11416. Engine.prototype._rebuildEffects = function () {
  11417. for (var key in this._compiledEffects) {
  11418. var effect = this._compiledEffects[key];
  11419. effect._prepareEffect();
  11420. }
  11421. BABYLON.Effect.ResetCache();
  11422. };
  11423. Engine.prototype._rebuildBuffers = function () {
  11424. // Index / Vertex
  11425. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11426. var scene = _a[_i];
  11427. scene.resetCachedMaterial();
  11428. scene._rebuildGeometries();
  11429. scene._rebuildTextures();
  11430. }
  11431. // Uniforms
  11432. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11433. var uniformBuffer = _c[_b];
  11434. uniformBuffer._rebuild();
  11435. }
  11436. };
  11437. Engine.prototype._initGLContext = function () {
  11438. // Caps
  11439. this._caps = new EngineCapabilities();
  11440. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11441. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11442. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11443. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11444. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11445. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11446. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11447. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11448. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11449. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11450. // Infos
  11451. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11452. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11453. if (rendererInfo != null) {
  11454. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11455. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11456. }
  11457. if (!this._glVendor) {
  11458. this._glVendor = "Unknown vendor";
  11459. }
  11460. if (!this._glRenderer) {
  11461. this._glRenderer = "Unknown renderer";
  11462. }
  11463. // Constants
  11464. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11465. if (this._gl.RGBA16F !== 0x881A) {
  11466. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11467. }
  11468. if (this._gl.RGBA32F !== 0x8814) {
  11469. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11470. }
  11471. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11472. this._gl.DEPTH24_STENCIL8 = 35056;
  11473. }
  11474. // Extensions
  11475. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11476. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11477. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11478. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11479. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11480. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11481. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11482. 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');
  11483. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11484. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11485. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11486. this._caps.highPrecisionShaderSupported = true;
  11487. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11488. if (this._caps.timerQuery) {
  11489. if (this._webGLVersion === 1) {
  11490. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11491. }
  11492. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11493. }
  11494. // Checks if some of the format renders first to allow the use of webgl inspector.
  11495. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11496. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11497. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11498. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11499. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11500. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11501. if (this._webGLVersion > 1) {
  11502. this._gl.HALF_FLOAT_OES = 0x140B;
  11503. }
  11504. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11505. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11506. // Draw buffers
  11507. if (this._webGLVersion > 1) {
  11508. this._caps.drawBuffersExtension = true;
  11509. }
  11510. else {
  11511. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11512. if (drawBuffersExtension !== null) {
  11513. this._caps.drawBuffersExtension = true;
  11514. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11515. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11516. for (var i = 0; i < 16; i++) {
  11517. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11518. }
  11519. }
  11520. else {
  11521. this._caps.drawBuffersExtension = false;
  11522. }
  11523. }
  11524. // Depth Texture
  11525. if (this._webGLVersion > 1) {
  11526. this._caps.depthTextureExtension = true;
  11527. }
  11528. else {
  11529. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11530. if (depthTextureExtension != null) {
  11531. this._caps.depthTextureExtension = true;
  11532. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11533. }
  11534. }
  11535. // Vertex array object
  11536. if (this._webGLVersion > 1) {
  11537. this._caps.vertexArrayObject = true;
  11538. }
  11539. else {
  11540. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11541. if (vertexArrayObjectExtension != null) {
  11542. this._caps.vertexArrayObject = true;
  11543. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11544. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11545. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11546. }
  11547. else {
  11548. this._caps.vertexArrayObject = false;
  11549. }
  11550. }
  11551. // Instances count
  11552. if (this._webGLVersion > 1) {
  11553. this._caps.instancedArrays = true;
  11554. }
  11555. else {
  11556. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11557. if (instanceExtension != null) {
  11558. this._caps.instancedArrays = true;
  11559. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11560. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11561. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11562. }
  11563. else {
  11564. this._caps.instancedArrays = false;
  11565. }
  11566. }
  11567. // Intelligently add supported compressed formats in order to check for.
  11568. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11569. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11570. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11571. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11572. if (this._caps.astc)
  11573. this.texturesSupported.push('-astc.ktx');
  11574. if (this._caps.s3tc)
  11575. this.texturesSupported.push('-dxt.ktx');
  11576. if (this._caps.pvrtc)
  11577. this.texturesSupported.push('-pvrtc.ktx');
  11578. if (this._caps.etc2)
  11579. this.texturesSupported.push('-etc2.ktx');
  11580. if (this._caps.etc1)
  11581. this.texturesSupported.push('-etc1.ktx');
  11582. if (this._gl.getShaderPrecisionFormat) {
  11583. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11584. if (highp) {
  11585. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11586. }
  11587. }
  11588. // Depth buffer
  11589. this.setDepthBuffer(true);
  11590. this.setDepthFunctionToLessOrEqual();
  11591. this.setDepthWrite(true);
  11592. // Texture maps
  11593. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11594. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11595. this._nextFreeTextureSlots.push(slot);
  11596. }
  11597. };
  11598. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11599. get: function () {
  11600. return this._webGLVersion;
  11601. },
  11602. enumerable: true,
  11603. configurable: true
  11604. });
  11605. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11606. /**
  11607. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11608. */
  11609. get: function () {
  11610. return this._isStencilEnable;
  11611. },
  11612. enumerable: true,
  11613. configurable: true
  11614. });
  11615. Engine.prototype._prepareWorkingCanvas = function () {
  11616. if (this._workingCanvas) {
  11617. return;
  11618. }
  11619. this._workingCanvas = document.createElement("canvas");
  11620. var context = this._workingCanvas.getContext("2d");
  11621. if (context) {
  11622. this._workingContext = context;
  11623. }
  11624. };
  11625. Engine.prototype.resetTextureCache = function () {
  11626. for (var key in this._boundTexturesCache) {
  11627. var boundTexture = this._boundTexturesCache[key];
  11628. if (boundTexture) {
  11629. this._removeDesignatedSlot(boundTexture);
  11630. }
  11631. this._boundTexturesCache[key] = null;
  11632. }
  11633. if (!this.disableTextureBindingOptimization) {
  11634. this._nextFreeTextureSlots = [];
  11635. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11636. this._nextFreeTextureSlots.push(slot);
  11637. }
  11638. }
  11639. this._currentTextureChannel = -1;
  11640. };
  11641. Engine.prototype.isDeterministicLockStep = function () {
  11642. return this._deterministicLockstep;
  11643. };
  11644. Engine.prototype.getLockstepMaxSteps = function () {
  11645. return this._lockstepMaxSteps;
  11646. };
  11647. Engine.prototype.getGlInfo = function () {
  11648. return {
  11649. vendor: this._glVendor,
  11650. renderer: this._glRenderer,
  11651. version: this._glVersion
  11652. };
  11653. };
  11654. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11655. if (useScreen === void 0) { useScreen = false; }
  11656. var viewport = camera.viewport;
  11657. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11658. };
  11659. Engine.prototype.getRenderWidth = function (useScreen) {
  11660. if (useScreen === void 0) { useScreen = false; }
  11661. if (!useScreen && this._currentRenderTarget) {
  11662. return this._currentRenderTarget.width;
  11663. }
  11664. return this._gl.drawingBufferWidth;
  11665. };
  11666. Engine.prototype.getRenderHeight = function (useScreen) {
  11667. if (useScreen === void 0) { useScreen = false; }
  11668. if (!useScreen && this._currentRenderTarget) {
  11669. return this._currentRenderTarget.height;
  11670. }
  11671. return this._gl.drawingBufferHeight;
  11672. };
  11673. Engine.prototype.getRenderingCanvas = function () {
  11674. return this._renderingCanvas;
  11675. };
  11676. Engine.prototype.getRenderingCanvasClientRect = function () {
  11677. if (!this._renderingCanvas) {
  11678. return null;
  11679. }
  11680. return this._renderingCanvas.getBoundingClientRect();
  11681. };
  11682. Engine.prototype.setHardwareScalingLevel = function (level) {
  11683. this._hardwareScalingLevel = level;
  11684. this.resize();
  11685. };
  11686. Engine.prototype.getHardwareScalingLevel = function () {
  11687. return this._hardwareScalingLevel;
  11688. };
  11689. Engine.prototype.getLoadedTexturesCache = function () {
  11690. return this._internalTexturesCache;
  11691. };
  11692. Engine.prototype.getCaps = function () {
  11693. return this._caps;
  11694. };
  11695. Object.defineProperty(Engine.prototype, "drawCalls", {
  11696. /** The number of draw calls submitted last frame */
  11697. get: function () {
  11698. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11699. return 0;
  11700. },
  11701. enumerable: true,
  11702. configurable: true
  11703. });
  11704. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11705. get: function () {
  11706. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11707. return null;
  11708. },
  11709. enumerable: true,
  11710. configurable: true
  11711. });
  11712. Engine.prototype.getDepthFunction = function () {
  11713. return this._depthCullingState.depthFunc;
  11714. };
  11715. Engine.prototype.setDepthFunction = function (depthFunc) {
  11716. this._depthCullingState.depthFunc = depthFunc;
  11717. };
  11718. Engine.prototype.setDepthFunctionToGreater = function () {
  11719. this._depthCullingState.depthFunc = this._gl.GREATER;
  11720. };
  11721. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11722. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11723. };
  11724. Engine.prototype.setDepthFunctionToLess = function () {
  11725. this._depthCullingState.depthFunc = this._gl.LESS;
  11726. };
  11727. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11728. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11729. };
  11730. Engine.prototype.getStencilBuffer = function () {
  11731. return this._stencilState.stencilTest;
  11732. };
  11733. Engine.prototype.setStencilBuffer = function (enable) {
  11734. this._stencilState.stencilTest = enable;
  11735. };
  11736. Engine.prototype.getStencilMask = function () {
  11737. return this._stencilState.stencilMask;
  11738. };
  11739. Engine.prototype.setStencilMask = function (mask) {
  11740. this._stencilState.stencilMask = mask;
  11741. };
  11742. Engine.prototype.getStencilFunction = function () {
  11743. return this._stencilState.stencilFunc;
  11744. };
  11745. Engine.prototype.getStencilFunctionReference = function () {
  11746. return this._stencilState.stencilFuncRef;
  11747. };
  11748. Engine.prototype.getStencilFunctionMask = function () {
  11749. return this._stencilState.stencilFuncMask;
  11750. };
  11751. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11752. this._stencilState.stencilFunc = stencilFunc;
  11753. };
  11754. Engine.prototype.setStencilFunctionReference = function (reference) {
  11755. this._stencilState.stencilFuncRef = reference;
  11756. };
  11757. Engine.prototype.setStencilFunctionMask = function (mask) {
  11758. this._stencilState.stencilFuncMask = mask;
  11759. };
  11760. Engine.prototype.getStencilOperationFail = function () {
  11761. return this._stencilState.stencilOpStencilFail;
  11762. };
  11763. Engine.prototype.getStencilOperationDepthFail = function () {
  11764. return this._stencilState.stencilOpDepthFail;
  11765. };
  11766. Engine.prototype.getStencilOperationPass = function () {
  11767. return this._stencilState.stencilOpStencilDepthPass;
  11768. };
  11769. Engine.prototype.setStencilOperationFail = function (operation) {
  11770. this._stencilState.stencilOpStencilFail = operation;
  11771. };
  11772. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11773. this._stencilState.stencilOpDepthFail = operation;
  11774. };
  11775. Engine.prototype.setStencilOperationPass = function (operation) {
  11776. this._stencilState.stencilOpStencilDepthPass = operation;
  11777. };
  11778. Engine.prototype.setDitheringState = function (value) {
  11779. if (value) {
  11780. this._gl.enable(this._gl.DITHER);
  11781. }
  11782. else {
  11783. this._gl.disable(this._gl.DITHER);
  11784. }
  11785. };
  11786. Engine.prototype.setRasterizerState = function (value) {
  11787. if (value) {
  11788. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11789. }
  11790. else {
  11791. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11792. }
  11793. };
  11794. /**
  11795. * stop executing a render loop function and remove it from the execution array
  11796. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11797. */
  11798. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11799. if (!renderFunction) {
  11800. this._activeRenderLoops = [];
  11801. return;
  11802. }
  11803. var index = this._activeRenderLoops.indexOf(renderFunction);
  11804. if (index >= 0) {
  11805. this._activeRenderLoops.splice(index, 1);
  11806. }
  11807. };
  11808. Engine.prototype._renderLoop = function () {
  11809. if (!this._contextWasLost) {
  11810. var shouldRender = true;
  11811. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11812. shouldRender = false;
  11813. }
  11814. if (shouldRender) {
  11815. // Start new frame
  11816. this.beginFrame();
  11817. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11818. var renderFunction = this._activeRenderLoops[index];
  11819. renderFunction();
  11820. }
  11821. // Present
  11822. this.endFrame();
  11823. }
  11824. }
  11825. if (this._activeRenderLoops.length > 0) {
  11826. // Register new frame
  11827. var requester = null;
  11828. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11829. requester = this._vrDisplay;
  11830. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11831. }
  11832. else {
  11833. this._renderingQueueLaunched = false;
  11834. }
  11835. };
  11836. /**
  11837. * Register and execute a render loop. The engine can have more than one render function.
  11838. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11839. * @example
  11840. * engine.runRenderLoop(function () {
  11841. * scene.render()
  11842. * })
  11843. */
  11844. Engine.prototype.runRenderLoop = function (renderFunction) {
  11845. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11846. return;
  11847. }
  11848. this._activeRenderLoops.push(renderFunction);
  11849. if (!this._renderingQueueLaunched) {
  11850. this._renderingQueueLaunched = true;
  11851. this._bindedRenderFunction = this._renderLoop.bind(this);
  11852. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11853. }
  11854. };
  11855. /**
  11856. * Toggle full screen mode.
  11857. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11858. * @param {any} options - an options object to be sent to the requestFullscreen function
  11859. */
  11860. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11861. if (this.isFullscreen) {
  11862. BABYLON.Tools.ExitFullscreen();
  11863. }
  11864. else {
  11865. this._pointerLockRequested = requestPointerLock;
  11866. if (this._renderingCanvas) {
  11867. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11868. }
  11869. }
  11870. };
  11871. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11872. if (stencil === void 0) { stencil = false; }
  11873. this.applyStates();
  11874. var mode = 0;
  11875. if (backBuffer && color) {
  11876. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11877. mode |= this._gl.COLOR_BUFFER_BIT;
  11878. }
  11879. if (depth) {
  11880. this._gl.clearDepth(1.0);
  11881. mode |= this._gl.DEPTH_BUFFER_BIT;
  11882. }
  11883. if (stencil) {
  11884. this._gl.clearStencil(0);
  11885. mode |= this._gl.STENCIL_BUFFER_BIT;
  11886. }
  11887. this._gl.clear(mode);
  11888. };
  11889. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11890. var gl = this._gl;
  11891. // Save state
  11892. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11893. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11894. // Change state
  11895. gl.enable(gl.SCISSOR_TEST);
  11896. gl.scissor(x, y, width, height);
  11897. // Clear
  11898. this.clear(clearColor, true, true, true);
  11899. // Restore state
  11900. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11901. if (curScissor === true) {
  11902. gl.enable(gl.SCISSOR_TEST);
  11903. }
  11904. else {
  11905. gl.disable(gl.SCISSOR_TEST);
  11906. }
  11907. };
  11908. /**
  11909. * Set the WebGL's viewport
  11910. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11911. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11912. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11913. */
  11914. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11915. var width = requiredWidth || this.getRenderWidth();
  11916. var height = requiredHeight || this.getRenderHeight();
  11917. var x = viewport.x || 0;
  11918. var y = viewport.y || 0;
  11919. this._cachedViewport = viewport;
  11920. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11921. };
  11922. /**
  11923. * Directly set the WebGL Viewport
  11924. * The x, y, width & height are directly passed to the WebGL call
  11925. * @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.
  11926. */
  11927. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11928. var currentViewport = this._cachedViewport;
  11929. this._cachedViewport = null;
  11930. this._gl.viewport(x, y, width, height);
  11931. return currentViewport;
  11932. };
  11933. Engine.prototype.beginFrame = function () {
  11934. this.onBeginFrameObservable.notifyObservers(this);
  11935. this._measureFps();
  11936. };
  11937. Engine.prototype.endFrame = function () {
  11938. //force a flush in case we are using a bad OS.
  11939. if (this._badOS) {
  11940. this.flushFramebuffer();
  11941. }
  11942. //submit frame to the vr device, if enabled
  11943. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11944. // TODO: We should only submit the frame if we read frameData successfully.
  11945. this._vrDisplay.submitFrame();
  11946. }
  11947. this.onEndFrameObservable.notifyObservers(this);
  11948. };
  11949. /**
  11950. * resize the view according to the canvas' size.
  11951. * @example
  11952. * window.addEventListener("resize", function () {
  11953. * engine.resize();
  11954. * });
  11955. */
  11956. Engine.prototype.resize = function () {
  11957. // We're not resizing the size of the canvas while in VR mode & presenting
  11958. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11959. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11960. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11961. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11962. }
  11963. };
  11964. /**
  11965. * force a specific size of the canvas
  11966. * @param {number} width - the new canvas' width
  11967. * @param {number} height - the new canvas' height
  11968. */
  11969. Engine.prototype.setSize = function (width, height) {
  11970. if (!this._renderingCanvas) {
  11971. return;
  11972. }
  11973. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11974. return;
  11975. }
  11976. this._renderingCanvas.width = width;
  11977. this._renderingCanvas.height = height;
  11978. for (var index = 0; index < this.scenes.length; index++) {
  11979. var scene = this.scenes[index];
  11980. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11981. var cam = scene.cameras[camIndex];
  11982. cam._currentRenderId = 0;
  11983. }
  11984. }
  11985. if (this.onResizeObservable.hasObservers) {
  11986. this.onResizeObservable.notifyObservers(this);
  11987. }
  11988. };
  11989. // WebVR functions
  11990. Engine.prototype.isVRDevicePresent = function () {
  11991. return !!this._vrDisplay;
  11992. };
  11993. Engine.prototype.getVRDevice = function () {
  11994. return this._vrDisplay;
  11995. };
  11996. /**
  11997. * Initializes a webVR display and starts listening to display change events.
  11998. * The onVRDisplayChangedObservable will be notified upon these changes.
  11999. * @returns The onVRDisplayChangedObservable.
  12000. */
  12001. Engine.prototype.initWebVR = function () {
  12002. this.initWebVRAsync();
  12003. return this.onVRDisplayChangedObservable;
  12004. };
  12005. /**
  12006. * Initializes a webVR display and starts listening to display change events.
  12007. * The onVRDisplayChangedObservable will be notified upon these changes.
  12008. * @returns A promise containing a VRDisplay and if vr is supported.
  12009. */
  12010. Engine.prototype.initWebVRAsync = function () {
  12011. var _this = this;
  12012. var notifyObservers = function () {
  12013. var eventArgs = {
  12014. vrDisplay: _this._vrDisplay,
  12015. vrSupported: _this._vrSupported
  12016. };
  12017. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12018. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12019. };
  12020. if (!this._onVrDisplayConnect) {
  12021. this._onVrDisplayConnect = function (event) {
  12022. _this._vrDisplay = event.display;
  12023. notifyObservers();
  12024. };
  12025. this._onVrDisplayDisconnect = function () {
  12026. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12027. _this._vrDisplay = undefined;
  12028. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12029. notifyObservers();
  12030. };
  12031. this._onVrDisplayPresentChange = function () {
  12032. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12033. };
  12034. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12035. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12036. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12037. }
  12038. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12039. this._webVRInitPromise.then(notifyObservers);
  12040. return this._webVRInitPromise;
  12041. };
  12042. Engine.prototype.enableVR = function () {
  12043. var _this = this;
  12044. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12045. var onResolved = function () {
  12046. _this.onVRRequestPresentComplete.notifyObservers(true);
  12047. _this._onVRFullScreenTriggered();
  12048. };
  12049. var onRejected = function () {
  12050. _this.onVRRequestPresentComplete.notifyObservers(false);
  12051. };
  12052. this.onVRRequestPresentStart.notifyObservers(this);
  12053. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12054. }
  12055. };
  12056. Engine.prototype.disableVR = function () {
  12057. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12058. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12059. }
  12060. };
  12061. Engine.prototype._getVRDisplaysAsync = function () {
  12062. var _this = this;
  12063. return new Promise(function (res, rej) {
  12064. if (navigator.getVRDisplays) {
  12065. navigator.getVRDisplays().then(function (devices) {
  12066. _this._vrSupported = true;
  12067. // note that devices may actually be an empty array. This is fine;
  12068. // we expect this._vrDisplay to be undefined in this case.
  12069. _this._vrDisplay = devices[0];
  12070. res({
  12071. vrDisplay: _this._vrDisplay,
  12072. vrSupported: _this._vrSupported
  12073. });
  12074. });
  12075. }
  12076. else {
  12077. _this._vrDisplay = undefined;
  12078. _this._vrSupported = false;
  12079. res({
  12080. vrDisplay: _this._vrDisplay,
  12081. vrSupported: _this._vrSupported
  12082. });
  12083. }
  12084. });
  12085. };
  12086. /**
  12087. * Binds the frame buffer to the specified texture.
  12088. * @param texture The texture to render to or null for the default canvas
  12089. * @param faceIndex The face of the texture to render to in case of cube texture
  12090. * @param requiredWidth The width of the target to render to
  12091. * @param requiredHeight The height of the target to render to
  12092. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12093. * @param depthStencilTexture The depth stencil texture to use to render
  12094. */
  12095. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  12096. if (this._currentRenderTarget) {
  12097. this.unBindFramebuffer(this._currentRenderTarget);
  12098. }
  12099. this._currentRenderTarget = texture;
  12100. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12101. var gl = this._gl;
  12102. if (texture.isCube) {
  12103. if (faceIndex === undefined) {
  12104. faceIndex = 0;
  12105. }
  12106. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  12107. if (depthStencilTexture) {
  12108. if (depthStencilTexture._generateStencilBuffer) {
  12109. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12110. }
  12111. else {
  12112. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12113. }
  12114. }
  12115. }
  12116. if (this._cachedViewport && !forceFullscreenViewport) {
  12117. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12118. }
  12119. else {
  12120. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  12121. }
  12122. this.wipeCaches();
  12123. };
  12124. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12125. if (this._currentFramebuffer !== framebuffer) {
  12126. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12127. this._currentFramebuffer = framebuffer;
  12128. }
  12129. };
  12130. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12131. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12132. this._currentRenderTarget = null;
  12133. // If MSAA, we need to bitblt back to main texture
  12134. var gl = this._gl;
  12135. if (texture._MSAAFramebuffer) {
  12136. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12137. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12138. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12139. }
  12140. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12141. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12142. gl.generateMipmap(gl.TEXTURE_2D);
  12143. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12144. }
  12145. if (onBeforeUnbind) {
  12146. if (texture._MSAAFramebuffer) {
  12147. // Bind the correct framebuffer
  12148. this.bindUnboundFramebuffer(texture._framebuffer);
  12149. }
  12150. onBeforeUnbind();
  12151. }
  12152. this.bindUnboundFramebuffer(null);
  12153. };
  12154. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12155. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12156. this._currentRenderTarget = null;
  12157. // If MSAA, we need to bitblt back to main texture
  12158. var gl = this._gl;
  12159. if (textures[0]._MSAAFramebuffer) {
  12160. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12161. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12162. var attachments = textures[0]._attachments;
  12163. if (!attachments) {
  12164. attachments = new Array(textures.length);
  12165. textures[0]._attachments = attachments;
  12166. }
  12167. for (var i = 0; i < textures.length; i++) {
  12168. var texture = textures[i];
  12169. for (var j = 0; j < attachments.length; j++) {
  12170. attachments[j] = gl.NONE;
  12171. }
  12172. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12173. gl.readBuffer(attachments[i]);
  12174. gl.drawBuffers(attachments);
  12175. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12176. }
  12177. for (var i = 0; i < attachments.length; i++) {
  12178. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12179. }
  12180. gl.drawBuffers(attachments);
  12181. }
  12182. for (var i = 0; i < textures.length; i++) {
  12183. var texture = textures[i];
  12184. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12185. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12186. gl.generateMipmap(gl.TEXTURE_2D);
  12187. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12188. }
  12189. }
  12190. if (onBeforeUnbind) {
  12191. if (textures[0]._MSAAFramebuffer) {
  12192. // Bind the correct framebuffer
  12193. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12194. }
  12195. onBeforeUnbind();
  12196. }
  12197. this.bindUnboundFramebuffer(null);
  12198. };
  12199. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12200. if (texture.generateMipMaps) {
  12201. var gl = this._gl;
  12202. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12203. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12204. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12205. }
  12206. };
  12207. Engine.prototype.flushFramebuffer = function () {
  12208. this._gl.flush();
  12209. };
  12210. Engine.prototype.restoreDefaultFramebuffer = function () {
  12211. if (this._currentRenderTarget) {
  12212. this.unBindFramebuffer(this._currentRenderTarget);
  12213. }
  12214. else {
  12215. this.bindUnboundFramebuffer(null);
  12216. }
  12217. if (this._cachedViewport) {
  12218. this.setViewport(this._cachedViewport);
  12219. }
  12220. this.wipeCaches();
  12221. };
  12222. // UBOs
  12223. Engine.prototype.createUniformBuffer = function (elements) {
  12224. var ubo = this._gl.createBuffer();
  12225. if (!ubo) {
  12226. throw new Error("Unable to create uniform buffer");
  12227. }
  12228. this.bindUniformBuffer(ubo);
  12229. if (elements instanceof Float32Array) {
  12230. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12231. }
  12232. else {
  12233. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12234. }
  12235. this.bindUniformBuffer(null);
  12236. ubo.references = 1;
  12237. return ubo;
  12238. };
  12239. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12240. var ubo = this._gl.createBuffer();
  12241. if (!ubo) {
  12242. throw new Error("Unable to create dynamic uniform buffer");
  12243. }
  12244. this.bindUniformBuffer(ubo);
  12245. if (elements instanceof Float32Array) {
  12246. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12247. }
  12248. else {
  12249. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12250. }
  12251. this.bindUniformBuffer(null);
  12252. ubo.references = 1;
  12253. return ubo;
  12254. };
  12255. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12256. this.bindUniformBuffer(uniformBuffer);
  12257. if (offset === undefined) {
  12258. offset = 0;
  12259. }
  12260. if (count === undefined) {
  12261. if (elements instanceof Float32Array) {
  12262. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12263. }
  12264. else {
  12265. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12266. }
  12267. }
  12268. else {
  12269. if (elements instanceof Float32Array) {
  12270. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12271. }
  12272. else {
  12273. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12274. }
  12275. }
  12276. this.bindUniformBuffer(null);
  12277. };
  12278. // VBOs
  12279. Engine.prototype._resetVertexBufferBinding = function () {
  12280. this.bindArrayBuffer(null);
  12281. this._cachedVertexBuffers = null;
  12282. };
  12283. Engine.prototype.createVertexBuffer = function (vertices) {
  12284. var vbo = this._gl.createBuffer();
  12285. if (!vbo) {
  12286. throw new Error("Unable to create vertex buffer");
  12287. }
  12288. this.bindArrayBuffer(vbo);
  12289. if (vertices instanceof Float32Array) {
  12290. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  12291. }
  12292. else {
  12293. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  12294. }
  12295. this._resetVertexBufferBinding();
  12296. vbo.references = 1;
  12297. return vbo;
  12298. };
  12299. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  12300. var vbo = this._gl.createBuffer();
  12301. if (!vbo) {
  12302. throw new Error("Unable to create dynamic vertex buffer");
  12303. }
  12304. this.bindArrayBuffer(vbo);
  12305. if (vertices instanceof Float32Array) {
  12306. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  12307. }
  12308. else {
  12309. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  12310. }
  12311. this._resetVertexBufferBinding();
  12312. vbo.references = 1;
  12313. return vbo;
  12314. };
  12315. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12316. if (offset === void 0) { offset = 0; }
  12317. // Force cache update
  12318. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12319. this.bindIndexBuffer(indexBuffer);
  12320. var arrayBuffer;
  12321. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12322. arrayBuffer = indices;
  12323. }
  12324. else {
  12325. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12326. }
  12327. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12328. this._resetIndexBufferBinding();
  12329. };
  12330. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  12331. this.bindArrayBuffer(vertexBuffer);
  12332. if (offset === undefined) {
  12333. offset = 0;
  12334. }
  12335. if (count === undefined) {
  12336. if (vertices instanceof Float32Array) {
  12337. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  12338. }
  12339. else {
  12340. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  12341. }
  12342. }
  12343. else {
  12344. if (vertices instanceof Float32Array) {
  12345. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  12346. }
  12347. else {
  12348. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  12349. }
  12350. }
  12351. this._resetVertexBufferBinding();
  12352. };
  12353. Engine.prototype._resetIndexBufferBinding = function () {
  12354. this.bindIndexBuffer(null);
  12355. this._cachedIndexBuffer = null;
  12356. };
  12357. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12358. var vbo = this._gl.createBuffer();
  12359. if (!vbo) {
  12360. throw new Error("Unable to create index buffer");
  12361. }
  12362. this.bindIndexBuffer(vbo);
  12363. // Check for 32 bits indices
  12364. var arrayBuffer;
  12365. var need32Bits = false;
  12366. if (indices instanceof Uint16Array) {
  12367. arrayBuffer = indices;
  12368. }
  12369. else {
  12370. //check 32 bit support
  12371. if (this._caps.uintIndices) {
  12372. if (indices instanceof Uint32Array) {
  12373. arrayBuffer = indices;
  12374. need32Bits = true;
  12375. }
  12376. else {
  12377. //number[] or Int32Array, check if 32 bit is necessary
  12378. for (var index = 0; index < indices.length; index++) {
  12379. if (indices[index] > 65535) {
  12380. need32Bits = true;
  12381. break;
  12382. }
  12383. }
  12384. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12385. }
  12386. }
  12387. else {
  12388. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12389. arrayBuffer = new Uint16Array(indices);
  12390. }
  12391. }
  12392. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12393. this._resetIndexBufferBinding();
  12394. vbo.references = 1;
  12395. vbo.is32Bits = need32Bits;
  12396. return vbo;
  12397. };
  12398. Engine.prototype.bindArrayBuffer = function (buffer) {
  12399. if (!this._vaoRecordInProgress) {
  12400. this._unbindVertexArrayObject();
  12401. }
  12402. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12403. };
  12404. Engine.prototype.bindUniformBuffer = function (buffer) {
  12405. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12406. };
  12407. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12408. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12409. };
  12410. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12411. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12412. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12413. };
  12414. ;
  12415. Engine.prototype.bindIndexBuffer = function (buffer) {
  12416. if (!this._vaoRecordInProgress) {
  12417. this._unbindVertexArrayObject();
  12418. }
  12419. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12420. };
  12421. Engine.prototype.bindBuffer = function (buffer, target) {
  12422. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12423. this._gl.bindBuffer(target, buffer);
  12424. this._currentBoundBuffer[target] = buffer;
  12425. }
  12426. };
  12427. Engine.prototype.updateArrayBuffer = function (data) {
  12428. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12429. };
  12430. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12431. var pointer = this._currentBufferPointers[indx];
  12432. var changed = false;
  12433. if (!pointer.active) {
  12434. changed = true;
  12435. pointer.active = true;
  12436. pointer.index = indx;
  12437. pointer.size = size;
  12438. pointer.type = type;
  12439. pointer.normalized = normalized;
  12440. pointer.stride = stride;
  12441. pointer.offset = offset;
  12442. pointer.buffer = buffer;
  12443. }
  12444. else {
  12445. if (pointer.buffer !== buffer) {
  12446. pointer.buffer = buffer;
  12447. changed = true;
  12448. }
  12449. if (pointer.size !== size) {
  12450. pointer.size = size;
  12451. changed = true;
  12452. }
  12453. if (pointer.type !== type) {
  12454. pointer.type = type;
  12455. changed = true;
  12456. }
  12457. if (pointer.normalized !== normalized) {
  12458. pointer.normalized = normalized;
  12459. changed = true;
  12460. }
  12461. if (pointer.stride !== stride) {
  12462. pointer.stride = stride;
  12463. changed = true;
  12464. }
  12465. if (pointer.offset !== offset) {
  12466. pointer.offset = offset;
  12467. changed = true;
  12468. }
  12469. }
  12470. if (changed || this._vaoRecordInProgress) {
  12471. this.bindArrayBuffer(buffer);
  12472. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12473. }
  12474. };
  12475. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12476. if (indexBuffer == null) {
  12477. return;
  12478. }
  12479. if (this._cachedIndexBuffer !== indexBuffer) {
  12480. this._cachedIndexBuffer = indexBuffer;
  12481. this.bindIndexBuffer(indexBuffer);
  12482. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12483. }
  12484. };
  12485. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12486. var attributes = effect.getAttributesNames();
  12487. if (!this._vaoRecordInProgress) {
  12488. this._unbindVertexArrayObject();
  12489. }
  12490. this.unbindAllAttributes();
  12491. for (var index = 0; index < attributes.length; index++) {
  12492. var order = effect.getAttributeLocation(index);
  12493. if (order >= 0) {
  12494. var vertexBuffer = vertexBuffers[attributes[index]];
  12495. if (!vertexBuffer) {
  12496. continue;
  12497. }
  12498. this._gl.enableVertexAttribArray(order);
  12499. if (!this._vaoRecordInProgress) {
  12500. this._vertexAttribArraysEnabled[order] = true;
  12501. }
  12502. var buffer = vertexBuffer.getBuffer();
  12503. if (buffer) {
  12504. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12505. if (vertexBuffer.getIsInstanced()) {
  12506. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12507. if (!this._vaoRecordInProgress) {
  12508. this._currentInstanceLocations.push(order);
  12509. this._currentInstanceBuffers.push(buffer);
  12510. }
  12511. }
  12512. }
  12513. }
  12514. }
  12515. };
  12516. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12517. var vao = this._gl.createVertexArray();
  12518. this._vaoRecordInProgress = true;
  12519. this._gl.bindVertexArray(vao);
  12520. this._mustWipeVertexAttributes = true;
  12521. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12522. this.bindIndexBuffer(indexBuffer);
  12523. this._vaoRecordInProgress = false;
  12524. this._gl.bindVertexArray(null);
  12525. return vao;
  12526. };
  12527. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12528. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12529. this._cachedVertexArrayObject = vertexArrayObject;
  12530. this._gl.bindVertexArray(vertexArrayObject);
  12531. this._cachedVertexBuffers = null;
  12532. this._cachedIndexBuffer = null;
  12533. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12534. this._mustWipeVertexAttributes = true;
  12535. }
  12536. };
  12537. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12538. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12539. this._cachedVertexBuffers = vertexBuffer;
  12540. this._cachedEffectForVertexBuffers = effect;
  12541. var attributesCount = effect.getAttributesCount();
  12542. this._unbindVertexArrayObject();
  12543. this.unbindAllAttributes();
  12544. var offset = 0;
  12545. for (var index = 0; index < attributesCount; index++) {
  12546. if (index < vertexDeclaration.length) {
  12547. var order = effect.getAttributeLocation(index);
  12548. if (order >= 0) {
  12549. this._gl.enableVertexAttribArray(order);
  12550. this._vertexAttribArraysEnabled[order] = true;
  12551. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12552. }
  12553. offset += vertexDeclaration[index] * 4;
  12554. }
  12555. }
  12556. }
  12557. this._bindIndexBufferWithCache(indexBuffer);
  12558. };
  12559. Engine.prototype._unbindVertexArrayObject = function () {
  12560. if (!this._cachedVertexArrayObject) {
  12561. return;
  12562. }
  12563. this._cachedVertexArrayObject = null;
  12564. this._gl.bindVertexArray(null);
  12565. };
  12566. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12567. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12568. this._cachedVertexBuffers = vertexBuffers;
  12569. this._cachedEffectForVertexBuffers = effect;
  12570. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12571. }
  12572. this._bindIndexBufferWithCache(indexBuffer);
  12573. };
  12574. Engine.prototype.unbindInstanceAttributes = function () {
  12575. var boundBuffer;
  12576. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12577. var instancesBuffer = this._currentInstanceBuffers[i];
  12578. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12579. boundBuffer = instancesBuffer;
  12580. this.bindArrayBuffer(instancesBuffer);
  12581. }
  12582. var offsetLocation = this._currentInstanceLocations[i];
  12583. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12584. }
  12585. this._currentInstanceBuffers.length = 0;
  12586. this._currentInstanceLocations.length = 0;
  12587. };
  12588. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12589. this._gl.deleteVertexArray(vao);
  12590. };
  12591. Engine.prototype._releaseBuffer = function (buffer) {
  12592. buffer.references--;
  12593. if (buffer.references === 0) {
  12594. this._gl.deleteBuffer(buffer);
  12595. return true;
  12596. }
  12597. return false;
  12598. };
  12599. Engine.prototype.createInstancesBuffer = function (capacity) {
  12600. var buffer = this._gl.createBuffer();
  12601. if (!buffer) {
  12602. throw new Error("Unable to create instance buffer");
  12603. }
  12604. buffer.capacity = capacity;
  12605. this.bindArrayBuffer(buffer);
  12606. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12607. return buffer;
  12608. };
  12609. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12610. this._gl.deleteBuffer(buffer);
  12611. };
  12612. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12613. this.bindArrayBuffer(instancesBuffer);
  12614. if (data) {
  12615. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12616. }
  12617. if (offsetLocations[0].index !== undefined) {
  12618. var stride = 0;
  12619. for (var i = 0; i < offsetLocations.length; i++) {
  12620. var ai = offsetLocations[i];
  12621. stride += ai.attributeSize * 4;
  12622. }
  12623. for (var i = 0; i < offsetLocations.length; i++) {
  12624. var ai = offsetLocations[i];
  12625. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12626. this._gl.enableVertexAttribArray(ai.index);
  12627. this._vertexAttribArraysEnabled[ai.index] = true;
  12628. }
  12629. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12630. this._gl.vertexAttribDivisor(ai.index, 1);
  12631. this._currentInstanceLocations.push(ai.index);
  12632. this._currentInstanceBuffers.push(instancesBuffer);
  12633. }
  12634. }
  12635. else {
  12636. for (var index = 0; index < 4; index++) {
  12637. var offsetLocation = offsetLocations[index];
  12638. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12639. this._gl.enableVertexAttribArray(offsetLocation);
  12640. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12641. }
  12642. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12643. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12644. this._currentInstanceLocations.push(offsetLocation);
  12645. this._currentInstanceBuffers.push(instancesBuffer);
  12646. }
  12647. }
  12648. };
  12649. Engine.prototype.applyStates = function () {
  12650. this._depthCullingState.apply(this._gl);
  12651. this._stencilState.apply(this._gl);
  12652. this._alphaState.apply(this._gl);
  12653. };
  12654. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12655. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12656. };
  12657. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12658. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12659. };
  12660. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12661. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12662. };
  12663. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12664. // Apply states
  12665. this.applyStates();
  12666. this._drawCalls.addCount(1, false);
  12667. // Render
  12668. var drawMode = this._drawMode(fillMode);
  12669. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12670. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12671. if (instancesCount) {
  12672. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12673. }
  12674. else {
  12675. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12676. }
  12677. };
  12678. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12679. // Apply states
  12680. this.applyStates();
  12681. this._drawCalls.addCount(1, false);
  12682. var drawMode = this._drawMode(fillMode);
  12683. if (instancesCount) {
  12684. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12685. }
  12686. else {
  12687. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12688. }
  12689. };
  12690. Engine.prototype._drawMode = function (fillMode) {
  12691. switch (fillMode) {
  12692. // Triangle views
  12693. case BABYLON.Material.TriangleFillMode:
  12694. return this._gl.TRIANGLES;
  12695. case BABYLON.Material.PointFillMode:
  12696. return this._gl.POINTS;
  12697. case BABYLON.Material.WireFrameFillMode:
  12698. return this._gl.LINES;
  12699. // Draw modes
  12700. case BABYLON.Material.PointListDrawMode:
  12701. return this._gl.POINTS;
  12702. case BABYLON.Material.LineListDrawMode:
  12703. return this._gl.LINES;
  12704. case BABYLON.Material.LineLoopDrawMode:
  12705. return this._gl.LINE_LOOP;
  12706. case BABYLON.Material.LineStripDrawMode:
  12707. return this._gl.LINE_STRIP;
  12708. case BABYLON.Material.TriangleStripDrawMode:
  12709. return this._gl.TRIANGLE_STRIP;
  12710. case BABYLON.Material.TriangleFanDrawMode:
  12711. return this._gl.TRIANGLE_FAN;
  12712. default:
  12713. return this._gl.TRIANGLES;
  12714. }
  12715. };
  12716. // Shaders
  12717. Engine.prototype._releaseEffect = function (effect) {
  12718. if (this._compiledEffects[effect._key]) {
  12719. delete this._compiledEffects[effect._key];
  12720. this._deleteProgram(effect.getProgram());
  12721. }
  12722. };
  12723. Engine.prototype._deleteProgram = function (program) {
  12724. if (program) {
  12725. program.__SPECTOR_rebuildProgram = null;
  12726. if (program.transformFeedback) {
  12727. this.deleteTransformFeedback(program.transformFeedback);
  12728. program.transformFeedback = null;
  12729. }
  12730. this._gl.deleteProgram(program);
  12731. }
  12732. };
  12733. /**
  12734. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12735. * @param samplers An array of string used to represent textures
  12736. */
  12737. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12738. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12739. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12740. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12741. if (this._compiledEffects[name]) {
  12742. var compiledEffect = this._compiledEffects[name];
  12743. if (onCompiled && compiledEffect.isReady()) {
  12744. onCompiled(compiledEffect);
  12745. }
  12746. return compiledEffect;
  12747. }
  12748. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12749. effect._key = name;
  12750. this._compiledEffects[name] = effect;
  12751. return effect;
  12752. };
  12753. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12754. if (uniformsNames === void 0) { uniformsNames = []; }
  12755. if (samplers === void 0) { samplers = []; }
  12756. if (defines === void 0) { defines = ""; }
  12757. return this.createEffect({
  12758. vertex: "particles",
  12759. fragmentElement: fragmentName
  12760. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12761. };
  12762. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12763. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12764. context = context || this._gl;
  12765. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12766. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12767. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12768. };
  12769. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12770. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12771. context = context || this._gl;
  12772. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12773. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  12774. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12775. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12776. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12777. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12778. return program;
  12779. };
  12780. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12781. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12782. var shaderProgram = context.createProgram();
  12783. if (!shaderProgram) {
  12784. throw new Error("Unable to create program");
  12785. }
  12786. context.attachShader(shaderProgram, vertexShader);
  12787. context.attachShader(shaderProgram, fragmentShader);
  12788. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12789. var transformFeedback = this.createTransformFeedback();
  12790. this.bindTransformFeedback(transformFeedback);
  12791. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12792. shaderProgram.transformFeedback = transformFeedback;
  12793. }
  12794. context.linkProgram(shaderProgram);
  12795. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12796. this.bindTransformFeedback(null);
  12797. }
  12798. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12799. if (!linked) {
  12800. context.validateProgram(shaderProgram);
  12801. var error = context.getProgramInfoLog(shaderProgram);
  12802. if (error) {
  12803. throw new Error(error);
  12804. }
  12805. }
  12806. context.deleteShader(vertexShader);
  12807. context.deleteShader(fragmentShader);
  12808. return shaderProgram;
  12809. };
  12810. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12811. var results = new Array();
  12812. for (var index = 0; index < uniformsNames.length; index++) {
  12813. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12814. }
  12815. return results;
  12816. };
  12817. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12818. var results = [];
  12819. for (var index = 0; index < attributesNames.length; index++) {
  12820. try {
  12821. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12822. }
  12823. catch (e) {
  12824. results.push(-1);
  12825. }
  12826. }
  12827. return results;
  12828. };
  12829. Engine.prototype.enableEffect = function (effect) {
  12830. if (!effect) {
  12831. return;
  12832. }
  12833. // Use program
  12834. this.bindSamplers(effect);
  12835. this._currentEffect = effect;
  12836. if (effect.onBind) {
  12837. effect.onBind(effect);
  12838. }
  12839. effect.onBindObservable.notifyObservers(effect);
  12840. };
  12841. Engine.prototype.setIntArray = function (uniform, array) {
  12842. if (!uniform)
  12843. return;
  12844. this._gl.uniform1iv(uniform, array);
  12845. };
  12846. Engine.prototype.setIntArray2 = function (uniform, array) {
  12847. if (!uniform || array.length % 2 !== 0)
  12848. return;
  12849. this._gl.uniform2iv(uniform, array);
  12850. };
  12851. Engine.prototype.setIntArray3 = function (uniform, array) {
  12852. if (!uniform || array.length % 3 !== 0)
  12853. return;
  12854. this._gl.uniform3iv(uniform, array);
  12855. };
  12856. Engine.prototype.setIntArray4 = function (uniform, array) {
  12857. if (!uniform || array.length % 4 !== 0)
  12858. return;
  12859. this._gl.uniform4iv(uniform, array);
  12860. };
  12861. Engine.prototype.setFloatArray = function (uniform, array) {
  12862. if (!uniform)
  12863. return;
  12864. this._gl.uniform1fv(uniform, array);
  12865. };
  12866. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12867. if (!uniform || array.length % 2 !== 0)
  12868. return;
  12869. this._gl.uniform2fv(uniform, array);
  12870. };
  12871. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12872. if (!uniform || array.length % 3 !== 0)
  12873. return;
  12874. this._gl.uniform3fv(uniform, array);
  12875. };
  12876. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12877. if (!uniform || array.length % 4 !== 0)
  12878. return;
  12879. this._gl.uniform4fv(uniform, array);
  12880. };
  12881. Engine.prototype.setArray = function (uniform, array) {
  12882. if (!uniform)
  12883. return;
  12884. this._gl.uniform1fv(uniform, array);
  12885. };
  12886. Engine.prototype.setArray2 = function (uniform, array) {
  12887. if (!uniform || array.length % 2 !== 0)
  12888. return;
  12889. this._gl.uniform2fv(uniform, array);
  12890. };
  12891. Engine.prototype.setArray3 = function (uniform, array) {
  12892. if (!uniform || array.length % 3 !== 0)
  12893. return;
  12894. this._gl.uniform3fv(uniform, array);
  12895. };
  12896. Engine.prototype.setArray4 = function (uniform, array) {
  12897. if (!uniform || array.length % 4 !== 0)
  12898. return;
  12899. this._gl.uniform4fv(uniform, array);
  12900. };
  12901. Engine.prototype.setMatrices = function (uniform, matrices) {
  12902. if (!uniform)
  12903. return;
  12904. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12905. };
  12906. Engine.prototype.setMatrix = function (uniform, matrix) {
  12907. if (!uniform)
  12908. return;
  12909. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12910. };
  12911. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12912. if (!uniform)
  12913. return;
  12914. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12915. };
  12916. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12917. if (!uniform)
  12918. return;
  12919. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12920. };
  12921. Engine.prototype.setInt = function (uniform, value) {
  12922. if (!uniform)
  12923. return;
  12924. this._gl.uniform1i(uniform, value);
  12925. };
  12926. Engine.prototype.setFloat = function (uniform, value) {
  12927. if (!uniform)
  12928. return;
  12929. this._gl.uniform1f(uniform, value);
  12930. };
  12931. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12932. if (!uniform)
  12933. return;
  12934. this._gl.uniform2f(uniform, x, y);
  12935. };
  12936. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12937. if (!uniform)
  12938. return;
  12939. this._gl.uniform3f(uniform, x, y, z);
  12940. };
  12941. Engine.prototype.setBool = function (uniform, bool) {
  12942. if (!uniform)
  12943. return;
  12944. this._gl.uniform1i(uniform, bool);
  12945. };
  12946. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12947. if (!uniform)
  12948. return;
  12949. this._gl.uniform4f(uniform, x, y, z, w);
  12950. };
  12951. Engine.prototype.setColor3 = function (uniform, color3) {
  12952. if (!uniform)
  12953. return;
  12954. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12955. };
  12956. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12957. if (!uniform)
  12958. return;
  12959. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12960. };
  12961. /**
  12962. * Sets a Color4 on a uniform variable
  12963. * @param uniform defines the uniform location
  12964. * @param color4 defines the value to be set
  12965. */
  12966. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  12967. if (!uniform)
  12968. return;
  12969. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  12970. };
  12971. // States
  12972. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12973. if (zOffset === void 0) { zOffset = 0; }
  12974. if (reverseSide === void 0) { reverseSide = false; }
  12975. // Culling
  12976. if (this._depthCullingState.cull !== culling || force) {
  12977. this._depthCullingState.cull = culling;
  12978. }
  12979. // Cull face
  12980. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12981. if (this._depthCullingState.cullFace !== cullFace || force) {
  12982. this._depthCullingState.cullFace = cullFace;
  12983. }
  12984. // Z offset
  12985. this.setZOffset(zOffset);
  12986. // Front face
  12987. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12988. if (this._depthCullingState.frontFace !== frontFace || force) {
  12989. this._depthCullingState.frontFace = frontFace;
  12990. }
  12991. };
  12992. Engine.prototype.setZOffset = function (value) {
  12993. this._depthCullingState.zOffset = value;
  12994. };
  12995. Engine.prototype.getZOffset = function () {
  12996. return this._depthCullingState.zOffset;
  12997. };
  12998. Engine.prototype.setDepthBuffer = function (enable) {
  12999. this._depthCullingState.depthTest = enable;
  13000. };
  13001. Engine.prototype.getDepthWrite = function () {
  13002. return this._depthCullingState.depthMask;
  13003. };
  13004. Engine.prototype.setDepthWrite = function (enable) {
  13005. this._depthCullingState.depthMask = enable;
  13006. };
  13007. Engine.prototype.setColorWrite = function (enable) {
  13008. this._gl.colorMask(enable, enable, enable, enable);
  13009. this._colorWrite = enable;
  13010. };
  13011. Engine.prototype.getColorWrite = function () {
  13012. return this._colorWrite;
  13013. };
  13014. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  13015. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  13016. };
  13017. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  13018. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  13019. if (this._alphaMode === mode) {
  13020. return;
  13021. }
  13022. switch (mode) {
  13023. case Engine.ALPHA_DISABLE:
  13024. this._alphaState.alphaBlend = false;
  13025. break;
  13026. case Engine.ALPHA_PREMULTIPLIED:
  13027. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  13028. this._alphaState.alphaBlend = true;
  13029. break;
  13030. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  13031. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  13032. this._alphaState.alphaBlend = true;
  13033. break;
  13034. case Engine.ALPHA_COMBINE:
  13035. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  13036. this._alphaState.alphaBlend = true;
  13037. break;
  13038. case Engine.ALPHA_ONEONE:
  13039. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  13040. this._alphaState.alphaBlend = true;
  13041. break;
  13042. case Engine.ALPHA_ADD:
  13043. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  13044. this._alphaState.alphaBlend = true;
  13045. break;
  13046. case Engine.ALPHA_SUBTRACT:
  13047. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  13048. this._alphaState.alphaBlend = true;
  13049. break;
  13050. case Engine.ALPHA_MULTIPLY:
  13051. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  13052. this._alphaState.alphaBlend = true;
  13053. break;
  13054. case Engine.ALPHA_MAXIMIZED:
  13055. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  13056. this._alphaState.alphaBlend = true;
  13057. break;
  13058. case Engine.ALPHA_INTERPOLATE:
  13059. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  13060. this._alphaState.alphaBlend = true;
  13061. break;
  13062. case Engine.ALPHA_SCREENMODE:
  13063. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  13064. this._alphaState.alphaBlend = true;
  13065. break;
  13066. }
  13067. if (!noDepthWriteChange) {
  13068. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  13069. }
  13070. this._alphaMode = mode;
  13071. };
  13072. Engine.prototype.getAlphaMode = function () {
  13073. return this._alphaMode;
  13074. };
  13075. // Textures
  13076. Engine.prototype.wipeCaches = function (bruteForce) {
  13077. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  13078. return;
  13079. }
  13080. this._currentEffect = null;
  13081. // 6/8/2017: deltakosh: Should not be required anymore.
  13082. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  13083. if (bruteForce) {
  13084. this.resetTextureCache();
  13085. this._currentProgram = null;
  13086. this._stencilState.reset();
  13087. this._depthCullingState.reset();
  13088. this.setDepthFunctionToLessOrEqual();
  13089. this._alphaState.reset();
  13090. }
  13091. this._resetVertexBufferBinding();
  13092. this._cachedIndexBuffer = null;
  13093. this._cachedEffectForVertexBuffers = null;
  13094. this._unbindVertexArrayObject();
  13095. this.bindIndexBuffer(null);
  13096. };
  13097. /**
  13098. * Set the compressed texture format to use, based on the formats you have, and the formats
  13099. * supported by the hardware / browser.
  13100. *
  13101. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  13102. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  13103. * to API arguments needed to compressed textures. This puts the burden on the container
  13104. * generator to house the arcane code for determining these for current & future formats.
  13105. *
  13106. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  13107. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  13108. *
  13109. * Note: The result of this call is not taken into account when a texture is base64.
  13110. *
  13111. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  13112. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  13113. *
  13114. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  13115. * @returns The extension selected.
  13116. */
  13117. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  13118. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  13119. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  13120. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  13121. return this._textureFormatInUse = this._texturesSupported[i];
  13122. }
  13123. }
  13124. }
  13125. // actively set format to nothing, to allow this to be called more than once
  13126. // and possibly fail the 2nd time
  13127. this._textureFormatInUse = null;
  13128. return null;
  13129. };
  13130. Engine.prototype._createTexture = function () {
  13131. var texture = this._gl.createTexture();
  13132. if (!texture) {
  13133. throw new Error("Unable to create texture");
  13134. }
  13135. return texture;
  13136. };
  13137. /**
  13138. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  13139. * @param {string} urlArg- This contains one of the following:
  13140. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  13141. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  13142. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  13143. *
  13144. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  13145. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  13146. * @param {Scene} scene- Needed for loading to the correct scene.
  13147. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  13148. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  13149. * @param {callback} onError- Optional callback to be called upon failure.
  13150. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  13151. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  13152. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  13153. *
  13154. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  13155. */
  13156. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  13157. var _this = this;
  13158. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13159. if (onLoad === void 0) { onLoad = null; }
  13160. if (onError === void 0) { onError = null; }
  13161. if (buffer === void 0) { buffer = null; }
  13162. if (fallBack === void 0) { fallBack = null; }
  13163. if (format === void 0) { format = null; }
  13164. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  13165. var fromData = url.substr(0, 5) === "data:";
  13166. var fromBlob = url.substr(0, 5) === "blob:";
  13167. var isBase64 = fromData && url.indexOf("base64") !== -1;
  13168. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  13169. // establish the file extension, if possible
  13170. var lastDot = url.lastIndexOf('.');
  13171. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  13172. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  13173. var isTGA = (extension.indexOf(".tga") === 0);
  13174. // determine if a ktx file should be substituted
  13175. var isKTX = false;
  13176. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  13177. url = url.substring(0, lastDot) + this._textureFormatInUse;
  13178. isKTX = true;
  13179. }
  13180. if (scene) {
  13181. scene._addPendingData(texture);
  13182. }
  13183. texture.url = url;
  13184. texture.generateMipMaps = !noMipmap;
  13185. texture.samplingMode = samplingMode;
  13186. texture.invertY = invertY;
  13187. if (!this._doNotHandleContextLost) {
  13188. // Keep a link to the buffer only if we plan to handle context lost
  13189. texture._buffer = buffer;
  13190. }
  13191. var onLoadObserver = null;
  13192. if (onLoad && !fallBack) {
  13193. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  13194. }
  13195. if (!fallBack)
  13196. this._internalTexturesCache.push(texture);
  13197. var onerror = function (message, exception) {
  13198. if (scene) {
  13199. scene._removePendingData(texture);
  13200. }
  13201. if (onLoadObserver) {
  13202. texture.onLoadedObservable.remove(onLoadObserver);
  13203. }
  13204. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  13205. if (isKTX) {
  13206. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13207. }
  13208. else if (BABYLON.Tools.UseFallbackTexture) {
  13209. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13210. }
  13211. if (onError) {
  13212. onError(message || "Unknown error", exception);
  13213. }
  13214. };
  13215. var callback = null;
  13216. // processing for non-image formats
  13217. if (isKTX || isTGA || isDDS) {
  13218. if (isKTX) {
  13219. callback = function (data) {
  13220. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  13221. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  13222. ktx.uploadLevels(_this._gl, !noMipmap);
  13223. return false;
  13224. }, samplingMode);
  13225. };
  13226. }
  13227. else if (isTGA) {
  13228. callback = function (arrayBuffer) {
  13229. var data = new Uint8Array(arrayBuffer);
  13230. var header = BABYLON.TGATools.GetTGAHeader(data);
  13231. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  13232. BABYLON.TGATools.UploadContent(_this._gl, data);
  13233. return false;
  13234. }, samplingMode);
  13235. };
  13236. }
  13237. else if (isDDS) {
  13238. callback = function (data) {
  13239. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13240. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  13241. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  13242. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  13243. return false;
  13244. }, samplingMode);
  13245. };
  13246. }
  13247. if (!buffer) {
  13248. this._loadFile(url, function (data) {
  13249. if (callback) {
  13250. callback(data);
  13251. }
  13252. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  13253. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  13254. });
  13255. }
  13256. else {
  13257. if (callback) {
  13258. callback(buffer);
  13259. }
  13260. }
  13261. // image format processing
  13262. }
  13263. else {
  13264. var onload = function (img) {
  13265. if (fromBlob && !_this._doNotHandleContextLost) {
  13266. // We need to store the image if we need to rebuild the texture
  13267. // in case of a webgl context lost
  13268. texture._buffer = img;
  13269. }
  13270. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  13271. var gl = _this._gl;
  13272. var isPot = (img.width === potWidth && img.height === potHeight);
  13273. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  13274. if (isPot) {
  13275. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13276. return false;
  13277. }
  13278. // Using shaders to rescale because canvas.drawImage is lossy
  13279. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13280. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  13281. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13282. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13283. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13284. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13285. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13286. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  13287. _this._releaseTexture(source);
  13288. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13289. continuationCallback();
  13290. });
  13291. return true;
  13292. }, samplingMode);
  13293. };
  13294. if (!fromData || isBase64)
  13295. if (buffer instanceof HTMLImageElement) {
  13296. onload(buffer);
  13297. }
  13298. else {
  13299. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  13300. }
  13301. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  13302. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  13303. else
  13304. onload(buffer);
  13305. }
  13306. return texture;
  13307. };
  13308. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  13309. var _this = this;
  13310. var rtt = this.createRenderTargetTexture({
  13311. width: destination.width,
  13312. height: destination.height,
  13313. }, {
  13314. generateMipMaps: false,
  13315. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  13316. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  13317. generateDepthBuffer: false,
  13318. generateStencilBuffer: false
  13319. });
  13320. if (!this._rescalePostProcess) {
  13321. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  13322. }
  13323. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  13324. _this._rescalePostProcess.onApply = function (effect) {
  13325. effect._bindTexture("textureSampler", source);
  13326. };
  13327. var hostingScene = scene;
  13328. if (!hostingScene) {
  13329. hostingScene = _this.scenes[_this.scenes.length - 1];
  13330. }
  13331. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  13332. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  13333. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  13334. _this.unBindFramebuffer(rtt);
  13335. _this._releaseTexture(rtt);
  13336. if (onComplete) {
  13337. onComplete();
  13338. }
  13339. });
  13340. };
  13341. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  13342. if (compression === void 0) { compression = null; }
  13343. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13344. if (!texture) {
  13345. return;
  13346. }
  13347. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  13348. var internalFormat = this._getInternalFormat(format);
  13349. var textureType = this._getWebGLTextureType(type);
  13350. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13351. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13352. if (!this._doNotHandleContextLost) {
  13353. texture._bufferView = data;
  13354. texture.format = format;
  13355. texture.type = type;
  13356. texture.invertY = invertY;
  13357. texture._compression = compression;
  13358. }
  13359. if (texture.width % 4 !== 0) {
  13360. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13361. }
  13362. if (compression && data) {
  13363. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  13364. }
  13365. else {
  13366. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  13367. }
  13368. if (texture.generateMipMaps) {
  13369. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13370. }
  13371. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13372. // this.resetTextureCache();
  13373. texture.isReady = true;
  13374. };
  13375. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  13376. if (compression === void 0) { compression = null; }
  13377. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13378. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  13379. texture.baseWidth = width;
  13380. texture.baseHeight = height;
  13381. texture.width = width;
  13382. texture.height = height;
  13383. texture.format = format;
  13384. texture.generateMipMaps = generateMipMaps;
  13385. texture.samplingMode = samplingMode;
  13386. texture.invertY = invertY;
  13387. texture._compression = compression;
  13388. texture.type = type;
  13389. if (!this._doNotHandleContextLost) {
  13390. texture._bufferView = data;
  13391. }
  13392. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13393. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13394. // Filters
  13395. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13396. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13397. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13398. if (generateMipMaps) {
  13399. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13400. }
  13401. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13402. this._internalTexturesCache.push(texture);
  13403. return texture;
  13404. };
  13405. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13406. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13407. texture.baseWidth = width;
  13408. texture.baseHeight = height;
  13409. if (generateMipMaps) {
  13410. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13411. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13412. }
  13413. // this.resetTextureCache();
  13414. texture.width = width;
  13415. texture.height = height;
  13416. texture.isReady = false;
  13417. texture.generateMipMaps = generateMipMaps;
  13418. texture.samplingMode = samplingMode;
  13419. this.updateTextureSamplingMode(samplingMode, texture);
  13420. this._internalTexturesCache.push(texture);
  13421. return texture;
  13422. };
  13423. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13424. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13425. if (texture.isCube) {
  13426. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13427. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13428. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13429. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13430. }
  13431. else if (texture.is3D) {
  13432. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13433. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13434. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13435. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13436. }
  13437. else {
  13438. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13439. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13440. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13441. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13442. }
  13443. texture.samplingMode = samplingMode;
  13444. };
  13445. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13446. if (premulAlpha === void 0) { premulAlpha = false; }
  13447. if (!texture) {
  13448. return;
  13449. }
  13450. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13451. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13452. if (premulAlpha) {
  13453. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13454. }
  13455. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13456. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13457. if (texture.generateMipMaps) {
  13458. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13459. }
  13460. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13461. if (premulAlpha) {
  13462. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13463. }
  13464. texture.isReady = true;
  13465. };
  13466. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13467. if (!texture || texture._isDisabled) {
  13468. return;
  13469. }
  13470. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13471. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13472. try {
  13473. // Testing video texture support
  13474. if (this._videoTextureSupported === undefined) {
  13475. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13476. if (this._gl.getError() !== 0) {
  13477. this._videoTextureSupported = false;
  13478. }
  13479. else {
  13480. this._videoTextureSupported = true;
  13481. }
  13482. }
  13483. // Copy video through the current working canvas if video texture is not supported
  13484. if (!this._videoTextureSupported) {
  13485. if (!texture._workingCanvas) {
  13486. texture._workingCanvas = document.createElement("canvas");
  13487. var context = texture._workingCanvas.getContext("2d");
  13488. if (!context) {
  13489. throw new Error("Unable to get 2d context");
  13490. }
  13491. texture._workingContext = context;
  13492. texture._workingCanvas.width = texture.width;
  13493. texture._workingCanvas.height = texture.height;
  13494. }
  13495. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13496. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13497. }
  13498. else {
  13499. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13500. }
  13501. if (texture.generateMipMaps) {
  13502. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13503. }
  13504. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13505. // this.resetTextureCache();
  13506. texture.isReady = true;
  13507. }
  13508. catch (ex) {
  13509. // Something unexpected
  13510. // Let's disable the texture
  13511. texture._isDisabled = true;
  13512. }
  13513. };
  13514. /**
  13515. * Updates a depth texture Comparison Mode and Function.
  13516. * If the comparison Function is equal to 0, the mode will be set to none.
  13517. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  13518. * @param texture The texture to set the comparison function for
  13519. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  13520. */
  13521. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  13522. if (this.webGLVersion === 1) {
  13523. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  13524. return;
  13525. }
  13526. var gl = this._gl;
  13527. if (texture.isCube) {
  13528. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13529. if (comparisonFunction === 0) {
  13530. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13531. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13532. }
  13533. else {
  13534. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13535. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13536. }
  13537. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13538. }
  13539. else {
  13540. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13541. if (comparisonFunction === 0) {
  13542. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13543. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13544. }
  13545. else {
  13546. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13547. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13548. }
  13549. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13550. }
  13551. texture._comparisonFunction = comparisonFunction;
  13552. };
  13553. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  13554. var width = size.width || size;
  13555. var height = size.height || size;
  13556. internalTexture.baseWidth = width;
  13557. internalTexture.baseHeight = height;
  13558. internalTexture.width = width;
  13559. internalTexture.height = height;
  13560. internalTexture.isReady = true;
  13561. internalTexture.samples = 1;
  13562. internalTexture.generateMipMaps = false;
  13563. internalTexture._generateDepthBuffer = true;
  13564. internalTexture._generateStencilBuffer = generateStencil;
  13565. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13566. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13567. internalTexture._comparisonFunction = comparisonFunction;
  13568. var gl = this._gl;
  13569. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  13570. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  13571. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  13572. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  13573. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13574. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13575. if (comparisonFunction === 0) {
  13576. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13577. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13578. }
  13579. else {
  13580. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13581. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13582. }
  13583. };
  13584. /**
  13585. * Creates a depth stencil texture.
  13586. * This is only available in WebGL 2 or with the depth texture extension available.
  13587. * @param size The size of face edge in the texture.
  13588. * @param options The options defining the texture.
  13589. * @returns The texture
  13590. */
  13591. Engine.prototype.createDepthStencilTexture = function (size, options) {
  13592. if (options.isCube) {
  13593. var width = size.width || size;
  13594. return this._createDepthStencilCubeTexture(width, options);
  13595. }
  13596. else {
  13597. return this._createDepthStencilTexture(size, options);
  13598. }
  13599. };
  13600. /**
  13601. * Creates a depth stencil texture.
  13602. * This is only available in WebGL 2 or with the depth texture extension available.
  13603. * @param size The size of face edge in the texture.
  13604. * @param options The options defining the texture.
  13605. * @returns The texture
  13606. */
  13607. Engine.prototype._createDepthStencilTexture = function (size, options) {
  13608. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  13609. if (!this._caps.depthTextureExtension) {
  13610. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  13611. return internalTexture;
  13612. }
  13613. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13614. var gl = this._gl;
  13615. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  13616. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13617. if (this.webGLVersion > 1) {
  13618. if (internalOptions.generateStencil) {
  13619. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13620. }
  13621. else {
  13622. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13623. }
  13624. }
  13625. else {
  13626. if (internalOptions.generateStencil) {
  13627. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13628. }
  13629. else {
  13630. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13631. }
  13632. }
  13633. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13634. return internalTexture;
  13635. };
  13636. /**
  13637. * Creates a depth stencil cube texture.
  13638. * This is only available in WebGL 2.
  13639. * @param size The size of face edge in the cube texture.
  13640. * @param options The options defining the cube texture.
  13641. * @returns The cube texture
  13642. */
  13643. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  13644. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  13645. internalTexture.isCube = true;
  13646. if (this.webGLVersion === 1) {
  13647. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  13648. return internalTexture;
  13649. }
  13650. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13651. var gl = this._gl;
  13652. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  13653. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13654. // Create the depth/stencil buffer
  13655. for (var face = 0; face < 6; face++) {
  13656. if (internalOptions.generateStencil) {
  13657. 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);
  13658. }
  13659. else {
  13660. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13661. }
  13662. }
  13663. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13664. return internalTexture;
  13665. };
  13666. /**
  13667. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  13668. * @param renderTarget The render target to set the frame buffer for
  13669. */
  13670. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  13671. // Create the framebuffer
  13672. var internalTexture = renderTarget.getInternalTexture();
  13673. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  13674. return;
  13675. }
  13676. var gl = this._gl;
  13677. var depthStencilTexture = renderTarget.depthStencilTexture;
  13678. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  13679. if (depthStencilTexture.isCube) {
  13680. if (depthStencilTexture._generateStencilBuffer) {
  13681. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  13682. }
  13683. else {
  13684. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  13685. }
  13686. }
  13687. else {
  13688. if (depthStencilTexture._generateStencilBuffer) {
  13689. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  13690. }
  13691. else {
  13692. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  13693. }
  13694. }
  13695. this.bindUnboundFramebuffer(null);
  13696. };
  13697. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13698. var fullOptions = new RenderTargetCreationOptions();
  13699. if (options !== undefined && typeof options === "object") {
  13700. fullOptions.generateMipMaps = options.generateMipMaps;
  13701. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13702. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13703. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13704. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13705. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  13706. }
  13707. else {
  13708. fullOptions.generateMipMaps = options;
  13709. fullOptions.generateDepthBuffer = true;
  13710. fullOptions.generateStencilBuffer = false;
  13711. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13712. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13713. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  13714. }
  13715. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13716. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13717. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13718. }
  13719. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13720. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13721. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13722. }
  13723. var gl = this._gl;
  13724. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13725. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13726. var width = size.width || size;
  13727. var height = size.height || size;
  13728. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13729. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13730. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13731. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13732. }
  13733. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13734. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13735. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13736. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13737. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  13738. // Create the framebuffer
  13739. var framebuffer = gl.createFramebuffer();
  13740. this.bindUnboundFramebuffer(framebuffer);
  13741. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13742. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13743. if (fullOptions.generateMipMaps) {
  13744. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13745. }
  13746. // Unbind
  13747. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13748. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13749. this.bindUnboundFramebuffer(null);
  13750. texture._framebuffer = framebuffer;
  13751. texture.baseWidth = width;
  13752. texture.baseHeight = height;
  13753. texture.width = width;
  13754. texture.height = height;
  13755. texture.isReady = true;
  13756. texture.samples = 1;
  13757. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13758. texture.samplingMode = fullOptions.samplingMode;
  13759. texture.type = fullOptions.type;
  13760. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13761. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13762. // this.resetTextureCache();
  13763. this._internalTexturesCache.push(texture);
  13764. return texture;
  13765. };
  13766. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13767. var generateMipMaps = false;
  13768. var generateDepthBuffer = true;
  13769. var generateStencilBuffer = false;
  13770. var generateDepthTexture = false;
  13771. var textureCount = 1;
  13772. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13773. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13774. var types = [], samplingModes = [];
  13775. if (options !== undefined) {
  13776. generateMipMaps = options.generateMipMaps;
  13777. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13778. generateStencilBuffer = options.generateStencilBuffer;
  13779. generateDepthTexture = options.generateDepthTexture;
  13780. textureCount = options.textureCount || 1;
  13781. if (options.types) {
  13782. types = options.types;
  13783. }
  13784. if (options.samplingModes) {
  13785. samplingModes = options.samplingModes;
  13786. }
  13787. }
  13788. var gl = this._gl;
  13789. // Create the framebuffer
  13790. var framebuffer = gl.createFramebuffer();
  13791. this.bindUnboundFramebuffer(framebuffer);
  13792. var width = size.width || size;
  13793. var height = size.height || size;
  13794. var textures = [];
  13795. var attachments = [];
  13796. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13797. for (var i = 0; i < textureCount; i++) {
  13798. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13799. var type = types[i] || defaultType;
  13800. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13801. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13802. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13803. }
  13804. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13805. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13806. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13807. }
  13808. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13809. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13810. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13811. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13812. }
  13813. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13814. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13815. textures.push(texture);
  13816. attachments.push(attachment);
  13817. gl.activeTexture(gl["TEXTURE" + i]);
  13818. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13819. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13820. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13821. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13822. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13823. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13824. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13825. if (generateMipMaps) {
  13826. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13827. }
  13828. // Unbind
  13829. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13830. texture._framebuffer = framebuffer;
  13831. texture._depthStencilBuffer = depthStencilBuffer;
  13832. texture.baseWidth = width;
  13833. texture.baseHeight = height;
  13834. texture.width = width;
  13835. texture.height = height;
  13836. texture.isReady = true;
  13837. texture.samples = 1;
  13838. texture.generateMipMaps = generateMipMaps;
  13839. texture.samplingMode = samplingMode;
  13840. texture.type = type;
  13841. texture._generateDepthBuffer = generateDepthBuffer;
  13842. texture._generateStencilBuffer = generateStencilBuffer;
  13843. texture._attachments = attachments;
  13844. this._internalTexturesCache.push(texture);
  13845. }
  13846. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13847. // Depth texture
  13848. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13849. gl.activeTexture(gl.TEXTURE0);
  13850. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13851. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13852. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13853. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13854. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13855. 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);
  13856. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13857. depthTexture._framebuffer = framebuffer;
  13858. depthTexture.baseWidth = width;
  13859. depthTexture.baseHeight = height;
  13860. depthTexture.width = width;
  13861. depthTexture.height = height;
  13862. depthTexture.isReady = true;
  13863. depthTexture.samples = 1;
  13864. depthTexture.generateMipMaps = generateMipMaps;
  13865. depthTexture.samplingMode = gl.NEAREST;
  13866. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13867. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13868. textures.push(depthTexture);
  13869. this._internalTexturesCache.push(depthTexture);
  13870. }
  13871. gl.drawBuffers(attachments);
  13872. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13873. this.bindUnboundFramebuffer(null);
  13874. this.resetTextureCache();
  13875. return textures;
  13876. };
  13877. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13878. if (samples === void 0) { samples = 1; }
  13879. var depthStencilBuffer = null;
  13880. var gl = this._gl;
  13881. // Create the depth/stencil buffer
  13882. if (generateStencilBuffer) {
  13883. depthStencilBuffer = gl.createRenderbuffer();
  13884. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13885. if (samples > 1) {
  13886. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13887. }
  13888. else {
  13889. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13890. }
  13891. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13892. }
  13893. else if (generateDepthBuffer) {
  13894. depthStencilBuffer = gl.createRenderbuffer();
  13895. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13896. if (samples > 1) {
  13897. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13898. }
  13899. else {
  13900. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13901. }
  13902. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13903. }
  13904. return depthStencilBuffer;
  13905. };
  13906. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13907. if (this.webGLVersion < 2 || !texture) {
  13908. return 1;
  13909. }
  13910. if (texture.samples === samples) {
  13911. return samples;
  13912. }
  13913. var gl = this._gl;
  13914. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13915. // Dispose previous render buffers
  13916. if (texture._depthStencilBuffer) {
  13917. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13918. texture._depthStencilBuffer = null;
  13919. }
  13920. if (texture._MSAAFramebuffer) {
  13921. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13922. texture._MSAAFramebuffer = null;
  13923. }
  13924. if (texture._MSAARenderBuffer) {
  13925. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13926. texture._MSAARenderBuffer = null;
  13927. }
  13928. if (samples > 1) {
  13929. var framebuffer = gl.createFramebuffer();
  13930. if (!framebuffer) {
  13931. throw new Error("Unable to create multi sampled framebuffer");
  13932. }
  13933. texture._MSAAFramebuffer = framebuffer;
  13934. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13935. var colorRenderbuffer = gl.createRenderbuffer();
  13936. if (!colorRenderbuffer) {
  13937. throw new Error("Unable to create multi sampled framebuffer");
  13938. }
  13939. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13940. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13941. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13942. texture._MSAARenderBuffer = colorRenderbuffer;
  13943. }
  13944. else {
  13945. this.bindUnboundFramebuffer(texture._framebuffer);
  13946. }
  13947. texture.samples = samples;
  13948. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13949. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13950. this.bindUnboundFramebuffer(null);
  13951. return samples;
  13952. };
  13953. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13954. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13955. return 1;
  13956. }
  13957. if (textures[0].samples === samples) {
  13958. return samples;
  13959. }
  13960. var gl = this._gl;
  13961. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13962. // Dispose previous render buffers
  13963. if (textures[0]._depthStencilBuffer) {
  13964. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13965. textures[0]._depthStencilBuffer = null;
  13966. }
  13967. if (textures[0]._MSAAFramebuffer) {
  13968. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13969. textures[0]._MSAAFramebuffer = null;
  13970. }
  13971. for (var i = 0; i < textures.length; i++) {
  13972. if (textures[i]._MSAARenderBuffer) {
  13973. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13974. textures[i]._MSAARenderBuffer = null;
  13975. }
  13976. }
  13977. if (samples > 1) {
  13978. var framebuffer = gl.createFramebuffer();
  13979. if (!framebuffer) {
  13980. throw new Error("Unable to create multi sampled framebuffer");
  13981. }
  13982. this.bindUnboundFramebuffer(framebuffer);
  13983. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13984. var attachments = [];
  13985. for (var i = 0; i < textures.length; i++) {
  13986. var texture = textures[i];
  13987. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13988. var colorRenderbuffer = gl.createRenderbuffer();
  13989. if (!colorRenderbuffer) {
  13990. throw new Error("Unable to create multi sampled framebuffer");
  13991. }
  13992. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13993. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13994. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13995. texture._MSAAFramebuffer = framebuffer;
  13996. texture._MSAARenderBuffer = colorRenderbuffer;
  13997. texture.samples = samples;
  13998. texture._depthStencilBuffer = depthStencilBuffer;
  13999. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14000. attachments.push(attachment);
  14001. }
  14002. gl.drawBuffers(attachments);
  14003. }
  14004. else {
  14005. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  14006. }
  14007. this.bindUnboundFramebuffer(null);
  14008. return samples;
  14009. };
  14010. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  14011. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  14012. };
  14013. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  14014. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  14015. };
  14016. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  14017. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  14018. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  14019. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  14020. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  14021. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14022. }
  14023. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  14024. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  14025. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14026. }
  14027. var gl = this._gl;
  14028. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  14029. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14030. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  14031. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  14032. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14033. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  14034. }
  14035. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14036. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14037. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14038. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14039. for (var face = 0; face < 6; face++) {
  14040. 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);
  14041. }
  14042. // Create the framebuffer
  14043. var framebuffer = gl.createFramebuffer();
  14044. this.bindUnboundFramebuffer(framebuffer);
  14045. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  14046. // MipMaps
  14047. if (fullOptions.generateMipMaps) {
  14048. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14049. }
  14050. // Unbind
  14051. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14052. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14053. this.bindUnboundFramebuffer(null);
  14054. texture._framebuffer = framebuffer;
  14055. texture.width = size;
  14056. texture.height = size;
  14057. texture.isReady = true;
  14058. texture.isCube = true;
  14059. texture.samples = 1;
  14060. texture.generateMipMaps = fullOptions.generateMipMaps;
  14061. texture.samplingMode = fullOptions.samplingMode;
  14062. texture.type = fullOptions.type;
  14063. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  14064. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  14065. this._internalTexturesCache.push(texture);
  14066. return texture;
  14067. };
  14068. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  14069. var _this = this;
  14070. if (onLoad === void 0) { onLoad = null; }
  14071. if (onError === void 0) { onError = null; }
  14072. if (forcedExtension === void 0) { forcedExtension = null; }
  14073. var callback = function (loadData) {
  14074. if (!loadData) {
  14075. if (onLoad) {
  14076. onLoad(null);
  14077. }
  14078. return;
  14079. }
  14080. var texture = loadData.texture;
  14081. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  14082. texture._lodGenerationScale = scale;
  14083. texture._lodGenerationOffset = offset;
  14084. if (_this._caps.textureLOD) {
  14085. // Do not add extra process if texture lod is supported.
  14086. if (onLoad) {
  14087. onLoad(texture);
  14088. }
  14089. return;
  14090. }
  14091. var mipSlices = 3;
  14092. var gl = _this._gl;
  14093. var width = loadData.width;
  14094. if (!width) {
  14095. return;
  14096. }
  14097. var textures = [];
  14098. for (var i = 0; i < mipSlices; i++) {
  14099. //compute LOD from even spacing in smoothness (matching shader calculation)
  14100. var smoothness = i / (mipSlices - 1);
  14101. var roughness = 1 - smoothness;
  14102. var minLODIndex = offset; // roughness = 0
  14103. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  14104. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  14105. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  14106. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14107. glTextureFromLod.isCube = true;
  14108. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  14109. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14110. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14111. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14112. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14113. if (loadData.isDDS) {
  14114. var info = loadData.info;
  14115. var data = loadData.data;
  14116. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14117. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  14118. }
  14119. else {
  14120. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  14121. }
  14122. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14123. // Wrap in a base texture for easy binding.
  14124. var lodTexture = new BABYLON.BaseTexture(scene);
  14125. lodTexture.isCube = true;
  14126. lodTexture._texture = glTextureFromLod;
  14127. glTextureFromLod.isReady = true;
  14128. textures.push(lodTexture);
  14129. }
  14130. texture._lodTextureHigh = textures[2];
  14131. texture._lodTextureMid = textures[1];
  14132. texture._lodTextureLow = textures[0];
  14133. if (onLoad) {
  14134. onLoad(texture);
  14135. }
  14136. };
  14137. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  14138. };
  14139. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  14140. var _this = this;
  14141. if (onLoad === void 0) { onLoad = null; }
  14142. if (onError === void 0) { onError = null; }
  14143. if (forcedExtension === void 0) { forcedExtension = null; }
  14144. var gl = this._gl;
  14145. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  14146. texture.isCube = true;
  14147. texture.url = rootUrl;
  14148. texture.generateMipMaps = !noMipmap;
  14149. if (!this._doNotHandleContextLost) {
  14150. texture._extension = forcedExtension;
  14151. texture._files = files;
  14152. }
  14153. var isKTX = false;
  14154. var isDDS = false;
  14155. var lastDot = rootUrl.lastIndexOf('.');
  14156. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  14157. if (this._textureFormatInUse) {
  14158. extension = this._textureFormatInUse;
  14159. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  14160. isKTX = true;
  14161. }
  14162. else {
  14163. isDDS = (extension === ".dds");
  14164. }
  14165. var onerror = function (request, exception) {
  14166. if (onError && request) {
  14167. onError(request.status + " " + request.statusText, exception);
  14168. }
  14169. };
  14170. if (isKTX) {
  14171. this._loadFile(rootUrl, function (data) {
  14172. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  14173. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  14174. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14175. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  14176. ktx.uploadLevels(_this._gl, !noMipmap);
  14177. _this.setCubeMapTextureParams(gl, loadMipmap);
  14178. texture.width = ktx.pixelWidth;
  14179. texture.height = ktx.pixelHeight;
  14180. texture.isReady = true;
  14181. }, undefined, undefined, true, onerror);
  14182. }
  14183. else if (isDDS) {
  14184. if (files && files.length === 6) {
  14185. this._cascadeLoadFiles(scene, function (imgs) {
  14186. var info;
  14187. var loadMipmap = false;
  14188. var width = 0;
  14189. for (var index = 0; index < imgs.length; index++) {
  14190. var data = imgs[index];
  14191. info = BABYLON.DDSTools.GetDDSInfo(data);
  14192. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14193. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14194. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14195. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  14196. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14197. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14198. }
  14199. texture.width = info.width;
  14200. texture.height = info.height;
  14201. texture.type = info.textureType;
  14202. width = info.width;
  14203. }
  14204. _this.setCubeMapTextureParams(gl, loadMipmap);
  14205. texture.isReady = true;
  14206. if (onLoad) {
  14207. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  14208. }
  14209. }, files, onError);
  14210. }
  14211. else {
  14212. this._loadFile(rootUrl, function (data) {
  14213. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14214. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14215. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14216. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14217. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  14218. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14219. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14220. }
  14221. _this.setCubeMapTextureParams(gl, loadMipmap);
  14222. texture.width = info.width;
  14223. texture.height = info.height;
  14224. texture.isReady = true;
  14225. texture.type = info.textureType;
  14226. if (onLoad) {
  14227. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  14228. }
  14229. }, undefined, undefined, true, onerror);
  14230. }
  14231. }
  14232. else {
  14233. if (!files) {
  14234. throw new Error("Cannot load cubemap because files were not defined");
  14235. }
  14236. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  14237. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  14238. var height = width;
  14239. _this._prepareWorkingCanvas();
  14240. if (!_this._workingCanvas || !_this._workingContext) {
  14241. return;
  14242. }
  14243. _this._workingCanvas.width = width;
  14244. _this._workingCanvas.height = height;
  14245. var faces = [
  14246. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  14247. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  14248. ];
  14249. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14250. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14251. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  14252. for (var index = 0; index < faces.length; index++) {
  14253. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  14254. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14255. }
  14256. if (!noMipmap) {
  14257. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14258. }
  14259. _this.setCubeMapTextureParams(gl, !noMipmap);
  14260. texture.width = width;
  14261. texture.height = height;
  14262. texture.isReady = true;
  14263. if (format) {
  14264. texture.format = format;
  14265. }
  14266. texture.onLoadedObservable.notifyObservers(texture);
  14267. texture.onLoadedObservable.clear();
  14268. if (onLoad) {
  14269. onLoad();
  14270. }
  14271. }, files, onError);
  14272. }
  14273. this._internalTexturesCache.push(texture);
  14274. return texture;
  14275. };
  14276. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  14277. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14278. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  14279. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14280. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14281. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14282. // this.resetTextureCache();
  14283. };
  14284. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  14285. if (compression === void 0) { compression = null; }
  14286. if (level === void 0) { level = 0; }
  14287. texture._bufferViewArray = data;
  14288. texture.format = format;
  14289. texture.type = type;
  14290. texture.invertY = invertY;
  14291. texture._compression = compression;
  14292. var gl = this._gl;
  14293. var textureType = this._getWebGLTextureType(type);
  14294. var internalFormat = this._getInternalFormat(format);
  14295. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  14296. var needConversion = false;
  14297. if (internalFormat === gl.RGB) {
  14298. internalFormat = gl.RGBA;
  14299. needConversion = true;
  14300. }
  14301. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14302. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14303. if (texture.width % 4 !== 0) {
  14304. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  14305. }
  14306. // Data are known to be in +X +Y +Z -X -Y -Z
  14307. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14308. var faceData = data[faceIndex];
  14309. if (compression) {
  14310. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  14311. }
  14312. else {
  14313. if (needConversion) {
  14314. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  14315. }
  14316. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  14317. }
  14318. }
  14319. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14320. if (isPot && texture.generateMipMaps && level === 0) {
  14321. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14322. }
  14323. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14324. // this.resetTextureCache();
  14325. texture.isReady = true;
  14326. };
  14327. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  14328. if (compression === void 0) { compression = null; }
  14329. var gl = this._gl;
  14330. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  14331. texture.isCube = true;
  14332. texture.generateMipMaps = generateMipMaps;
  14333. texture.format = format;
  14334. texture.type = type;
  14335. if (!this._doNotHandleContextLost) {
  14336. texture._bufferViewArray = data;
  14337. }
  14338. var textureType = this._getWebGLTextureType(type);
  14339. var internalFormat = this._getInternalFormat(format);
  14340. if (internalFormat === gl.RGB) {
  14341. internalFormat = gl.RGBA;
  14342. }
  14343. var width = size;
  14344. var height = width;
  14345. texture.width = width;
  14346. texture.height = height;
  14347. // Double check on POT to generate Mips.
  14348. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14349. if (!isPot) {
  14350. generateMipMaps = false;
  14351. }
  14352. // Upload data if needed. The texture won't be ready until then.
  14353. if (data) {
  14354. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  14355. }
  14356. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14357. // Filters
  14358. if (data && generateMipMaps) {
  14359. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14360. }
  14361. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  14362. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14363. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14364. }
  14365. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  14366. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14367. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14368. }
  14369. else {
  14370. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14371. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14372. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14373. }
  14374. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14375. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14376. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14377. return texture;
  14378. };
  14379. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  14380. var _this = this;
  14381. if (onLoad === void 0) { onLoad = null; }
  14382. if (onError === void 0) { onError = null; }
  14383. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14384. if (invertY === void 0) { invertY = false; }
  14385. var gl = this._gl;
  14386. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  14387. scene._addPendingData(texture);
  14388. texture.url = url;
  14389. this._internalTexturesCache.push(texture);
  14390. var onerror = function (request, exception) {
  14391. scene._removePendingData(texture);
  14392. if (onError && request) {
  14393. onError(request.status + " " + request.statusText, exception);
  14394. }
  14395. };
  14396. var internalCallback = function (data) {
  14397. var width = texture.width;
  14398. var faceDataArrays = callback(data);
  14399. if (!faceDataArrays) {
  14400. return;
  14401. }
  14402. if (mipmmapGenerator) {
  14403. var textureType = _this._getWebGLTextureType(type);
  14404. var internalFormat = _this._getInternalFormat(format);
  14405. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  14406. var needConversion = false;
  14407. if (internalFormat === gl.RGB) {
  14408. internalFormat = gl.RGBA;
  14409. needConversion = true;
  14410. }
  14411. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14412. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14413. var mipData = mipmmapGenerator(faceDataArrays);
  14414. for (var level = 0; level < mipData.length; level++) {
  14415. var mipSize = width >> level;
  14416. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14417. var mipFaceData = mipData[level][faceIndex];
  14418. if (needConversion) {
  14419. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  14420. }
  14421. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  14422. }
  14423. }
  14424. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14425. }
  14426. else {
  14427. texture.generateMipMaps = !noMipmap;
  14428. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  14429. }
  14430. texture.isReady = true;
  14431. // this.resetTextureCache();
  14432. scene._removePendingData(texture);
  14433. if (onLoad) {
  14434. onLoad();
  14435. }
  14436. };
  14437. this._loadFile(url, function (data) {
  14438. internalCallback(data);
  14439. }, undefined, scene.database, true, onerror);
  14440. return texture;
  14441. };
  14442. ;
  14443. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  14444. if (compression === void 0) { compression = null; }
  14445. var internalFormat = this._getInternalFormat(format);
  14446. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14447. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14448. if (!this._doNotHandleContextLost) {
  14449. texture._bufferView = data;
  14450. texture.format = format;
  14451. texture.invertY = invertY;
  14452. texture._compression = compression;
  14453. }
  14454. if (texture.width % 4 !== 0) {
  14455. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14456. }
  14457. if (compression && data) {
  14458. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  14459. }
  14460. else {
  14461. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  14462. }
  14463. if (texture.generateMipMaps) {
  14464. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14465. }
  14466. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14467. // this.resetTextureCache();
  14468. texture.isReady = true;
  14469. };
  14470. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  14471. if (compression === void 0) { compression = null; }
  14472. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  14473. texture.baseWidth = width;
  14474. texture.baseHeight = height;
  14475. texture.baseDepth = depth;
  14476. texture.width = width;
  14477. texture.height = height;
  14478. texture.depth = depth;
  14479. texture.format = format;
  14480. texture.generateMipMaps = generateMipMaps;
  14481. texture.samplingMode = samplingMode;
  14482. texture.is3D = true;
  14483. if (!this._doNotHandleContextLost) {
  14484. texture._bufferView = data;
  14485. }
  14486. this.updateRawTexture3D(texture, data, format, invertY, compression);
  14487. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14488. // Filters
  14489. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14490. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14491. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14492. if (generateMipMaps) {
  14493. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14494. }
  14495. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14496. this._internalTexturesCache.push(texture);
  14497. return texture;
  14498. };
  14499. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  14500. var gl = this._gl;
  14501. if (!gl) {
  14502. return;
  14503. }
  14504. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  14505. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14506. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14507. if (!noMipmap && !isCompressed) {
  14508. gl.generateMipmap(gl.TEXTURE_2D);
  14509. }
  14510. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14511. // this.resetTextureCache();
  14512. if (scene) {
  14513. scene._removePendingData(texture);
  14514. }
  14515. texture.onLoadedObservable.notifyObservers(texture);
  14516. texture.onLoadedObservable.clear();
  14517. };
  14518. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  14519. var _this = this;
  14520. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14521. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  14522. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  14523. var gl = this._gl;
  14524. if (!gl) {
  14525. return;
  14526. }
  14527. if (!texture._webGLTexture) {
  14528. // this.resetTextureCache();
  14529. if (scene) {
  14530. scene._removePendingData(texture);
  14531. }
  14532. return;
  14533. }
  14534. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14535. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14536. texture.baseWidth = width;
  14537. texture.baseHeight = height;
  14538. texture.width = potWidth;
  14539. texture.height = potHeight;
  14540. texture.isReady = true;
  14541. if (processFunction(potWidth, potHeight, function () {
  14542. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14543. })) {
  14544. // Returning as texture needs extra async steps
  14545. return;
  14546. }
  14547. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14548. };
  14549. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  14550. // Create new RGBA data container.
  14551. var rgbaData;
  14552. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  14553. rgbaData = new Float32Array(width * height * 4);
  14554. }
  14555. else {
  14556. rgbaData = new Uint32Array(width * height * 4);
  14557. }
  14558. // Convert each pixel.
  14559. for (var x = 0; x < width; x++) {
  14560. for (var y = 0; y < height; y++) {
  14561. var index = (y * width + x) * 3;
  14562. var newIndex = (y * width + x) * 4;
  14563. // Map Old Value to new value.
  14564. rgbaData[newIndex + 0] = rgbData[index + 0];
  14565. rgbaData[newIndex + 1] = rgbData[index + 1];
  14566. rgbaData[newIndex + 2] = rgbData[index + 2];
  14567. // Add fully opaque alpha channel.
  14568. rgbaData[newIndex + 3] = 1;
  14569. }
  14570. }
  14571. return rgbaData;
  14572. };
  14573. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14574. var gl = this._gl;
  14575. if (texture._framebuffer) {
  14576. gl.deleteFramebuffer(texture._framebuffer);
  14577. texture._framebuffer = null;
  14578. }
  14579. if (texture._depthStencilBuffer) {
  14580. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14581. texture._depthStencilBuffer = null;
  14582. }
  14583. if (texture._MSAAFramebuffer) {
  14584. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14585. texture._MSAAFramebuffer = null;
  14586. }
  14587. if (texture._MSAARenderBuffer) {
  14588. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14589. texture._MSAARenderBuffer = null;
  14590. }
  14591. };
  14592. Engine.prototype._releaseTexture = function (texture) {
  14593. var gl = this._gl;
  14594. this._releaseFramebufferObjects(texture);
  14595. gl.deleteTexture(texture._webGLTexture);
  14596. // Unbind channels
  14597. this.unbindAllTextures();
  14598. var index = this._internalTexturesCache.indexOf(texture);
  14599. if (index !== -1) {
  14600. this._internalTexturesCache.splice(index, 1);
  14601. }
  14602. // Integrated fixed lod samplers.
  14603. if (texture._lodTextureHigh) {
  14604. texture._lodTextureHigh.dispose();
  14605. }
  14606. if (texture._lodTextureMid) {
  14607. texture._lodTextureMid.dispose();
  14608. }
  14609. if (texture._lodTextureLow) {
  14610. texture._lodTextureLow.dispose();
  14611. }
  14612. // Set output texture of post process to null if the texture has been released/disposed
  14613. this.scenes.forEach(function (scene) {
  14614. scene.postProcesses.forEach(function (postProcess) {
  14615. if (postProcess._outputTexture == texture) {
  14616. postProcess._outputTexture = null;
  14617. }
  14618. });
  14619. scene.cameras.forEach(function (camera) {
  14620. camera._postProcesses.forEach(function (postProcess) {
  14621. if (postProcess) {
  14622. if (postProcess._outputTexture == texture) {
  14623. postProcess._outputTexture = null;
  14624. }
  14625. }
  14626. });
  14627. });
  14628. });
  14629. };
  14630. Engine.prototype.setProgram = function (program) {
  14631. if (this._currentProgram !== program) {
  14632. this._gl.useProgram(program);
  14633. this._currentProgram = program;
  14634. }
  14635. };
  14636. Engine.prototype.bindSamplers = function (effect) {
  14637. this.setProgram(effect.getProgram());
  14638. var samplers = effect.getSamplers();
  14639. for (var index = 0; index < samplers.length; index++) {
  14640. var uniform = effect.getUniform(samplers[index]);
  14641. if (uniform) {
  14642. this._boundUniforms[index] = uniform;
  14643. }
  14644. }
  14645. this._currentEffect = null;
  14646. };
  14647. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14648. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14649. return;
  14650. }
  14651. // Remove
  14652. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14653. // Bind last to it
  14654. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14655. // Bind to dummy
  14656. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14657. };
  14658. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14659. if (!internalTexture) {
  14660. return -1;
  14661. }
  14662. internalTexture._initialSlot = channel;
  14663. if (this.disableTextureBindingOptimization) {
  14664. if (channel !== internalTexture._designatedSlot) {
  14665. this._textureCollisions.addCount(1, false);
  14666. }
  14667. }
  14668. else {
  14669. if (channel !== internalTexture._designatedSlot) {
  14670. if (internalTexture._designatedSlot > -1) {
  14671. return internalTexture._designatedSlot;
  14672. }
  14673. else {
  14674. // No slot for this texture, let's pick a new one (if we find a free slot)
  14675. if (this._nextFreeTextureSlots.length) {
  14676. return this._nextFreeTextureSlots[0];
  14677. }
  14678. // We need to recycle the oldest bound texture, sorry.
  14679. this._textureCollisions.addCount(1, false);
  14680. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14681. }
  14682. }
  14683. }
  14684. return channel;
  14685. };
  14686. Engine.prototype._linkTrackers = function (previous, next) {
  14687. previous.next = next;
  14688. next.previous = previous;
  14689. };
  14690. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14691. var currentSlot = internalTexture._designatedSlot;
  14692. if (currentSlot === -1) {
  14693. return -1;
  14694. }
  14695. internalTexture._designatedSlot = -1;
  14696. if (this.disableTextureBindingOptimization) {
  14697. return -1;
  14698. }
  14699. // Remove from bound list
  14700. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14701. // Free the slot
  14702. this._boundTexturesCache[currentSlot] = null;
  14703. this._nextFreeTextureSlots.push(currentSlot);
  14704. return currentSlot;
  14705. };
  14706. Engine.prototype._activateCurrentTexture = function () {
  14707. if (this._currentTextureChannel !== this._activeChannel) {
  14708. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14709. this._currentTextureChannel = this._activeChannel;
  14710. }
  14711. };
  14712. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14713. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14714. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14715. this._activeChannel = texture._designatedSlot;
  14716. }
  14717. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14718. var isTextureForRendering = texture && texture._initialSlot > -1;
  14719. if (currentTextureBound !== texture) {
  14720. if (currentTextureBound) {
  14721. this._removeDesignatedSlot(currentTextureBound);
  14722. }
  14723. this._activateCurrentTexture();
  14724. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14725. this._boundTexturesCache[this._activeChannel] = texture;
  14726. if (texture) {
  14727. if (!this.disableTextureBindingOptimization) {
  14728. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14729. if (slotIndex > -1) {
  14730. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14731. }
  14732. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14733. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14734. }
  14735. texture._designatedSlot = this._activeChannel;
  14736. }
  14737. }
  14738. else if (forTextureDataUpdate) {
  14739. this._activateCurrentTexture();
  14740. }
  14741. if (isTextureForRendering && !forTextureDataUpdate) {
  14742. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14743. }
  14744. };
  14745. Engine.prototype._bindTexture = function (channel, texture) {
  14746. if (channel < 0) {
  14747. return;
  14748. }
  14749. if (texture) {
  14750. channel = this._getCorrectTextureChannel(channel, texture);
  14751. }
  14752. this._activeChannel = channel;
  14753. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14754. };
  14755. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14756. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14757. };
  14758. /**
  14759. * Binds the output of the passed in post process to the texture channel specified
  14760. * @param channel The channel the texture should be bound to
  14761. * @param postProcess The post process which's output should be bound
  14762. */
  14763. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  14764. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  14765. };
  14766. Engine.prototype.unbindAllTextures = function () {
  14767. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14768. this._activeChannel = channel;
  14769. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14770. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14771. if (this.webGLVersion > 1) {
  14772. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14773. }
  14774. }
  14775. };
  14776. /**
  14777. * Sets a texture to the according uniform.
  14778. * @param channel The texture channel
  14779. * @param uniform The uniform to set
  14780. * @param texture The texture to apply
  14781. */
  14782. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14783. if (channel < 0) {
  14784. return;
  14785. }
  14786. if (uniform) {
  14787. this._boundUniforms[channel] = uniform;
  14788. }
  14789. this._setTexture(channel, texture);
  14790. };
  14791. /**
  14792. * Sets a depth stencil texture from a render target to the according uniform.
  14793. * @param channel The texture channel
  14794. * @param uniform The uniform to set
  14795. * @param texture The render target texture containing the depth stencil texture to apply
  14796. */
  14797. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  14798. if (channel < 0) {
  14799. return;
  14800. }
  14801. if (uniform) {
  14802. this._boundUniforms[channel] = uniform;
  14803. }
  14804. if (!texture || !texture.depthStencilTexture) {
  14805. this._setTexture(channel, null);
  14806. }
  14807. else {
  14808. this._setTexture(channel, texture, false, true);
  14809. }
  14810. };
  14811. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14812. var uniform = this._boundUniforms[sourceSlot];
  14813. if (uniform._currentState === destination) {
  14814. return;
  14815. }
  14816. this._gl.uniform1i(uniform, destination);
  14817. uniform._currentState = destination;
  14818. };
  14819. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  14820. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14821. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  14822. // Not ready?
  14823. if (!texture) {
  14824. if (this._boundTexturesCache[channel] != null) {
  14825. this._activeChannel = channel;
  14826. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14827. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14828. if (this.webGLVersion > 1) {
  14829. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14830. }
  14831. }
  14832. return false;
  14833. }
  14834. // Video
  14835. if (texture.video) {
  14836. this._activeChannel = channel;
  14837. texture.update();
  14838. }
  14839. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14840. texture.delayLoad();
  14841. return false;
  14842. }
  14843. var internalTexture;
  14844. if (depthStencilTexture) {
  14845. internalTexture = texture.depthStencilTexture;
  14846. }
  14847. else if (texture.isReady()) {
  14848. internalTexture = texture.getInternalTexture();
  14849. }
  14850. else if (texture.isCube) {
  14851. internalTexture = this.emptyCubeTexture;
  14852. }
  14853. else if (texture.is3D) {
  14854. internalTexture = this.emptyTexture3D;
  14855. }
  14856. else {
  14857. internalTexture = this.emptyTexture;
  14858. }
  14859. if (!isPartOfTextureArray) {
  14860. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14861. }
  14862. if (this._boundTexturesCache[channel] === internalTexture) {
  14863. this._moveBoundTextureOnTop(internalTexture);
  14864. if (!isPartOfTextureArray) {
  14865. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14866. }
  14867. return false;
  14868. }
  14869. this._activeChannel = channel;
  14870. if (internalTexture && internalTexture.is3D) {
  14871. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14872. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14873. internalTexture._cachedWrapU = texture.wrapU;
  14874. switch (texture.wrapU) {
  14875. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14876. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14877. break;
  14878. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14879. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14880. break;
  14881. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14882. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14883. break;
  14884. }
  14885. }
  14886. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14887. internalTexture._cachedWrapV = texture.wrapV;
  14888. switch (texture.wrapV) {
  14889. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14890. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14891. break;
  14892. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14893. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14894. break;
  14895. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14896. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14897. break;
  14898. }
  14899. }
  14900. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14901. internalTexture._cachedWrapR = texture.wrapR;
  14902. switch (texture.wrapR) {
  14903. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14904. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14905. break;
  14906. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14907. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14908. break;
  14909. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14910. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14911. break;
  14912. }
  14913. }
  14914. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14915. }
  14916. else if (internalTexture && internalTexture.isCube) {
  14917. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14918. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14919. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14920. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14921. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14922. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14923. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14924. }
  14925. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14926. }
  14927. else {
  14928. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14929. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14930. internalTexture._cachedWrapU = texture.wrapU;
  14931. switch (texture.wrapU) {
  14932. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14933. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14934. break;
  14935. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14936. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14937. break;
  14938. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14939. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14940. break;
  14941. }
  14942. }
  14943. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14944. internalTexture._cachedWrapV = texture.wrapV;
  14945. switch (texture.wrapV) {
  14946. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14947. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14948. break;
  14949. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14950. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14951. break;
  14952. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14953. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14954. break;
  14955. }
  14956. }
  14957. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14958. }
  14959. return true;
  14960. };
  14961. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14962. if (channel < 0 || !uniform) {
  14963. return;
  14964. }
  14965. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14966. this._textureUnits = new Int32Array(textures.length);
  14967. }
  14968. for (var i = 0; i < textures.length; i++) {
  14969. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14970. }
  14971. this._gl.uniform1iv(uniform, this._textureUnits);
  14972. for (var index = 0; index < textures.length; index++) {
  14973. this._setTexture(this._textureUnits[index], textures[index], true);
  14974. }
  14975. };
  14976. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14977. var internalTexture = texture.getInternalTexture();
  14978. if (!internalTexture) {
  14979. return;
  14980. }
  14981. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14982. var value = texture.anisotropicFilteringLevel;
  14983. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14984. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14985. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14986. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14987. }
  14988. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14989. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14990. internalTexture._cachedAnisotropicFilteringLevel = value;
  14991. }
  14992. };
  14993. Engine.prototype.readPixels = function (x, y, width, height) {
  14994. var data = new Uint8Array(height * width * 4);
  14995. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14996. return data;
  14997. };
  14998. /**
  14999. * Add an externaly attached data from its key.
  15000. * This method call will fail and return false, if such key already exists.
  15001. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  15002. * @param key the unique key that identifies the data
  15003. * @param data the data object to associate to the key for this Engine instance
  15004. * @return true if no such key were already present and the data was added successfully, false otherwise
  15005. */
  15006. Engine.prototype.addExternalData = function (key, data) {
  15007. if (!this._externalData) {
  15008. this._externalData = new BABYLON.StringDictionary();
  15009. }
  15010. return this._externalData.add(key, data);
  15011. };
  15012. /**
  15013. * Get an externaly attached data from its key
  15014. * @param key the unique key that identifies the data
  15015. * @return the associated data, if present (can be null), or undefined if not present
  15016. */
  15017. Engine.prototype.getExternalData = function (key) {
  15018. if (!this._externalData) {
  15019. this._externalData = new BABYLON.StringDictionary();
  15020. }
  15021. return this._externalData.get(key);
  15022. };
  15023. /**
  15024. * Get an externaly attached data from its key, create it using a factory if it's not already present
  15025. * @param key the unique key that identifies the data
  15026. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  15027. * @return the associated data, can be null if the factory returned null.
  15028. */
  15029. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  15030. if (!this._externalData) {
  15031. this._externalData = new BABYLON.StringDictionary();
  15032. }
  15033. return this._externalData.getOrAddWithFactory(key, factory);
  15034. };
  15035. /**
  15036. * Remove an externaly attached data from the Engine instance
  15037. * @param key the unique key that identifies the data
  15038. * @return true if the data was successfully removed, false if it doesn't exist
  15039. */
  15040. Engine.prototype.removeExternalData = function (key) {
  15041. if (!this._externalData) {
  15042. this._externalData = new BABYLON.StringDictionary();
  15043. }
  15044. return this._externalData.remove(key);
  15045. };
  15046. Engine.prototype.unbindAllAttributes = function () {
  15047. if (this._mustWipeVertexAttributes) {
  15048. this._mustWipeVertexAttributes = false;
  15049. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  15050. this._gl.disableVertexAttribArray(i);
  15051. this._vertexAttribArraysEnabled[i] = false;
  15052. this._currentBufferPointers[i].active = false;
  15053. }
  15054. return;
  15055. }
  15056. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  15057. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  15058. continue;
  15059. }
  15060. this._gl.disableVertexAttribArray(i);
  15061. this._vertexAttribArraysEnabled[i] = false;
  15062. this._currentBufferPointers[i].active = false;
  15063. }
  15064. };
  15065. Engine.prototype.releaseEffects = function () {
  15066. for (var name in this._compiledEffects) {
  15067. this._deleteProgram(this._compiledEffects[name]._program);
  15068. }
  15069. this._compiledEffects = {};
  15070. };
  15071. // Dispose
  15072. Engine.prototype.dispose = function () {
  15073. this.hideLoadingUI();
  15074. this.stopRenderLoop();
  15075. // Release postProcesses
  15076. while (this.postProcesses.length) {
  15077. this.postProcesses[0].dispose();
  15078. }
  15079. // Empty texture
  15080. if (this._emptyTexture) {
  15081. this._releaseTexture(this._emptyTexture);
  15082. this._emptyTexture = null;
  15083. }
  15084. if (this._emptyCubeTexture) {
  15085. this._releaseTexture(this._emptyCubeTexture);
  15086. this._emptyCubeTexture = null;
  15087. }
  15088. // Rescale PP
  15089. if (this._rescalePostProcess) {
  15090. this._rescalePostProcess.dispose();
  15091. }
  15092. // Release scenes
  15093. while (this.scenes.length) {
  15094. this.scenes[0].dispose();
  15095. }
  15096. // Release audio engine
  15097. if (Engine.audioEngine) {
  15098. Engine.audioEngine.dispose();
  15099. }
  15100. // Release effects
  15101. this.releaseEffects();
  15102. // Unbind
  15103. this.unbindAllAttributes();
  15104. this._boundUniforms = [];
  15105. if (this._dummyFramebuffer) {
  15106. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  15107. }
  15108. //WebVR
  15109. this.disableVR();
  15110. // Events
  15111. if (BABYLON.Tools.IsWindowObjectExist()) {
  15112. window.removeEventListener("blur", this._onBlur);
  15113. window.removeEventListener("focus", this._onFocus);
  15114. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  15115. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  15116. if (this._renderingCanvas) {
  15117. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  15118. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  15119. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  15120. if (!this._doNotHandleContextLost) {
  15121. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  15122. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  15123. }
  15124. }
  15125. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  15126. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  15127. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  15128. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  15129. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  15130. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  15131. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  15132. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  15133. if (this._onVrDisplayConnect) {
  15134. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  15135. if (this._onVrDisplayDisconnect) {
  15136. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  15137. }
  15138. if (this._onVrDisplayPresentChange) {
  15139. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  15140. }
  15141. this._onVrDisplayConnect = null;
  15142. this._onVrDisplayDisconnect = null;
  15143. }
  15144. }
  15145. // Remove from Instances
  15146. var index = Engine.Instances.indexOf(this);
  15147. if (index >= 0) {
  15148. Engine.Instances.splice(index, 1);
  15149. }
  15150. this._workingCanvas = null;
  15151. this._workingContext = null;
  15152. this._currentBufferPointers = [];
  15153. this._renderingCanvas = null;
  15154. this._currentProgram = null;
  15155. this._bindedRenderFunction = null;
  15156. this.onResizeObservable.clear();
  15157. this.onCanvasBlurObservable.clear();
  15158. this.onCanvasFocusObservable.clear();
  15159. this.onCanvasPointerOutObservable.clear();
  15160. this.onBeginFrameObservable.clear();
  15161. this.onEndFrameObservable.clear();
  15162. BABYLON.Effect.ResetCache();
  15163. // Abort active requests
  15164. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  15165. var request = _a[_i];
  15166. request.abort();
  15167. }
  15168. };
  15169. // Loading screen
  15170. Engine.prototype.displayLoadingUI = function () {
  15171. if (!BABYLON.Tools.IsWindowObjectExist()) {
  15172. return;
  15173. }
  15174. var loadingScreen = this.loadingScreen;
  15175. if (loadingScreen) {
  15176. loadingScreen.displayLoadingUI();
  15177. }
  15178. };
  15179. Engine.prototype.hideLoadingUI = function () {
  15180. if (!BABYLON.Tools.IsWindowObjectExist()) {
  15181. return;
  15182. }
  15183. var loadingScreen = this.loadingScreen;
  15184. if (loadingScreen) {
  15185. loadingScreen.hideLoadingUI();
  15186. }
  15187. };
  15188. Object.defineProperty(Engine.prototype, "loadingScreen", {
  15189. get: function () {
  15190. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  15191. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  15192. return this._loadingScreen;
  15193. },
  15194. set: function (loadingScreen) {
  15195. this._loadingScreen = loadingScreen;
  15196. },
  15197. enumerable: true,
  15198. configurable: true
  15199. });
  15200. Object.defineProperty(Engine.prototype, "loadingUIText", {
  15201. set: function (text) {
  15202. this.loadingScreen.loadingUIText = text;
  15203. },
  15204. enumerable: true,
  15205. configurable: true
  15206. });
  15207. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  15208. set: function (color) {
  15209. this.loadingScreen.loadingUIBackgroundColor = color;
  15210. },
  15211. enumerable: true,
  15212. configurable: true
  15213. });
  15214. Engine.prototype.attachContextLostEvent = function (callback) {
  15215. if (this._renderingCanvas) {
  15216. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  15217. }
  15218. };
  15219. Engine.prototype.attachContextRestoredEvent = function (callback) {
  15220. if (this._renderingCanvas) {
  15221. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  15222. }
  15223. };
  15224. Engine.prototype.getVertexShaderSource = function (program) {
  15225. var shaders = this._gl.getAttachedShaders(program);
  15226. if (!shaders) {
  15227. return null;
  15228. }
  15229. return this._gl.getShaderSource(shaders[0]);
  15230. };
  15231. Engine.prototype.getFragmentShaderSource = function (program) {
  15232. var shaders = this._gl.getAttachedShaders(program);
  15233. if (!shaders) {
  15234. return null;
  15235. }
  15236. return this._gl.getShaderSource(shaders[1]);
  15237. };
  15238. Engine.prototype.getError = function () {
  15239. return this._gl.getError();
  15240. };
  15241. // FPS
  15242. Engine.prototype.getFps = function () {
  15243. return this._fps;
  15244. };
  15245. Engine.prototype.getDeltaTime = function () {
  15246. return this._deltaTime;
  15247. };
  15248. Engine.prototype._measureFps = function () {
  15249. this._performanceMonitor.sampleFrame();
  15250. this._fps = this._performanceMonitor.averageFPS;
  15251. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  15252. };
  15253. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  15254. if (faceIndex === void 0) { faceIndex = -1; }
  15255. var gl = this._gl;
  15256. if (!this._dummyFramebuffer) {
  15257. var dummy = gl.createFramebuffer();
  15258. if (!dummy) {
  15259. throw new Error("Unable to create dummy framebuffer");
  15260. }
  15261. this._dummyFramebuffer = dummy;
  15262. }
  15263. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  15264. if (faceIndex > -1) {
  15265. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  15266. }
  15267. else {
  15268. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15269. }
  15270. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  15271. var buffer;
  15272. switch (readType) {
  15273. case gl.UNSIGNED_BYTE:
  15274. buffer = new Uint8Array(4 * width * height);
  15275. readType = gl.UNSIGNED_BYTE;
  15276. break;
  15277. default:
  15278. buffer = new Float32Array(4 * width * height);
  15279. readType = gl.FLOAT;
  15280. break;
  15281. }
  15282. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  15283. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  15284. return buffer;
  15285. };
  15286. Engine.prototype._canRenderToFloatFramebuffer = function () {
  15287. if (this._webGLVersion > 1) {
  15288. return this._caps.colorBufferFloat;
  15289. }
  15290. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  15291. };
  15292. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  15293. if (this._webGLVersion > 1) {
  15294. return this._caps.colorBufferFloat;
  15295. }
  15296. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  15297. };
  15298. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  15299. Engine.prototype._canRenderToFramebuffer = function (type) {
  15300. var gl = this._gl;
  15301. //clear existing errors
  15302. while (gl.getError() !== gl.NO_ERROR) { }
  15303. var successful = true;
  15304. var texture = gl.createTexture();
  15305. gl.bindTexture(gl.TEXTURE_2D, texture);
  15306. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15307. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15308. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15309. var fb = gl.createFramebuffer();
  15310. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  15311. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  15312. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  15313. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  15314. successful = successful && (gl.getError() === gl.NO_ERROR);
  15315. //try render by clearing frame buffer's color buffer
  15316. if (successful) {
  15317. gl.clear(gl.COLOR_BUFFER_BIT);
  15318. successful = successful && (gl.getError() === gl.NO_ERROR);
  15319. }
  15320. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  15321. if (successful) {
  15322. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  15323. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15324. var readFormat = gl.RGBA;
  15325. var readType = gl.UNSIGNED_BYTE;
  15326. var buffer = new Uint8Array(4);
  15327. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  15328. successful = successful && (gl.getError() === gl.NO_ERROR);
  15329. }
  15330. //clean up
  15331. gl.deleteTexture(texture);
  15332. gl.deleteFramebuffer(fb);
  15333. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15334. //clear accumulated errors
  15335. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  15336. return successful;
  15337. };
  15338. Engine.prototype._getWebGLTextureType = function (type) {
  15339. if (type === Engine.TEXTURETYPE_FLOAT) {
  15340. return this._gl.FLOAT;
  15341. }
  15342. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15343. // Add Half Float Constant.
  15344. return this._gl.HALF_FLOAT_OES;
  15345. }
  15346. return this._gl.UNSIGNED_BYTE;
  15347. };
  15348. ;
  15349. Engine.prototype._getInternalFormat = function (format) {
  15350. var internalFormat = this._gl.RGBA;
  15351. switch (format) {
  15352. case Engine.TEXTUREFORMAT_ALPHA:
  15353. internalFormat = this._gl.ALPHA;
  15354. break;
  15355. case Engine.TEXTUREFORMAT_LUMINANCE:
  15356. internalFormat = this._gl.LUMINANCE;
  15357. break;
  15358. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  15359. internalFormat = this._gl.LUMINANCE_ALPHA;
  15360. break;
  15361. case Engine.TEXTUREFORMAT_RGB:
  15362. case Engine.TEXTUREFORMAT_RGB32F:
  15363. internalFormat = this._gl.RGB;
  15364. break;
  15365. case Engine.TEXTUREFORMAT_RGBA:
  15366. case Engine.TEXTUREFORMAT_RGBA32F:
  15367. internalFormat = this._gl.RGBA;
  15368. break;
  15369. case Engine.TEXTUREFORMAT_R32F:
  15370. internalFormat = this._gl.RED;
  15371. break;
  15372. case Engine.TEXTUREFORMAT_RG32F:
  15373. internalFormat = this._gl.RG;
  15374. break;
  15375. }
  15376. return internalFormat;
  15377. };
  15378. /** @ignore */
  15379. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  15380. if (this._webGLVersion === 1) {
  15381. if (format) {
  15382. switch (format) {
  15383. case Engine.TEXTUREFORMAT_LUMINANCE:
  15384. return this._gl.LUMINANCE;
  15385. }
  15386. }
  15387. return this._gl.RGBA;
  15388. }
  15389. if (type === Engine.TEXTURETYPE_FLOAT) {
  15390. if (format) {
  15391. switch (format) {
  15392. case Engine.TEXTUREFORMAT_R32F:
  15393. return this._gl.R32F;
  15394. case Engine.TEXTUREFORMAT_RG32F:
  15395. return this._gl.RG32F;
  15396. case Engine.TEXTUREFORMAT_RGB32F:
  15397. return this._gl.RGB32F;
  15398. }
  15399. }
  15400. return this._gl.RGBA32F;
  15401. }
  15402. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15403. return this._gl.RGBA16F;
  15404. }
  15405. if (format) {
  15406. switch (format) {
  15407. case Engine.TEXTUREFORMAT_LUMINANCE:
  15408. return this._gl.LUMINANCE;
  15409. }
  15410. }
  15411. return this._gl.RGBA;
  15412. };
  15413. ;
  15414. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  15415. if (type === Engine.TEXTURETYPE_FLOAT) {
  15416. return this._gl.RGBA32F;
  15417. }
  15418. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15419. return this._gl.RGBA16F;
  15420. }
  15421. return this._gl.RGBA8;
  15422. };
  15423. ;
  15424. Engine.prototype.createQuery = function () {
  15425. return this._gl.createQuery();
  15426. };
  15427. Engine.prototype.deleteQuery = function (query) {
  15428. this._gl.deleteQuery(query);
  15429. return this;
  15430. };
  15431. Engine.prototype.isQueryResultAvailable = function (query) {
  15432. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  15433. };
  15434. Engine.prototype.getQueryResult = function (query) {
  15435. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  15436. };
  15437. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  15438. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15439. this._gl.beginQuery(glAlgorithm, query);
  15440. return this;
  15441. };
  15442. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  15443. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15444. this._gl.endQuery(glAlgorithm);
  15445. return this;
  15446. };
  15447. /* Time queries */
  15448. Engine.prototype._createTimeQuery = function () {
  15449. var timerQuery = this._caps.timerQuery;
  15450. if (timerQuery.createQueryEXT) {
  15451. return timerQuery.createQueryEXT();
  15452. }
  15453. return this.createQuery();
  15454. };
  15455. Engine.prototype._deleteTimeQuery = function (query) {
  15456. var timerQuery = this._caps.timerQuery;
  15457. if (timerQuery.deleteQueryEXT) {
  15458. timerQuery.deleteQueryEXT(query);
  15459. return;
  15460. }
  15461. this.deleteQuery(query);
  15462. };
  15463. Engine.prototype._getTimeQueryResult = function (query) {
  15464. var timerQuery = this._caps.timerQuery;
  15465. if (timerQuery.getQueryObjectEXT) {
  15466. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  15467. }
  15468. return this.getQueryResult(query);
  15469. };
  15470. Engine.prototype._getTimeQueryAvailability = function (query) {
  15471. var timerQuery = this._caps.timerQuery;
  15472. if (timerQuery.getQueryObjectEXT) {
  15473. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  15474. }
  15475. return this.isQueryResultAvailable(query);
  15476. };
  15477. Engine.prototype.startTimeQuery = function () {
  15478. var timerQuery = this._caps.timerQuery;
  15479. if (!timerQuery) {
  15480. return null;
  15481. }
  15482. var token = new BABYLON._TimeToken();
  15483. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15484. if (this._caps.canUseTimestampForTimerQuery) {
  15485. token._startTimeQuery = this._createTimeQuery();
  15486. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  15487. }
  15488. else {
  15489. if (this._currentNonTimestampToken) {
  15490. return this._currentNonTimestampToken;
  15491. }
  15492. token._timeElapsedQuery = this._createTimeQuery();
  15493. if (timerQuery.beginQueryEXT) {
  15494. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15495. }
  15496. else {
  15497. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15498. }
  15499. this._currentNonTimestampToken = token;
  15500. }
  15501. return token;
  15502. };
  15503. Engine.prototype.endTimeQuery = function (token) {
  15504. var timerQuery = this._caps.timerQuery;
  15505. if (!timerQuery || !token) {
  15506. return -1;
  15507. }
  15508. if (this._caps.canUseTimestampForTimerQuery) {
  15509. if (!token._startTimeQuery) {
  15510. return -1;
  15511. }
  15512. if (!token._endTimeQuery) {
  15513. token._endTimeQuery = this._createTimeQuery();
  15514. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  15515. }
  15516. }
  15517. else if (!token._timeElapsedQueryEnded) {
  15518. if (!token._timeElapsedQuery) {
  15519. return -1;
  15520. }
  15521. if (timerQuery.endQueryEXT) {
  15522. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  15523. }
  15524. else {
  15525. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  15526. }
  15527. token._timeElapsedQueryEnded = true;
  15528. }
  15529. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15530. var available = false;
  15531. if (token._endTimeQuery) {
  15532. available = this._getTimeQueryAvailability(token._endTimeQuery);
  15533. }
  15534. else if (token._timeElapsedQuery) {
  15535. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  15536. }
  15537. if (available && !disjoint) {
  15538. var result = 0;
  15539. if (this._caps.canUseTimestampForTimerQuery) {
  15540. if (!token._startTimeQuery || !token._endTimeQuery) {
  15541. return -1;
  15542. }
  15543. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  15544. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  15545. result = timeEnd - timeStart;
  15546. this._deleteTimeQuery(token._startTimeQuery);
  15547. this._deleteTimeQuery(token._endTimeQuery);
  15548. token._startTimeQuery = null;
  15549. token._endTimeQuery = null;
  15550. }
  15551. else {
  15552. if (!token._timeElapsedQuery) {
  15553. return -1;
  15554. }
  15555. result = this._getTimeQueryResult(token._timeElapsedQuery);
  15556. this._deleteTimeQuery(token._timeElapsedQuery);
  15557. token._timeElapsedQuery = null;
  15558. token._timeElapsedQueryEnded = false;
  15559. this._currentNonTimestampToken = null;
  15560. }
  15561. return result;
  15562. }
  15563. return -1;
  15564. };
  15565. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  15566. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  15567. };
  15568. // Transform feedback
  15569. Engine.prototype.createTransformFeedback = function () {
  15570. return this._gl.createTransformFeedback();
  15571. };
  15572. Engine.prototype.deleteTransformFeedback = function (value) {
  15573. this._gl.deleteTransformFeedback(value);
  15574. };
  15575. Engine.prototype.bindTransformFeedback = function (value) {
  15576. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  15577. };
  15578. Engine.prototype.beginTransformFeedback = function (usePoints) {
  15579. if (usePoints === void 0) { usePoints = true; }
  15580. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  15581. };
  15582. Engine.prototype.endTransformFeedback = function () {
  15583. this._gl.endTransformFeedback();
  15584. };
  15585. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  15586. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  15587. };
  15588. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  15589. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  15590. };
  15591. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  15592. var _this = this;
  15593. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  15594. this._activeRequests.push(request);
  15595. request.onCompleteObservable.add(function (request) {
  15596. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  15597. });
  15598. return request;
  15599. };
  15600. /** @ignore */
  15601. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  15602. var _this = this;
  15603. return new Promise(function (resolve, reject) {
  15604. _this._loadFile(url, function (data) {
  15605. resolve(data);
  15606. }, undefined, database, useArrayBuffer, function (request, exception) {
  15607. reject(exception);
  15608. });
  15609. });
  15610. };
  15611. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  15612. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15613. var onload = function (data) {
  15614. loadedFiles[index] = data;
  15615. loadedFiles._internalCount++;
  15616. if (loadedFiles._internalCount === 6) {
  15617. onfinish(loadedFiles);
  15618. }
  15619. };
  15620. var onerror = function (request, exception) {
  15621. if (onErrorCallBack && request) {
  15622. onErrorCallBack(request.status + " " + request.statusText, exception);
  15623. }
  15624. };
  15625. this._loadFile(url, onload, undefined, undefined, true, onerror);
  15626. };
  15627. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  15628. if (onError === void 0) { onError = null; }
  15629. var loadedFiles = [];
  15630. loadedFiles._internalCount = 0;
  15631. for (var index = 0; index < 6; index++) {
  15632. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  15633. }
  15634. };
  15635. // Statics
  15636. Engine.isSupported = function () {
  15637. try {
  15638. var tempcanvas = document.createElement("canvas");
  15639. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  15640. return gl != null && !!window.WebGLRenderingContext;
  15641. }
  15642. catch (e) {
  15643. return false;
  15644. }
  15645. };
  15646. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  15647. Engine.ExceptionList = [
  15648. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  15649. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15650. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15651. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15652. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15653. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  15654. ];
  15655. Engine.Instances = new Array();
  15656. // Const statics
  15657. Engine._ALPHA_DISABLE = 0;
  15658. Engine._ALPHA_ADD = 1;
  15659. Engine._ALPHA_COMBINE = 2;
  15660. Engine._ALPHA_SUBTRACT = 3;
  15661. Engine._ALPHA_MULTIPLY = 4;
  15662. Engine._ALPHA_MAXIMIZED = 5;
  15663. Engine._ALPHA_ONEONE = 6;
  15664. Engine._ALPHA_PREMULTIPLIED = 7;
  15665. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15666. Engine._ALPHA_INTERPOLATE = 9;
  15667. Engine._ALPHA_SCREENMODE = 10;
  15668. Engine._DELAYLOADSTATE_NONE = 0;
  15669. Engine._DELAYLOADSTATE_LOADED = 1;
  15670. Engine._DELAYLOADSTATE_LOADING = 2;
  15671. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15672. Engine._TEXTUREFORMAT_ALPHA = 0;
  15673. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15674. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15675. Engine._TEXTUREFORMAT_RGB = 4;
  15676. Engine._TEXTUREFORMAT_RGBA = 5;
  15677. Engine._TEXTUREFORMAT_R32F = 6;
  15678. Engine._TEXTUREFORMAT_RG32F = 7;
  15679. Engine._TEXTUREFORMAT_RGB32F = 8;
  15680. Engine._TEXTUREFORMAT_RGBA32F = 9;
  15681. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15682. Engine._TEXTURETYPE_FLOAT = 1;
  15683. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15684. // Depht or Stencil test Constants.
  15685. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15686. 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.
  15687. 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.
  15688. 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.
  15689. 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.
  15690. 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.
  15691. 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.
  15692. 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.
  15693. // Stencil Actions Constants.
  15694. Engine._KEEP = 0x1E00;
  15695. Engine._REPLACE = 0x1E01;
  15696. Engine._INCR = 0x1E02;
  15697. Engine._DECR = 0x1E03;
  15698. Engine._INVERT = 0x150A;
  15699. Engine._INCR_WRAP = 0x8507;
  15700. Engine._DECR_WRAP = 0x8508;
  15701. // Texture rescaling mode
  15702. Engine._SCALEMODE_FLOOR = 1;
  15703. Engine._SCALEMODE_NEAREST = 2;
  15704. Engine._SCALEMODE_CEILING = 3;
  15705. // Updatable statics so stick with vars here
  15706. Engine.CollisionsEpsilon = 0.001;
  15707. Engine.CodeRepository = "src/";
  15708. Engine.ShadersRepository = "src/Shaders/";
  15709. return Engine;
  15710. }());
  15711. BABYLON.Engine = Engine;
  15712. })(BABYLON || (BABYLON = {}));
  15713. //# sourceMappingURL=babylon.engine.js.map
  15714. "use strict";
  15715. var BABYLON;
  15716. (function (BABYLON) {
  15717. /**
  15718. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15719. */
  15720. var Node = /** @class */ (function () {
  15721. /**
  15722. * Creates a new Node
  15723. * @param {string} name - the name and id to be given to this node
  15724. * @param {BABYLON.Scene} the scene this node will be added to
  15725. */
  15726. function Node(name, scene) {
  15727. if (scene === void 0) { scene = null; }
  15728. /**
  15729. * Gets or sets a string used to store user defined state for the node
  15730. */
  15731. this.state = "";
  15732. /**
  15733. * Gets or sets an object used to store user defined information for the node
  15734. */
  15735. this.metadata = null;
  15736. /**
  15737. * Gets or sets a boolean used to define if the node must be serialized
  15738. */
  15739. this.doNotSerialize = false;
  15740. /** @ignore */
  15741. this._isDisposed = false;
  15742. /**
  15743. * Gets a list of {BABYLON.Animation} associated with the node
  15744. */
  15745. this.animations = new Array();
  15746. this._ranges = {};
  15747. this._isEnabled = true;
  15748. this._isReady = true;
  15749. /** @ignore */
  15750. this._currentRenderId = -1;
  15751. this._parentRenderId = -1;
  15752. this._childRenderId = -1;
  15753. this._animationPropertiesOverride = null;
  15754. /**
  15755. * An event triggered when the mesh is disposed
  15756. */
  15757. this.onDisposeObservable = new BABYLON.Observable();
  15758. // Behaviors
  15759. this._behaviors = new Array();
  15760. this.name = name;
  15761. this.id = name;
  15762. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15763. this.uniqueId = this._scene.getUniqueId();
  15764. this._initCache();
  15765. }
  15766. /**
  15767. * Gets a boolean indicating if the node has been disposed
  15768. * @returns true if the node was disposed
  15769. */
  15770. Node.prototype.isDisposed = function () {
  15771. return this._isDisposed;
  15772. };
  15773. Object.defineProperty(Node.prototype, "parent", {
  15774. get: function () {
  15775. return this._parentNode;
  15776. },
  15777. /**
  15778. * Gets or sets the parent of the node
  15779. */
  15780. set: function (parent) {
  15781. if (this._parentNode === parent) {
  15782. return;
  15783. }
  15784. // Remove self from list of children of parent
  15785. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15786. var index = this._parentNode._children.indexOf(this);
  15787. if (index !== -1) {
  15788. this._parentNode._children.splice(index, 1);
  15789. }
  15790. }
  15791. // Store new parent
  15792. this._parentNode = parent;
  15793. // Add as child to new parent
  15794. if (this._parentNode) {
  15795. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15796. this._parentNode._children = new Array();
  15797. }
  15798. this._parentNode._children.push(this);
  15799. }
  15800. },
  15801. enumerable: true,
  15802. configurable: true
  15803. });
  15804. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  15805. /**
  15806. * Gets or sets the animation properties override
  15807. */
  15808. get: function () {
  15809. return this._animationPropertiesOverride;
  15810. },
  15811. set: function (value) {
  15812. this._animationPropertiesOverride = value;
  15813. },
  15814. enumerable: true,
  15815. configurable: true
  15816. });
  15817. /**
  15818. * Gets a string idenfifying the name of the class
  15819. * @returns "Node" string
  15820. */
  15821. Node.prototype.getClassName = function () {
  15822. return "Node";
  15823. };
  15824. Object.defineProperty(Node.prototype, "onDispose", {
  15825. /**
  15826. * Sets a callback that will be raised when the node will be disposed
  15827. */
  15828. set: function (callback) {
  15829. if (this._onDisposeObserver) {
  15830. this.onDisposeObservable.remove(this._onDisposeObserver);
  15831. }
  15832. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15833. },
  15834. enumerable: true,
  15835. configurable: true
  15836. });
  15837. /**
  15838. * Gets the scene of the node
  15839. * @returns a {BABYLON.Scene}
  15840. */
  15841. Node.prototype.getScene = function () {
  15842. return this._scene;
  15843. };
  15844. /**
  15845. * Gets the engine of the node
  15846. * @returns a {BABYLON.Engine}
  15847. */
  15848. Node.prototype.getEngine = function () {
  15849. return this._scene.getEngine();
  15850. };
  15851. /**
  15852. * Attach a behavior to the node
  15853. * @see http://doc.babylonjs.com/features/behaviour
  15854. * @param behavior defines the behavior to attach
  15855. * @returns the current Node
  15856. */
  15857. Node.prototype.addBehavior = function (behavior) {
  15858. var _this = this;
  15859. var index = this._behaviors.indexOf(behavior);
  15860. if (index !== -1) {
  15861. return this;
  15862. }
  15863. behavior.init();
  15864. if (this._scene.isLoading) {
  15865. // We defer the attach when the scene will be loaded
  15866. var observer = this._scene.onDataLoadedObservable.add(function () {
  15867. behavior.attach(_this);
  15868. setTimeout(function () {
  15869. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15870. _this._scene.onDataLoadedObservable.remove(observer);
  15871. }, 0);
  15872. });
  15873. }
  15874. else {
  15875. behavior.attach(this);
  15876. }
  15877. this._behaviors.push(behavior);
  15878. return this;
  15879. };
  15880. /**
  15881. * Remove an attached behavior
  15882. * @see http://doc.babylonjs.com/features/behaviour
  15883. * @param behavior defines the behavior to attach
  15884. * @returns the current Node
  15885. */
  15886. Node.prototype.removeBehavior = function (behavior) {
  15887. var index = this._behaviors.indexOf(behavior);
  15888. if (index === -1) {
  15889. return this;
  15890. }
  15891. this._behaviors[index].detach();
  15892. this._behaviors.splice(index, 1);
  15893. return this;
  15894. };
  15895. Object.defineProperty(Node.prototype, "behaviors", {
  15896. /**
  15897. * Gets the list of attached behaviors
  15898. * @see http://doc.babylonjs.com/features/behaviour
  15899. */
  15900. get: function () {
  15901. return this._behaviors;
  15902. },
  15903. enumerable: true,
  15904. configurable: true
  15905. });
  15906. /**
  15907. * Gets an attached behavior by name
  15908. * @param name defines the name of the behavior to look for
  15909. * @see http://doc.babylonjs.com/features/behaviour
  15910. * @returns null if behavior was not found else the requested behavior
  15911. */
  15912. Node.prototype.getBehaviorByName = function (name) {
  15913. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15914. var behavior = _a[_i];
  15915. if (behavior.name === name) {
  15916. return behavior;
  15917. }
  15918. }
  15919. return null;
  15920. };
  15921. /**
  15922. * Returns the world matrix of the node
  15923. * @returns a matrix containing the node's world matrix
  15924. */
  15925. Node.prototype.getWorldMatrix = function () {
  15926. return BABYLON.Matrix.Identity();
  15927. };
  15928. // override it in derived class if you add new variables to the cache
  15929. // and call the parent class method
  15930. /** @ignore */
  15931. Node.prototype._initCache = function () {
  15932. this._cache = {};
  15933. this._cache.parent = undefined;
  15934. };
  15935. /** @ignore */
  15936. Node.prototype.updateCache = function (force) {
  15937. if (!force && this.isSynchronized())
  15938. return;
  15939. this._cache.parent = this.parent;
  15940. this._updateCache();
  15941. };
  15942. // override it in derived class if you add new variables to the cache
  15943. // and call the parent class method if !ignoreParentClass
  15944. /** @ignore */
  15945. Node.prototype._updateCache = function (ignoreParentClass) {
  15946. };
  15947. // override it in derived class if you add new variables to the cache
  15948. /** @ignore */
  15949. Node.prototype._isSynchronized = function () {
  15950. return true;
  15951. };
  15952. /** @ignore */
  15953. Node.prototype._markSyncedWithParent = function () {
  15954. if (this.parent) {
  15955. this._parentRenderId = this.parent._childRenderId;
  15956. }
  15957. };
  15958. /** @ignore */
  15959. Node.prototype.isSynchronizedWithParent = function () {
  15960. if (!this.parent) {
  15961. return true;
  15962. }
  15963. if (this._parentRenderId !== this.parent._childRenderId) {
  15964. return false;
  15965. }
  15966. return this.parent.isSynchronized();
  15967. };
  15968. /** @ignore */
  15969. Node.prototype.isSynchronized = function (updateCache) {
  15970. var check = this.hasNewParent();
  15971. check = check || !this.isSynchronizedWithParent();
  15972. check = check || !this._isSynchronized();
  15973. if (updateCache)
  15974. this.updateCache(true);
  15975. return !check;
  15976. };
  15977. /** @ignore */
  15978. Node.prototype.hasNewParent = function (update) {
  15979. if (this._cache.parent === this.parent)
  15980. return false;
  15981. if (update)
  15982. this._cache.parent = this.parent;
  15983. return true;
  15984. };
  15985. /**
  15986. * Is this node ready to be used/rendered
  15987. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  15988. * @return true if the node is ready
  15989. */
  15990. Node.prototype.isReady = function (completeCheck) {
  15991. if (completeCheck === void 0) { completeCheck = false; }
  15992. return this._isReady;
  15993. };
  15994. /**
  15995. * Is this node enabled?
  15996. * 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
  15997. * @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
  15998. * @return whether this node (and its parent) is enabled
  15999. */
  16000. Node.prototype.isEnabled = function (checkAncestors) {
  16001. if (checkAncestors === void 0) { checkAncestors = true; }
  16002. if (checkAncestors === false) {
  16003. return this._isEnabled;
  16004. }
  16005. if (this._isEnabled === false) {
  16006. return false;
  16007. }
  16008. if (this.parent !== undefined && this.parent !== null) {
  16009. return this.parent.isEnabled(checkAncestors);
  16010. }
  16011. return true;
  16012. };
  16013. /**
  16014. * Set the enabled state of this node
  16015. * @param value defines the new enabled state
  16016. */
  16017. Node.prototype.setEnabled = function (value) {
  16018. this._isEnabled = value;
  16019. };
  16020. /**
  16021. * Is this node a descendant of the given node?
  16022. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  16023. * @param ancestor defines the parent node to inspect
  16024. * @returns a boolean indicating if this node is a descendant of the given node
  16025. */
  16026. Node.prototype.isDescendantOf = function (ancestor) {
  16027. if (this.parent) {
  16028. if (this.parent === ancestor) {
  16029. return true;
  16030. }
  16031. return this.parent.isDescendantOf(ancestor);
  16032. }
  16033. return false;
  16034. };
  16035. /** @ignore */
  16036. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  16037. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  16038. if (!this._children) {
  16039. return;
  16040. }
  16041. for (var index = 0; index < this._children.length; index++) {
  16042. var item = this._children[index];
  16043. if (!predicate || predicate(item)) {
  16044. results.push(item);
  16045. }
  16046. if (!directDescendantsOnly) {
  16047. item._getDescendants(results, false, predicate);
  16048. }
  16049. }
  16050. };
  16051. /**
  16052. * Will return all nodes that have this node as ascendant
  16053. * @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
  16054. * @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
  16055. * @return all children nodes of all types
  16056. */
  16057. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  16058. var results = new Array();
  16059. this._getDescendants(results, directDescendantsOnly, predicate);
  16060. return results;
  16061. };
  16062. /**
  16063. * Get all child-meshes of this node
  16064. * @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
  16065. * @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
  16066. * @returns an array of {BABYLON.AbstractMesh}
  16067. */
  16068. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  16069. var results = [];
  16070. this._getDescendants(results, directDescendantsOnly, function (node) {
  16071. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  16072. });
  16073. return results;
  16074. };
  16075. /**
  16076. * Get all child-transformNodes of this node
  16077. * @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
  16078. * @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
  16079. * @returns an array of {BABYLON.TransformNode}
  16080. */
  16081. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  16082. var results = [];
  16083. this._getDescendants(results, directDescendantsOnly, function (node) {
  16084. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  16085. });
  16086. return results;
  16087. };
  16088. /**
  16089. * Get all direct children of this node
  16090. * @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
  16091. * @returns an array of {BABYLON.Node}
  16092. */
  16093. Node.prototype.getChildren = function (predicate) {
  16094. return this.getDescendants(true, predicate);
  16095. };
  16096. /** @ignore */
  16097. Node.prototype._setReady = function (state) {
  16098. if (state === this._isReady) {
  16099. return;
  16100. }
  16101. if (!state) {
  16102. this._isReady = false;
  16103. return;
  16104. }
  16105. if (this.onReady) {
  16106. this.onReady(this);
  16107. }
  16108. this._isReady = true;
  16109. };
  16110. /**
  16111. * Get an animation by name
  16112. * @param name defines the name of the animation to look for
  16113. * @returns null if not found else the requested animation
  16114. */
  16115. Node.prototype.getAnimationByName = function (name) {
  16116. for (var i = 0; i < this.animations.length; i++) {
  16117. var animation = this.animations[i];
  16118. if (animation.name === name) {
  16119. return animation;
  16120. }
  16121. }
  16122. return null;
  16123. };
  16124. /**
  16125. * Creates an animation range for this node
  16126. * @param name defines the name of the range
  16127. * @param from defines the starting key
  16128. * @param to defines the end key
  16129. */
  16130. Node.prototype.createAnimationRange = function (name, from, to) {
  16131. // check name not already in use
  16132. if (!this._ranges[name]) {
  16133. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  16134. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  16135. if (this.animations[i]) {
  16136. this.animations[i].createRange(name, from, to);
  16137. }
  16138. }
  16139. }
  16140. };
  16141. /**
  16142. * Delete a specific animation range
  16143. * @param name defines the name of the range to delete
  16144. * @param deleteFrames defines if animation frames from the range must be deleted as well
  16145. */
  16146. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  16147. if (deleteFrames === void 0) { deleteFrames = true; }
  16148. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  16149. if (this.animations[i]) {
  16150. this.animations[i].deleteRange(name, deleteFrames);
  16151. }
  16152. }
  16153. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  16154. };
  16155. /**
  16156. * Get an animation range by name
  16157. * @param name defines the name of the animation range to look for
  16158. * @returns null if not found else the requested animation range
  16159. */
  16160. Node.prototype.getAnimationRange = function (name) {
  16161. return this._ranges[name];
  16162. };
  16163. /**
  16164. * Will start the animation sequence
  16165. * @param name defines the range frames for animation sequence
  16166. * @param loop defines if the animation should loop (false by default)
  16167. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  16168. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  16169. * @returns the object created for this animation. If range does not exist, it will return null
  16170. */
  16171. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  16172. var range = this.getAnimationRange(name);
  16173. if (!range) {
  16174. return null;
  16175. }
  16176. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  16177. };
  16178. /**
  16179. * Serialize animation ranges into a JSON compatible object
  16180. * @returns serialization object
  16181. */
  16182. Node.prototype.serializeAnimationRanges = function () {
  16183. var serializationRanges = [];
  16184. for (var name in this._ranges) {
  16185. var localRange = this._ranges[name];
  16186. if (!localRange) {
  16187. continue;
  16188. }
  16189. var range = {};
  16190. range.name = name;
  16191. range.from = localRange.from;
  16192. range.to = localRange.to;
  16193. serializationRanges.push(range);
  16194. }
  16195. return serializationRanges;
  16196. };
  16197. /**
  16198. * Computes the world matrix of the node
  16199. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  16200. * @returns the world matrix
  16201. */
  16202. Node.prototype.computeWorldMatrix = function (force) {
  16203. return BABYLON.Matrix.Identity();
  16204. };
  16205. /**
  16206. * Releases resources associated with this node.
  16207. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  16208. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  16209. */
  16210. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  16211. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  16212. if (!doNotRecurse) {
  16213. var nodes = this.getDescendants(true);
  16214. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  16215. var node = nodes_1[_i];
  16216. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  16217. }
  16218. }
  16219. else {
  16220. var transformNodes = this.getChildTransformNodes(true);
  16221. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  16222. var transformNode = transformNodes_1[_a];
  16223. transformNode.parent = null;
  16224. transformNode.computeWorldMatrix(true);
  16225. }
  16226. }
  16227. this.parent = null;
  16228. // Callback
  16229. this.onDisposeObservable.notifyObservers(this);
  16230. this.onDisposeObservable.clear();
  16231. // Behaviors
  16232. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  16233. var behavior = _c[_b];
  16234. behavior.detach();
  16235. }
  16236. this._behaviors = [];
  16237. this._isDisposed = true;
  16238. };
  16239. /**
  16240. * Parse animation range data from a serialization object and store them into a given node
  16241. * @param node defines where to store the animation ranges
  16242. * @param parsedNode defines the serialization object to read data from
  16243. * @param scene defines the hosting scene
  16244. */
  16245. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  16246. if (parsedNode.ranges) {
  16247. for (var index = 0; index < parsedNode.ranges.length; index++) {
  16248. var data = parsedNode.ranges[index];
  16249. node.createAnimationRange(data.name, data.from, data.to);
  16250. }
  16251. }
  16252. };
  16253. __decorate([
  16254. BABYLON.serialize()
  16255. ], Node.prototype, "name", void 0);
  16256. __decorate([
  16257. BABYLON.serialize()
  16258. ], Node.prototype, "id", void 0);
  16259. __decorate([
  16260. BABYLON.serialize()
  16261. ], Node.prototype, "uniqueId", void 0);
  16262. __decorate([
  16263. BABYLON.serialize()
  16264. ], Node.prototype, "state", void 0);
  16265. __decorate([
  16266. BABYLON.serialize()
  16267. ], Node.prototype, "metadata", void 0);
  16268. return Node;
  16269. }());
  16270. BABYLON.Node = Node;
  16271. })(BABYLON || (BABYLON = {}));
  16272. //# sourceMappingURL=babylon.node.js.map
  16273. "use strict";
  16274. var BABYLON;
  16275. (function (BABYLON) {
  16276. var BoundingSphere = /** @class */ (function () {
  16277. function BoundingSphere(minimum, maximum) {
  16278. this.minimum = minimum;
  16279. this.maximum = maximum;
  16280. this._tempRadiusVector = BABYLON.Vector3.Zero();
  16281. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  16282. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  16283. this.radius = distance * 0.5;
  16284. this.centerWorld = BABYLON.Vector3.Zero();
  16285. this._update(BABYLON.Matrix.Identity());
  16286. }
  16287. // Methods
  16288. BoundingSphere.prototype._update = function (world) {
  16289. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  16290. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  16291. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  16292. };
  16293. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  16294. for (var i = 0; i < 6; i++) {
  16295. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  16296. return false;
  16297. }
  16298. return true;
  16299. };
  16300. BoundingSphere.prototype.intersectsPoint = function (point) {
  16301. var x = this.centerWorld.x - point.x;
  16302. var y = this.centerWorld.y - point.y;
  16303. var z = this.centerWorld.z - point.z;
  16304. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16305. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  16306. return false;
  16307. return true;
  16308. };
  16309. // Statics
  16310. BoundingSphere.Intersects = function (sphere0, sphere1) {
  16311. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  16312. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  16313. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  16314. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16315. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  16316. return false;
  16317. return true;
  16318. };
  16319. return BoundingSphere;
  16320. }());
  16321. BABYLON.BoundingSphere = BoundingSphere;
  16322. })(BABYLON || (BABYLON = {}));
  16323. //# sourceMappingURL=babylon.boundingSphere.js.map
  16324. "use strict";
  16325. var BABYLON;
  16326. (function (BABYLON) {
  16327. var BoundingBox = /** @class */ (function () {
  16328. function BoundingBox(minimum, maximum) {
  16329. this.minimum = minimum;
  16330. this.maximum = maximum;
  16331. this.vectors = new Array();
  16332. this.vectorsWorld = new Array();
  16333. // Bounding vectors
  16334. this.vectors.push(this.minimum.clone());
  16335. this.vectors.push(this.maximum.clone());
  16336. this.vectors.push(this.minimum.clone());
  16337. this.vectors[2].x = this.maximum.x;
  16338. this.vectors.push(this.minimum.clone());
  16339. this.vectors[3].y = this.maximum.y;
  16340. this.vectors.push(this.minimum.clone());
  16341. this.vectors[4].z = this.maximum.z;
  16342. this.vectors.push(this.maximum.clone());
  16343. this.vectors[5].z = this.minimum.z;
  16344. this.vectors.push(this.maximum.clone());
  16345. this.vectors[6].x = this.minimum.x;
  16346. this.vectors.push(this.maximum.clone());
  16347. this.vectors[7].y = this.minimum.y;
  16348. // OBB
  16349. this.center = this.maximum.add(this.minimum).scale(0.5);
  16350. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  16351. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  16352. // World
  16353. for (var index = 0; index < this.vectors.length; index++) {
  16354. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  16355. }
  16356. this.minimumWorld = BABYLON.Vector3.Zero();
  16357. this.maximumWorld = BABYLON.Vector3.Zero();
  16358. this.centerWorld = BABYLON.Vector3.Zero();
  16359. this.extendSizeWorld = BABYLON.Vector3.Zero();
  16360. this._update(BABYLON.Matrix.Identity());
  16361. }
  16362. // Methods
  16363. BoundingBox.prototype.getWorldMatrix = function () {
  16364. return this._worldMatrix;
  16365. };
  16366. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  16367. this._worldMatrix.copyFrom(matrix);
  16368. return this;
  16369. };
  16370. BoundingBox.prototype._update = function (world) {
  16371. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  16372. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  16373. for (var index = 0; index < this.vectors.length; index++) {
  16374. var v = this.vectorsWorld[index];
  16375. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  16376. if (v.x < this.minimumWorld.x)
  16377. this.minimumWorld.x = v.x;
  16378. if (v.y < this.minimumWorld.y)
  16379. this.minimumWorld.y = v.y;
  16380. if (v.z < this.minimumWorld.z)
  16381. this.minimumWorld.z = v.z;
  16382. if (v.x > this.maximumWorld.x)
  16383. this.maximumWorld.x = v.x;
  16384. if (v.y > this.maximumWorld.y)
  16385. this.maximumWorld.y = v.y;
  16386. if (v.z > this.maximumWorld.z)
  16387. this.maximumWorld.z = v.z;
  16388. }
  16389. // Extend
  16390. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  16391. this.extendSizeWorld.scaleInPlace(0.5);
  16392. // OBB
  16393. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  16394. this.centerWorld.scaleInPlace(0.5);
  16395. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  16396. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  16397. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  16398. this._worldMatrix = world;
  16399. };
  16400. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  16401. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  16402. };
  16403. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16404. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  16405. };
  16406. BoundingBox.prototype.intersectsPoint = function (point) {
  16407. var delta = -BABYLON.Epsilon;
  16408. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  16409. return false;
  16410. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  16411. return false;
  16412. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  16413. return false;
  16414. return true;
  16415. };
  16416. BoundingBox.prototype.intersectsSphere = function (sphere) {
  16417. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  16418. };
  16419. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  16420. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  16421. return false;
  16422. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  16423. return false;
  16424. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  16425. return false;
  16426. return true;
  16427. };
  16428. // Statics
  16429. BoundingBox.Intersects = function (box0, box1) {
  16430. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  16431. return false;
  16432. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  16433. return false;
  16434. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  16435. return false;
  16436. return true;
  16437. };
  16438. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  16439. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  16440. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  16441. return (num <= (sphereRadius * sphereRadius));
  16442. };
  16443. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  16444. for (var p = 0; p < 6; p++) {
  16445. for (var i = 0; i < 8; i++) {
  16446. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16447. return false;
  16448. }
  16449. }
  16450. }
  16451. return true;
  16452. };
  16453. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  16454. for (var p = 0; p < 6; p++) {
  16455. var inCount = 8;
  16456. for (var i = 0; i < 8; i++) {
  16457. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16458. --inCount;
  16459. }
  16460. else {
  16461. break;
  16462. }
  16463. }
  16464. if (inCount === 0)
  16465. return false;
  16466. }
  16467. return true;
  16468. };
  16469. return BoundingBox;
  16470. }());
  16471. BABYLON.BoundingBox = BoundingBox;
  16472. })(BABYLON || (BABYLON = {}));
  16473. //# sourceMappingURL=babylon.boundingBox.js.map
  16474. "use strict";
  16475. var BABYLON;
  16476. (function (BABYLON) {
  16477. var computeBoxExtents = function (axis, box) {
  16478. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  16479. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  16480. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  16481. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  16482. var r = r0 + r1 + r2;
  16483. return {
  16484. min: p - r,
  16485. max: p + r
  16486. };
  16487. };
  16488. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  16489. var axisOverlap = function (axis, box0, box1) {
  16490. var result0 = computeBoxExtents(axis, box0);
  16491. var result1 = computeBoxExtents(axis, box1);
  16492. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  16493. };
  16494. var BoundingInfo = /** @class */ (function () {
  16495. function BoundingInfo(minimum, maximum) {
  16496. this.minimum = minimum;
  16497. this.maximum = maximum;
  16498. this._isLocked = false;
  16499. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  16500. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  16501. }
  16502. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  16503. get: function () {
  16504. return this._isLocked;
  16505. },
  16506. set: function (value) {
  16507. this._isLocked = value;
  16508. },
  16509. enumerable: true,
  16510. configurable: true
  16511. });
  16512. // Methods
  16513. BoundingInfo.prototype.update = function (world) {
  16514. if (this._isLocked) {
  16515. return;
  16516. }
  16517. this.boundingBox._update(world);
  16518. this.boundingSphere._update(world);
  16519. };
  16520. /**
  16521. * Recreate the bounding info to be centered around a specific point given a specific extend.
  16522. * @param center New center of the bounding info
  16523. * @param extend New extend of the bounding info
  16524. */
  16525. BoundingInfo.prototype.centerOn = function (center, extend) {
  16526. this.minimum = center.subtract(extend);
  16527. this.maximum = center.add(extend);
  16528. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  16529. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  16530. return this;
  16531. };
  16532. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  16533. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  16534. return false;
  16535. return this.boundingBox.isInFrustum(frustumPlanes);
  16536. };
  16537. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  16538. /**
  16539. * Gets the world distance between the min and max points of the bounding box
  16540. */
  16541. get: function () {
  16542. var boundingBox = this.boundingBox;
  16543. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  16544. return size.length();
  16545. },
  16546. enumerable: true,
  16547. configurable: true
  16548. });
  16549. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16550. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  16551. };
  16552. BoundingInfo.prototype._checkCollision = function (collider) {
  16553. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  16554. };
  16555. BoundingInfo.prototype.intersectsPoint = function (point) {
  16556. if (!this.boundingSphere.centerWorld) {
  16557. return false;
  16558. }
  16559. if (!this.boundingSphere.intersectsPoint(point)) {
  16560. return false;
  16561. }
  16562. if (!this.boundingBox.intersectsPoint(point)) {
  16563. return false;
  16564. }
  16565. return true;
  16566. };
  16567. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  16568. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  16569. return false;
  16570. }
  16571. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  16572. return false;
  16573. }
  16574. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  16575. return false;
  16576. }
  16577. if (!precise) {
  16578. return true;
  16579. }
  16580. var box0 = this.boundingBox;
  16581. var box1 = boundingInfo.boundingBox;
  16582. if (!axisOverlap(box0.directions[0], box0, box1))
  16583. return false;
  16584. if (!axisOverlap(box0.directions[1], box0, box1))
  16585. return false;
  16586. if (!axisOverlap(box0.directions[2], box0, box1))
  16587. return false;
  16588. if (!axisOverlap(box1.directions[0], box0, box1))
  16589. return false;
  16590. if (!axisOverlap(box1.directions[1], box0, box1))
  16591. return false;
  16592. if (!axisOverlap(box1.directions[2], box0, box1))
  16593. return false;
  16594. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  16595. return false;
  16596. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  16597. return false;
  16598. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  16599. return false;
  16600. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  16601. return false;
  16602. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  16603. return false;
  16604. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  16605. return false;
  16606. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  16607. return false;
  16608. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  16609. return false;
  16610. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  16611. return false;
  16612. return true;
  16613. };
  16614. return BoundingInfo;
  16615. }());
  16616. BABYLON.BoundingInfo = BoundingInfo;
  16617. })(BABYLON || (BABYLON = {}));
  16618. //# sourceMappingURL=babylon.boundingInfo.js.map
  16619. "use strict";
  16620. var BABYLON;
  16621. (function (BABYLON) {
  16622. var TransformNode = /** @class */ (function (_super) {
  16623. __extends(TransformNode, _super);
  16624. function TransformNode(name, scene, isPure) {
  16625. if (scene === void 0) { scene = null; }
  16626. if (isPure === void 0) { isPure = true; }
  16627. var _this = _super.call(this, name, scene) || this;
  16628. _this._forward = new BABYLON.Vector3(0, 0, 1);
  16629. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  16630. _this._up = new BABYLON.Vector3(0, 1, 0);
  16631. _this._right = new BABYLON.Vector3(1, 0, 0);
  16632. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  16633. // Properties
  16634. _this._rotation = BABYLON.Vector3.Zero();
  16635. _this._scaling = BABYLON.Vector3.One();
  16636. _this._isDirty = false;
  16637. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  16638. _this.scalingDeterminant = 1;
  16639. _this.infiniteDistance = false;
  16640. _this.position = BABYLON.Vector3.Zero();
  16641. _this._localWorld = BABYLON.Matrix.Zero();
  16642. _this._worldMatrix = BABYLON.Matrix.Zero();
  16643. _this._worldMatrixDeterminant = 0;
  16644. _this._absolutePosition = BABYLON.Vector3.Zero();
  16645. _this._pivotMatrix = BABYLON.Matrix.Identity();
  16646. _this._postMultiplyPivotMatrix = false;
  16647. _this._isWorldMatrixFrozen = false;
  16648. /**
  16649. * An event triggered after the world matrix is updated
  16650. */
  16651. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  16652. _this._nonUniformScaling = false;
  16653. if (isPure) {
  16654. _this.getScene().addTransformNode(_this);
  16655. }
  16656. return _this;
  16657. }
  16658. /**
  16659. * Gets a string idenfifying the name of the class
  16660. * @returns "TransformNode" string
  16661. */
  16662. TransformNode.prototype.getClassName = function () {
  16663. return "TransformNode";
  16664. };
  16665. Object.defineProperty(TransformNode.prototype, "rotation", {
  16666. /**
  16667. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  16668. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  16669. * Default : (0.0, 0.0, 0.0)
  16670. */
  16671. get: function () {
  16672. return this._rotation;
  16673. },
  16674. set: function (newRotation) {
  16675. this._rotation = newRotation;
  16676. },
  16677. enumerable: true,
  16678. configurable: true
  16679. });
  16680. Object.defineProperty(TransformNode.prototype, "scaling", {
  16681. /**
  16682. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16683. * Default : (1.0, 1.0, 1.0)
  16684. */
  16685. get: function () {
  16686. return this._scaling;
  16687. },
  16688. /**
  16689. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16690. * Default : (1.0, 1.0, 1.0)
  16691. */
  16692. set: function (newScaling) {
  16693. this._scaling = newScaling;
  16694. },
  16695. enumerable: true,
  16696. configurable: true
  16697. });
  16698. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  16699. /**
  16700. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  16701. * It's null by default.
  16702. * 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)
  16703. */
  16704. get: function () {
  16705. return this._rotationQuaternion;
  16706. },
  16707. set: function (quaternion) {
  16708. this._rotationQuaternion = quaternion;
  16709. //reset the rotation vector.
  16710. if (quaternion && this.rotation.length()) {
  16711. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16712. }
  16713. },
  16714. enumerable: true,
  16715. configurable: true
  16716. });
  16717. Object.defineProperty(TransformNode.prototype, "forward", {
  16718. /**
  16719. * The forward direction of that transform in world space.
  16720. */
  16721. get: function () {
  16722. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  16723. },
  16724. enumerable: true,
  16725. configurable: true
  16726. });
  16727. Object.defineProperty(TransformNode.prototype, "up", {
  16728. /**
  16729. * The up direction of that transform in world space.
  16730. */
  16731. get: function () {
  16732. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  16733. },
  16734. enumerable: true,
  16735. configurable: true
  16736. });
  16737. Object.defineProperty(TransformNode.prototype, "right", {
  16738. /**
  16739. * The right direction of that transform in world space.
  16740. */
  16741. get: function () {
  16742. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  16743. },
  16744. enumerable: true,
  16745. configurable: true
  16746. });
  16747. /**
  16748. * Returns the latest update of the World matrix
  16749. * Returns a Matrix.
  16750. */
  16751. TransformNode.prototype.getWorldMatrix = function () {
  16752. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16753. this.computeWorldMatrix();
  16754. }
  16755. return this._worldMatrix;
  16756. };
  16757. /**
  16758. * Returns the latest update of the World matrix determinant.
  16759. */
  16760. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16761. return this._worldMatrixDeterminant;
  16762. };
  16763. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16764. /**
  16765. * Returns directly the latest state of the mesh World matrix.
  16766. * A Matrix is returned.
  16767. */
  16768. get: function () {
  16769. return this._worldMatrix;
  16770. },
  16771. enumerable: true,
  16772. configurable: true
  16773. });
  16774. /**
  16775. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16776. * Returns the TransformNode.
  16777. */
  16778. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16779. this._poseMatrix.copyFrom(matrix);
  16780. return this;
  16781. };
  16782. /**
  16783. * Returns the mesh Pose matrix.
  16784. * Returned object : Matrix
  16785. */
  16786. TransformNode.prototype.getPoseMatrix = function () {
  16787. return this._poseMatrix;
  16788. };
  16789. TransformNode.prototype._isSynchronized = function () {
  16790. if (this._isDirty) {
  16791. return false;
  16792. }
  16793. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  16794. return false;
  16795. if (this._cache.pivotMatrixUpdated) {
  16796. return false;
  16797. }
  16798. if (this.infiniteDistance) {
  16799. return false;
  16800. }
  16801. if (!this._cache.position.equals(this.position))
  16802. return false;
  16803. if (this.rotationQuaternion) {
  16804. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16805. return false;
  16806. }
  16807. if (!this._cache.rotation.equals(this.rotation))
  16808. return false;
  16809. if (!this._cache.scaling.equals(this.scaling))
  16810. return false;
  16811. return true;
  16812. };
  16813. TransformNode.prototype._initCache = function () {
  16814. _super.prototype._initCache.call(this);
  16815. this._cache.localMatrixUpdated = false;
  16816. this._cache.position = BABYLON.Vector3.Zero();
  16817. this._cache.scaling = BABYLON.Vector3.Zero();
  16818. this._cache.rotation = BABYLON.Vector3.Zero();
  16819. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16820. this._cache.billboardMode = -1;
  16821. };
  16822. TransformNode.prototype.markAsDirty = function (property) {
  16823. if (property === "rotation") {
  16824. this.rotationQuaternion = null;
  16825. }
  16826. this._currentRenderId = Number.MAX_VALUE;
  16827. this._isDirty = true;
  16828. return this;
  16829. };
  16830. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16831. /**
  16832. * Returns the current mesh absolute position.
  16833. * Retuns a Vector3.
  16834. */
  16835. get: function () {
  16836. return this._absolutePosition;
  16837. },
  16838. enumerable: true,
  16839. configurable: true
  16840. });
  16841. /**
  16842. * Sets a new matrix to apply before all other transformation
  16843. * @param matrix defines the transform matrix
  16844. * @returns the current TransformNode
  16845. */
  16846. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16847. return this.setPivotMatrix(matrix, false);
  16848. };
  16849. /**
  16850. * Sets a new pivot matrix to the current node
  16851. * @param matrix defines the new pivot matrix to use
  16852. * @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
  16853. * @returns the current TransformNode
  16854. */
  16855. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16856. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16857. this._pivotMatrix = matrix.clone();
  16858. this._cache.pivotMatrixUpdated = true;
  16859. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16860. if (this._postMultiplyPivotMatrix) {
  16861. if (!this._pivotMatrixInverse) {
  16862. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16863. }
  16864. else {
  16865. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16866. }
  16867. }
  16868. return this;
  16869. };
  16870. /**
  16871. * Returns the mesh pivot matrix.
  16872. * Default : Identity.
  16873. * A Matrix is returned.
  16874. */
  16875. TransformNode.prototype.getPivotMatrix = function () {
  16876. return this._pivotMatrix;
  16877. };
  16878. /**
  16879. * Prevents the World matrix to be computed any longer.
  16880. * Returns the TransformNode.
  16881. */
  16882. TransformNode.prototype.freezeWorldMatrix = function () {
  16883. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16884. this.computeWorldMatrix(true);
  16885. this._isWorldMatrixFrozen = true;
  16886. return this;
  16887. };
  16888. /**
  16889. * Allows back the World matrix computation.
  16890. * Returns the TransformNode.
  16891. */
  16892. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16893. this._isWorldMatrixFrozen = false;
  16894. this.computeWorldMatrix(true);
  16895. return this;
  16896. };
  16897. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16898. /**
  16899. * True if the World matrix has been frozen.
  16900. * Returns a boolean.
  16901. */
  16902. get: function () {
  16903. return this._isWorldMatrixFrozen;
  16904. },
  16905. enumerable: true,
  16906. configurable: true
  16907. });
  16908. /**
  16909. * Retuns the mesh absolute position in the World.
  16910. * Returns a Vector3.
  16911. */
  16912. TransformNode.prototype.getAbsolutePosition = function () {
  16913. this.computeWorldMatrix();
  16914. return this._absolutePosition;
  16915. };
  16916. /**
  16917. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16918. * Returns the TransformNode.
  16919. */
  16920. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16921. if (!absolutePosition) {
  16922. return this;
  16923. }
  16924. var absolutePositionX;
  16925. var absolutePositionY;
  16926. var absolutePositionZ;
  16927. if (absolutePosition.x === undefined) {
  16928. if (arguments.length < 3) {
  16929. return this;
  16930. }
  16931. absolutePositionX = arguments[0];
  16932. absolutePositionY = arguments[1];
  16933. absolutePositionZ = arguments[2];
  16934. }
  16935. else {
  16936. absolutePositionX = absolutePosition.x;
  16937. absolutePositionY = absolutePosition.y;
  16938. absolutePositionZ = absolutePosition.z;
  16939. }
  16940. if (this.parent) {
  16941. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16942. invertParentWorldMatrix.invert();
  16943. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16944. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16945. }
  16946. else {
  16947. this.position.x = absolutePositionX;
  16948. this.position.y = absolutePositionY;
  16949. this.position.z = absolutePositionZ;
  16950. }
  16951. return this;
  16952. };
  16953. /**
  16954. * Sets the mesh position in its local space.
  16955. * Returns the TransformNode.
  16956. */
  16957. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16958. this.computeWorldMatrix();
  16959. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16960. return this;
  16961. };
  16962. /**
  16963. * Returns the mesh position in the local space from the current World matrix values.
  16964. * Returns a new Vector3.
  16965. */
  16966. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16967. this.computeWorldMatrix();
  16968. var invLocalWorldMatrix = this._localWorld.clone();
  16969. invLocalWorldMatrix.invert();
  16970. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16971. };
  16972. /**
  16973. * Translates the mesh along the passed Vector3 in its local space.
  16974. * Returns the TransformNode.
  16975. */
  16976. TransformNode.prototype.locallyTranslate = function (vector3) {
  16977. this.computeWorldMatrix(true);
  16978. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16979. return this;
  16980. };
  16981. /**
  16982. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16983. * @param targetPoint the position (must be in same space as current mesh) to look at
  16984. * @param yawCor optional yaw (y-axis) correction in radians
  16985. * @param pitchCor optional pitch (x-axis) correction in radians
  16986. * @param rollCor optional roll (z-axis) correction in radians
  16987. * @param space the choosen space of the target
  16988. * @returns the TransformNode.
  16989. */
  16990. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16991. if (yawCor === void 0) { yawCor = 0; }
  16992. if (pitchCor === void 0) { pitchCor = 0; }
  16993. if (rollCor === void 0) { rollCor = 0; }
  16994. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16995. var dv = TransformNode._lookAtVectorCache;
  16996. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16997. targetPoint.subtractToRef(pos, dv);
  16998. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16999. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  17000. var pitch = Math.atan2(dv.y, len);
  17001. if (this.rotationQuaternion) {
  17002. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  17003. }
  17004. else {
  17005. this.rotation.x = pitch + pitchCor;
  17006. this.rotation.y = yaw + yawCor;
  17007. this.rotation.z = rollCor;
  17008. }
  17009. return this;
  17010. };
  17011. /**
  17012. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  17013. * This Vector3 is expressed in the World space.
  17014. */
  17015. TransformNode.prototype.getDirection = function (localAxis) {
  17016. var result = BABYLON.Vector3.Zero();
  17017. this.getDirectionToRef(localAxis, result);
  17018. return result;
  17019. };
  17020. /**
  17021. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  17022. * localAxis is expressed in the mesh local space.
  17023. * result is computed in the Wordl space from the mesh World matrix.
  17024. * Returns the TransformNode.
  17025. */
  17026. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  17027. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  17028. return this;
  17029. };
  17030. /**
  17031. * Sets a new pivot point to the current node
  17032. * @param point defines the new pivot point to use
  17033. * @param space defines if the point is in world or local space (local by default)
  17034. * @returns the current TransformNode
  17035. */
  17036. TransformNode.prototype.setPivotPoint = function (point, space) {
  17037. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  17038. if (this.getScene().getRenderId() == 0) {
  17039. this.computeWorldMatrix(true);
  17040. }
  17041. var wm = this.getWorldMatrix();
  17042. if (space == BABYLON.Space.WORLD) {
  17043. var tmat = BABYLON.Tmp.Matrix[0];
  17044. wm.invertToRef(tmat);
  17045. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  17046. }
  17047. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  17048. };
  17049. /**
  17050. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  17051. */
  17052. TransformNode.prototype.getPivotPoint = function () {
  17053. var point = BABYLON.Vector3.Zero();
  17054. this.getPivotPointToRef(point);
  17055. return point;
  17056. };
  17057. /**
  17058. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  17059. * Returns the TransformNode.
  17060. */
  17061. TransformNode.prototype.getPivotPointToRef = function (result) {
  17062. result.x = -this._pivotMatrix.m[12];
  17063. result.y = -this._pivotMatrix.m[13];
  17064. result.z = -this._pivotMatrix.m[14];
  17065. return this;
  17066. };
  17067. /**
  17068. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  17069. */
  17070. TransformNode.prototype.getAbsolutePivotPoint = function () {
  17071. var point = BABYLON.Vector3.Zero();
  17072. this.getAbsolutePivotPointToRef(point);
  17073. return point;
  17074. };
  17075. /**
  17076. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  17077. * Returns the TransformNode.
  17078. */
  17079. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  17080. result.x = this._pivotMatrix.m[12];
  17081. result.y = this._pivotMatrix.m[13];
  17082. result.z = this._pivotMatrix.m[14];
  17083. this.getPivotPointToRef(result);
  17084. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  17085. return this;
  17086. };
  17087. /**
  17088. * Defines the passed node as the parent of the current node.
  17089. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  17090. * Returns the TransformNode.
  17091. */
  17092. TransformNode.prototype.setParent = function (node) {
  17093. if (node === null) {
  17094. var rotation = BABYLON.Tmp.Quaternion[0];
  17095. var position = BABYLON.Tmp.Vector3[0];
  17096. var scale = BABYLON.Tmp.Vector3[1];
  17097. if (this.parent && this.parent.computeWorldMatrix) {
  17098. this.parent.computeWorldMatrix(true);
  17099. }
  17100. this.computeWorldMatrix(true);
  17101. this.getWorldMatrix().decompose(scale, rotation, position);
  17102. if (this.rotationQuaternion) {
  17103. this.rotationQuaternion.copyFrom(rotation);
  17104. }
  17105. else {
  17106. rotation.toEulerAnglesToRef(this.rotation);
  17107. }
  17108. this.scaling.x = scale.x;
  17109. this.scaling.y = scale.y;
  17110. this.scaling.z = scale.z;
  17111. this.position.x = position.x;
  17112. this.position.y = position.y;
  17113. this.position.z = position.z;
  17114. }
  17115. else {
  17116. var rotation = BABYLON.Tmp.Quaternion[0];
  17117. var position = BABYLON.Tmp.Vector3[0];
  17118. var scale = BABYLON.Tmp.Vector3[1];
  17119. var diffMatrix = BABYLON.Tmp.Matrix[0];
  17120. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  17121. this.computeWorldMatrix(true);
  17122. node.computeWorldMatrix(true);
  17123. node.getWorldMatrix().invertToRef(invParentMatrix);
  17124. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  17125. diffMatrix.decompose(scale, rotation, position);
  17126. if (this.rotationQuaternion) {
  17127. this.rotationQuaternion.copyFrom(rotation);
  17128. }
  17129. else {
  17130. rotation.toEulerAnglesToRef(this.rotation);
  17131. }
  17132. this.position.x = position.x;
  17133. this.position.y = position.y;
  17134. this.position.z = position.z;
  17135. this.scaling.x = scale.x;
  17136. this.scaling.y = scale.y;
  17137. this.scaling.z = scale.z;
  17138. }
  17139. this.parent = node;
  17140. return this;
  17141. };
  17142. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  17143. get: function () {
  17144. return this._nonUniformScaling;
  17145. },
  17146. enumerable: true,
  17147. configurable: true
  17148. });
  17149. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  17150. if (this._nonUniformScaling === value) {
  17151. return false;
  17152. }
  17153. this._nonUniformScaling = true;
  17154. return true;
  17155. };
  17156. /**
  17157. * Attach the current TransformNode to another TransformNode associated with a bone
  17158. * @param bone Bone affecting the TransformNode
  17159. * @param affectedTransformNode TransformNode associated with the bone
  17160. */
  17161. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  17162. this._transformToBoneReferal = affectedTransformNode;
  17163. this.parent = bone;
  17164. if (bone.getWorldMatrix().determinant() < 0) {
  17165. this.scalingDeterminant *= -1;
  17166. }
  17167. return this;
  17168. };
  17169. TransformNode.prototype.detachFromBone = function () {
  17170. if (!this.parent) {
  17171. return this;
  17172. }
  17173. if (this.parent.getWorldMatrix().determinant() < 0) {
  17174. this.scalingDeterminant *= -1;
  17175. }
  17176. this._transformToBoneReferal = null;
  17177. this.parent = null;
  17178. return this;
  17179. };
  17180. /**
  17181. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  17182. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  17183. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  17184. * The passed axis is also normalized.
  17185. * Returns the TransformNode.
  17186. */
  17187. TransformNode.prototype.rotate = function (axis, amount, space) {
  17188. axis.normalize();
  17189. if (!this.rotationQuaternion) {
  17190. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17191. this.rotation = BABYLON.Vector3.Zero();
  17192. }
  17193. var rotationQuaternion;
  17194. if (!space || space === BABYLON.Space.LOCAL) {
  17195. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  17196. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  17197. }
  17198. else {
  17199. if (this.parent) {
  17200. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  17201. invertParentWorldMatrix.invert();
  17202. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  17203. }
  17204. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  17205. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  17206. }
  17207. return this;
  17208. };
  17209. /**
  17210. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  17211. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  17212. * The passed axis is also normalized.
  17213. * Returns the TransformNode.
  17214. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  17215. */
  17216. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  17217. axis.normalize();
  17218. if (!this.rotationQuaternion) {
  17219. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17220. this.rotation.copyFromFloats(0, 0, 0);
  17221. }
  17222. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  17223. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  17224. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  17225. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  17226. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  17227. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  17228. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  17229. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  17230. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  17231. return this;
  17232. };
  17233. /**
  17234. * Translates the mesh along the axis vector for the passed distance in the given space.
  17235. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  17236. * Returns the TransformNode.
  17237. */
  17238. TransformNode.prototype.translate = function (axis, distance, space) {
  17239. var displacementVector = axis.scale(distance);
  17240. if (!space || space === BABYLON.Space.LOCAL) {
  17241. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  17242. this.setPositionWithLocalVector(tempV3);
  17243. }
  17244. else {
  17245. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  17246. }
  17247. return this;
  17248. };
  17249. /**
  17250. * Adds a rotation step to the mesh current rotation.
  17251. * x, y, z are Euler angles expressed in radians.
  17252. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  17253. * This means this rotation is made in the mesh local space only.
  17254. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  17255. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  17256. * ```javascript
  17257. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  17258. * ```
  17259. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  17260. * 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.
  17261. * Returns the TransformNode.
  17262. */
  17263. TransformNode.prototype.addRotation = function (x, y, z) {
  17264. var rotationQuaternion;
  17265. if (this.rotationQuaternion) {
  17266. rotationQuaternion = this.rotationQuaternion;
  17267. }
  17268. else {
  17269. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  17270. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  17271. }
  17272. var accumulation = BABYLON.Tmp.Quaternion[0];
  17273. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  17274. rotationQuaternion.multiplyInPlace(accumulation);
  17275. if (!this.rotationQuaternion) {
  17276. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  17277. }
  17278. return this;
  17279. };
  17280. /**
  17281. * Computes the mesh World matrix and returns it.
  17282. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  17283. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  17284. * If the parameter `force`is set to `true`, the actual computation is done.
  17285. * Returns the mesh World Matrix.
  17286. */
  17287. TransformNode.prototype.computeWorldMatrix = function (force) {
  17288. if (this._isWorldMatrixFrozen) {
  17289. return this._worldMatrix;
  17290. }
  17291. if (!force && this.isSynchronized(true)) {
  17292. this._currentRenderId = this.getScene().getRenderId();
  17293. return this._worldMatrix;
  17294. }
  17295. this._cache.position.copyFrom(this.position);
  17296. this._cache.scaling.copyFrom(this.scaling);
  17297. this._cache.pivotMatrixUpdated = false;
  17298. this._cache.billboardMode = this.billboardMode;
  17299. this._currentRenderId = this.getScene().getRenderId();
  17300. this._childRenderId = this.getScene().getRenderId();
  17301. this._isDirty = false;
  17302. // Scaling
  17303. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  17304. // Rotation
  17305. //rotate, if quaternion is set and rotation was used
  17306. if (this.rotationQuaternion) {
  17307. var len = this.rotation.length();
  17308. if (len) {
  17309. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  17310. this.rotation.copyFromFloats(0, 0, 0);
  17311. }
  17312. }
  17313. if (this.rotationQuaternion) {
  17314. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  17315. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17316. }
  17317. else {
  17318. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  17319. this._cache.rotation.copyFrom(this.rotation);
  17320. }
  17321. // Translation
  17322. var camera = this.getScene().activeCamera;
  17323. if (this.infiniteDistance && !this.parent && camera) {
  17324. var cameraWorldMatrix = camera.getWorldMatrix();
  17325. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  17326. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  17327. }
  17328. else {
  17329. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  17330. }
  17331. // Composing transformations
  17332. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  17333. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17334. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  17335. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  17336. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  17337. // Need to decompose each rotation here
  17338. var currentPosition = BABYLON.Tmp.Vector3[3];
  17339. if (this.parent && this.parent.getWorldMatrix) {
  17340. if (this._transformToBoneReferal) {
  17341. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17342. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  17343. }
  17344. else {
  17345. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  17346. }
  17347. }
  17348. else {
  17349. currentPosition.copyFrom(this.position);
  17350. }
  17351. currentPosition.subtractInPlace(camera.globalPosition);
  17352. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  17353. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  17354. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  17355. }
  17356. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  17357. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  17358. }
  17359. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  17360. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  17361. }
  17362. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  17363. }
  17364. else {
  17365. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  17366. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  17367. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  17368. }
  17369. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  17370. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17371. }
  17372. // Local world
  17373. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  17374. // Parent
  17375. if (this.parent && this.parent.getWorldMatrix) {
  17376. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  17377. if (this._transformToBoneReferal) {
  17378. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17379. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  17380. }
  17381. else {
  17382. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  17383. }
  17384. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  17385. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  17386. this._worldMatrix.copyFrom(this._localWorld);
  17387. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  17388. }
  17389. else {
  17390. if (this._transformToBoneReferal) {
  17391. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17392. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  17393. }
  17394. else {
  17395. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  17396. }
  17397. }
  17398. this._markSyncedWithParent();
  17399. }
  17400. else {
  17401. this._worldMatrix.copyFrom(this._localWorld);
  17402. }
  17403. // Post multiply inverse of pivotMatrix
  17404. if (this._postMultiplyPivotMatrix) {
  17405. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  17406. }
  17407. // Normal matrix
  17408. if (this.scaling.isNonUniform) {
  17409. this._updateNonUniformScalingState(true);
  17410. }
  17411. else if (this.parent && this.parent._nonUniformScaling) {
  17412. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  17413. }
  17414. else {
  17415. this._updateNonUniformScalingState(false);
  17416. }
  17417. this._afterComputeWorldMatrix();
  17418. // Absolute position
  17419. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  17420. // Callbacks
  17421. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  17422. if (!this._poseMatrix) {
  17423. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  17424. }
  17425. // Cache the determinant
  17426. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  17427. return this._worldMatrix;
  17428. };
  17429. TransformNode.prototype._afterComputeWorldMatrix = function () {
  17430. };
  17431. /**
  17432. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  17433. * @param func: callback function to add
  17434. *
  17435. * Returns the TransformNode.
  17436. */
  17437. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  17438. this.onAfterWorldMatrixUpdateObservable.add(func);
  17439. return this;
  17440. };
  17441. /**
  17442. * Removes a registered callback function.
  17443. * Returns the TransformNode.
  17444. */
  17445. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  17446. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  17447. return this;
  17448. };
  17449. /**
  17450. * Clone the current transform node
  17451. * Returns the new transform node
  17452. * @param name Name of the new clone
  17453. * @param newParent New parent for the clone
  17454. * @param doNotCloneChildren Do not clone children hierarchy
  17455. */
  17456. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17457. var _this = this;
  17458. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  17459. result.name = name;
  17460. result.id = name;
  17461. if (newParent) {
  17462. result.parent = newParent;
  17463. }
  17464. if (!doNotCloneChildren) {
  17465. // Children
  17466. var directDescendants = this.getDescendants(true);
  17467. for (var index = 0; index < directDescendants.length; index++) {
  17468. var child = directDescendants[index];
  17469. if (child.clone) {
  17470. child.clone(name + "." + child.name, result);
  17471. }
  17472. }
  17473. }
  17474. return result;
  17475. };
  17476. TransformNode.prototype.serialize = function (currentSerializationObject) {
  17477. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  17478. serializationObject.type = this.getClassName();
  17479. // Parent
  17480. if (this.parent) {
  17481. serializationObject.parentId = this.parent.id;
  17482. }
  17483. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  17484. serializationObject.tags = BABYLON.Tags.GetTags(this);
  17485. }
  17486. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  17487. serializationObject.isEnabled = this.isEnabled();
  17488. // Parent
  17489. if (this.parent) {
  17490. serializationObject.parentId = this.parent.id;
  17491. }
  17492. return serializationObject;
  17493. };
  17494. // Statics
  17495. /**
  17496. * Returns a new TransformNode object parsed from the source provided.
  17497. * The parameter `parsedMesh` is the source.
  17498. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  17499. */
  17500. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  17501. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  17502. if (BABYLON.Tags) {
  17503. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  17504. }
  17505. if (parsedTransformNode.localMatrix) {
  17506. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  17507. }
  17508. else if (parsedTransformNode.pivotMatrix) {
  17509. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  17510. }
  17511. transformNode.setEnabled(parsedTransformNode.isEnabled);
  17512. // Parent
  17513. if (parsedTransformNode.parentId) {
  17514. transformNode._waitingParentId = parsedTransformNode.parentId;
  17515. }
  17516. return transformNode;
  17517. };
  17518. /**
  17519. * Releases resources associated with this transform node.
  17520. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17521. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17522. */
  17523. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17524. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17525. // Animations
  17526. this.getScene().stopAnimation(this);
  17527. // Remove from scene
  17528. this.getScene().removeTransformNode(this);
  17529. this.onAfterWorldMatrixUpdateObservable.clear();
  17530. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  17531. };
  17532. // Statics
  17533. TransformNode.BILLBOARDMODE_NONE = 0;
  17534. TransformNode.BILLBOARDMODE_X = 1;
  17535. TransformNode.BILLBOARDMODE_Y = 2;
  17536. TransformNode.BILLBOARDMODE_Z = 4;
  17537. TransformNode.BILLBOARDMODE_ALL = 7;
  17538. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  17539. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  17540. __decorate([
  17541. BABYLON.serializeAsVector3()
  17542. ], TransformNode.prototype, "_rotation", void 0);
  17543. __decorate([
  17544. BABYLON.serializeAsQuaternion()
  17545. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  17546. __decorate([
  17547. BABYLON.serializeAsVector3()
  17548. ], TransformNode.prototype, "_scaling", void 0);
  17549. __decorate([
  17550. BABYLON.serialize()
  17551. ], TransformNode.prototype, "billboardMode", void 0);
  17552. __decorate([
  17553. BABYLON.serialize()
  17554. ], TransformNode.prototype, "scalingDeterminant", void 0);
  17555. __decorate([
  17556. BABYLON.serialize()
  17557. ], TransformNode.prototype, "infiniteDistance", void 0);
  17558. __decorate([
  17559. BABYLON.serializeAsVector3()
  17560. ], TransformNode.prototype, "position", void 0);
  17561. return TransformNode;
  17562. }(BABYLON.Node));
  17563. BABYLON.TransformNode = TransformNode;
  17564. })(BABYLON || (BABYLON = {}));
  17565. //# sourceMappingURL=babylon.transformNode.js.map
  17566. "use strict";
  17567. var BABYLON;
  17568. (function (BABYLON) {
  17569. var AbstractMesh = /** @class */ (function (_super) {
  17570. __extends(AbstractMesh, _super);
  17571. // Constructor
  17572. function AbstractMesh(name, scene) {
  17573. if (scene === void 0) { scene = null; }
  17574. var _this = _super.call(this, name, scene, false) || this;
  17575. _this._facetNb = 0; // facet number
  17576. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  17577. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  17578. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  17579. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  17580. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  17581. _this._subDiv = {
  17582. max: 1,
  17583. X: 1,
  17584. Y: 1,
  17585. Z: 1
  17586. };
  17587. _this._facetDepthSort = false; // is the facet depth sort to be computed
  17588. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  17589. // Events
  17590. /**
  17591. * An event triggered when this mesh collides with another one
  17592. */
  17593. _this.onCollideObservable = new BABYLON.Observable();
  17594. /**
  17595. * An event triggered when the collision's position changes
  17596. */
  17597. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  17598. /**
  17599. * An event triggered when material is changed
  17600. */
  17601. _this.onMaterialChangedObservable = new BABYLON.Observable();
  17602. // Properties
  17603. _this.definedFacingForward = true; // orientation for POV movement & rotation
  17604. /**
  17605. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  17606. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  17607. * or
  17608. * 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.
  17609. * for more info check WebGl documentations
  17610. */
  17611. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  17612. /**
  17613. * 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:
  17614. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  17615. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  17616. * 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.
  17617. */
  17618. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  17619. /**
  17620. * 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.
  17621. * The default value is -1 which means don't break the query and wait till the result.
  17622. */
  17623. _this.occlusionRetryCount = -1;
  17624. _this._occlusionInternalRetryCounter = 0;
  17625. _this._isOccluded = false;
  17626. _this._isOcclusionQueryInProgress = false;
  17627. _this._visibility = 1.0;
  17628. _this.alphaIndex = Number.MAX_VALUE;
  17629. _this.isVisible = true;
  17630. _this.isPickable = true;
  17631. _this.showBoundingBox = false;
  17632. _this.showSubMeshesBoundingBox = false;
  17633. _this.isBlocker = false;
  17634. _this.enablePointerMoveEvents = false;
  17635. _this.renderingGroupId = 0;
  17636. _this._receiveShadows = false;
  17637. _this.renderOutline = false;
  17638. _this.outlineColor = BABYLON.Color3.Red();
  17639. _this.outlineWidth = 0.02;
  17640. _this.renderOverlay = false;
  17641. _this.overlayColor = BABYLON.Color3.Red();
  17642. _this.overlayAlpha = 0.5;
  17643. _this._hasVertexAlpha = false;
  17644. _this._useVertexColors = true;
  17645. _this._computeBonesUsingShaders = true;
  17646. _this._numBoneInfluencers = 4;
  17647. _this._applyFog = true;
  17648. _this.useOctreeForRenderingSelection = true;
  17649. _this.useOctreeForPicking = true;
  17650. _this.useOctreeForCollisions = true;
  17651. _this._layerMask = 0x0FFFFFFF;
  17652. /**
  17653. * True if the mesh must be rendered in any case.
  17654. */
  17655. _this.alwaysSelectAsActiveMesh = false;
  17656. /**
  17657. * This scene's action manager
  17658. */
  17659. _this.actionManager = null;
  17660. // Physics
  17661. _this.physicsImpostor = null;
  17662. // Collisions
  17663. _this._checkCollisions = false;
  17664. _this._collisionMask = -1;
  17665. _this._collisionGroup = -1;
  17666. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17667. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  17668. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17669. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17670. // Edges
  17671. _this.edgesWidth = 1;
  17672. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  17673. // Cache
  17674. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  17675. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  17676. _this._renderId = 0;
  17677. _this._intersectionsInProgress = new Array();
  17678. _this._unIndexed = false;
  17679. _this._lightSources = new Array();
  17680. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17681. if (collidedMesh === void 0) { collidedMesh = null; }
  17682. //TODO move this to the collision coordinator!
  17683. if (_this.getScene().workerCollisions)
  17684. newPosition.multiplyInPlace(_this._collider._radius);
  17685. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  17686. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  17687. _this.position.addInPlace(_this._diffPositionForCollisions);
  17688. }
  17689. if (collidedMesh) {
  17690. _this.onCollideObservable.notifyObservers(collidedMesh);
  17691. }
  17692. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  17693. };
  17694. _this.getScene().addMesh(_this);
  17695. _this._resyncLightSources();
  17696. return _this;
  17697. }
  17698. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  17699. get: function () {
  17700. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  17701. },
  17702. enumerable: true,
  17703. configurable: true
  17704. });
  17705. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  17706. get: function () {
  17707. return BABYLON.TransformNode.BILLBOARDMODE_X;
  17708. },
  17709. enumerable: true,
  17710. configurable: true
  17711. });
  17712. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  17713. get: function () {
  17714. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  17715. },
  17716. enumerable: true,
  17717. configurable: true
  17718. });
  17719. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  17720. get: function () {
  17721. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  17722. },
  17723. enumerable: true,
  17724. configurable: true
  17725. });
  17726. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17727. get: function () {
  17728. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17729. },
  17730. enumerable: true,
  17731. configurable: true
  17732. });
  17733. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17734. /**
  17735. * Read-only : the number of facets in the mesh
  17736. */
  17737. get: function () {
  17738. return this._facetNb;
  17739. },
  17740. enumerable: true,
  17741. configurable: true
  17742. });
  17743. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17744. /**
  17745. * The number (integer) of subdivisions per axis in the partioning space
  17746. */
  17747. get: function () {
  17748. return this._partitioningSubdivisions;
  17749. },
  17750. set: function (nb) {
  17751. this._partitioningSubdivisions = nb;
  17752. },
  17753. enumerable: true,
  17754. configurable: true
  17755. });
  17756. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17757. /**
  17758. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17759. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17760. */
  17761. get: function () {
  17762. return this._partitioningBBoxRatio;
  17763. },
  17764. set: function (ratio) {
  17765. this._partitioningBBoxRatio = ratio;
  17766. },
  17767. enumerable: true,
  17768. configurable: true
  17769. });
  17770. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17771. /**
  17772. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17773. * Works only for updatable meshes.
  17774. * Doesn't work with multi-materials.
  17775. */
  17776. get: function () {
  17777. return this._facetDepthSort;
  17778. },
  17779. set: function (sort) {
  17780. this._facetDepthSort = sort;
  17781. },
  17782. enumerable: true,
  17783. configurable: true
  17784. });
  17785. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17786. /**
  17787. * The location (Vector3) where the facet depth sort must be computed from.
  17788. * By default, the active camera position.
  17789. * Used only when facet depth sort is enabled.
  17790. */
  17791. get: function () {
  17792. return this._facetDepthSortFrom;
  17793. },
  17794. set: function (location) {
  17795. this._facetDepthSortFrom = location;
  17796. },
  17797. enumerable: true,
  17798. configurable: true
  17799. });
  17800. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17801. /**
  17802. * Read-only boolean : is the feature facetData enabled ?
  17803. */
  17804. get: function () {
  17805. return this._facetDataEnabled;
  17806. },
  17807. enumerable: true,
  17808. configurable: true
  17809. });
  17810. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17811. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17812. return false;
  17813. }
  17814. this._markSubMeshesAsMiscDirty();
  17815. return true;
  17816. };
  17817. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17818. set: function (callback) {
  17819. if (this._onCollideObserver) {
  17820. this.onCollideObservable.remove(this._onCollideObserver);
  17821. }
  17822. this._onCollideObserver = this.onCollideObservable.add(callback);
  17823. },
  17824. enumerable: true,
  17825. configurable: true
  17826. });
  17827. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17828. set: function (callback) {
  17829. if (this._onCollisionPositionChangeObserver) {
  17830. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17831. }
  17832. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17833. },
  17834. enumerable: true,
  17835. configurable: true
  17836. });
  17837. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17838. /**
  17839. * Property isOccluded : 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.
  17840. */
  17841. get: function () {
  17842. return this._isOccluded;
  17843. },
  17844. set: function (value) {
  17845. this._isOccluded = value;
  17846. },
  17847. enumerable: true,
  17848. configurable: true
  17849. });
  17850. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17851. /**
  17852. * Flag to check the progress status of the query
  17853. */
  17854. get: function () {
  17855. return this._isOcclusionQueryInProgress;
  17856. },
  17857. enumerable: true,
  17858. configurable: true
  17859. });
  17860. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17861. /**
  17862. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17863. */
  17864. get: function () {
  17865. return this._visibility;
  17866. },
  17867. /**
  17868. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17869. */
  17870. set: function (value) {
  17871. if (this._visibility === value) {
  17872. return;
  17873. }
  17874. this._visibility = value;
  17875. this._markSubMeshesAsMiscDirty();
  17876. },
  17877. enumerable: true,
  17878. configurable: true
  17879. });
  17880. Object.defineProperty(AbstractMesh.prototype, "material", {
  17881. get: function () {
  17882. return this._material;
  17883. },
  17884. set: function (value) {
  17885. if (this._material === value) {
  17886. return;
  17887. }
  17888. this._material = value;
  17889. if (this.onMaterialChangedObservable.hasObservers) {
  17890. this.onMaterialChangedObservable.notifyObservers(this);
  17891. }
  17892. if (!this.subMeshes) {
  17893. return;
  17894. }
  17895. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17896. var subMesh = _a[_i];
  17897. subMesh.setEffect(null);
  17898. }
  17899. },
  17900. enumerable: true,
  17901. configurable: true
  17902. });
  17903. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17904. get: function () {
  17905. return this._receiveShadows;
  17906. },
  17907. set: function (value) {
  17908. if (this._receiveShadows === value) {
  17909. return;
  17910. }
  17911. this._receiveShadows = value;
  17912. this._markSubMeshesAsLightDirty();
  17913. },
  17914. enumerable: true,
  17915. configurable: true
  17916. });
  17917. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17918. get: function () {
  17919. return this._hasVertexAlpha;
  17920. },
  17921. set: function (value) {
  17922. if (this._hasVertexAlpha === value) {
  17923. return;
  17924. }
  17925. this._hasVertexAlpha = value;
  17926. this._markSubMeshesAsAttributesDirty();
  17927. this._markSubMeshesAsMiscDirty();
  17928. },
  17929. enumerable: true,
  17930. configurable: true
  17931. });
  17932. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17933. get: function () {
  17934. return this._useVertexColors;
  17935. },
  17936. set: function (value) {
  17937. if (this._useVertexColors === value) {
  17938. return;
  17939. }
  17940. this._useVertexColors = value;
  17941. this._markSubMeshesAsAttributesDirty();
  17942. },
  17943. enumerable: true,
  17944. configurable: true
  17945. });
  17946. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17947. get: function () {
  17948. return this._computeBonesUsingShaders;
  17949. },
  17950. set: function (value) {
  17951. if (this._computeBonesUsingShaders === value) {
  17952. return;
  17953. }
  17954. this._computeBonesUsingShaders = value;
  17955. this._markSubMeshesAsAttributesDirty();
  17956. },
  17957. enumerable: true,
  17958. configurable: true
  17959. });
  17960. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17961. get: function () {
  17962. return this._numBoneInfluencers;
  17963. },
  17964. set: function (value) {
  17965. if (this._numBoneInfluencers === value) {
  17966. return;
  17967. }
  17968. this._numBoneInfluencers = value;
  17969. this._markSubMeshesAsAttributesDirty();
  17970. },
  17971. enumerable: true,
  17972. configurable: true
  17973. });
  17974. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17975. get: function () {
  17976. return this._applyFog;
  17977. },
  17978. set: function (value) {
  17979. if (this._applyFog === value) {
  17980. return;
  17981. }
  17982. this._applyFog = value;
  17983. this._markSubMeshesAsMiscDirty();
  17984. },
  17985. enumerable: true,
  17986. configurable: true
  17987. });
  17988. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17989. get: function () {
  17990. return this._layerMask;
  17991. },
  17992. set: function (value) {
  17993. if (value === this._layerMask) {
  17994. return;
  17995. }
  17996. this._layerMask = value;
  17997. this._resyncLightSources();
  17998. },
  17999. enumerable: true,
  18000. configurable: true
  18001. });
  18002. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  18003. get: function () {
  18004. return this._collisionMask;
  18005. },
  18006. set: function (mask) {
  18007. this._collisionMask = !isNaN(mask) ? mask : -1;
  18008. },
  18009. enumerable: true,
  18010. configurable: true
  18011. });
  18012. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  18013. get: function () {
  18014. return this._collisionGroup;
  18015. },
  18016. set: function (mask) {
  18017. this._collisionGroup = !isNaN(mask) ? mask : -1;
  18018. },
  18019. enumerable: true,
  18020. configurable: true
  18021. });
  18022. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  18023. get: function () {
  18024. return null;
  18025. },
  18026. enumerable: true,
  18027. configurable: true
  18028. });
  18029. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  18030. get: function () {
  18031. return this._skeleton;
  18032. },
  18033. set: function (value) {
  18034. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  18035. this._skeleton._unregisterMeshWithPoseMatrix(this);
  18036. }
  18037. if (value && value.needInitialSkinMatrix) {
  18038. value._registerMeshWithPoseMatrix(this);
  18039. }
  18040. this._skeleton = value;
  18041. if (!this._skeleton) {
  18042. this._bonesTransformMatrices = null;
  18043. }
  18044. this._markSubMeshesAsAttributesDirty();
  18045. },
  18046. enumerable: true,
  18047. configurable: true
  18048. });
  18049. /**
  18050. * Returns the string "AbstractMesh"
  18051. */
  18052. AbstractMesh.prototype.getClassName = function () {
  18053. return "AbstractMesh";
  18054. };
  18055. /**
  18056. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  18057. */
  18058. AbstractMesh.prototype.toString = function (fullDetails) {
  18059. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  18060. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  18061. if (this._skeleton) {
  18062. ret += ", skeleton: " + this._skeleton.name;
  18063. }
  18064. if (fullDetails) {
  18065. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  18066. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  18067. }
  18068. return ret;
  18069. };
  18070. AbstractMesh.prototype._rebuild = function () {
  18071. if (this._occlusionQuery) {
  18072. this._occlusionQuery = null;
  18073. }
  18074. if (this._edgesRenderer) {
  18075. this._edgesRenderer._rebuild();
  18076. }
  18077. if (!this.subMeshes) {
  18078. return;
  18079. }
  18080. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18081. var subMesh = _a[_i];
  18082. subMesh._rebuild();
  18083. }
  18084. };
  18085. AbstractMesh.prototype._resyncLightSources = function () {
  18086. this._lightSources.length = 0;
  18087. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  18088. var light = _a[_i];
  18089. if (!light.isEnabled()) {
  18090. continue;
  18091. }
  18092. if (light.canAffectMesh(this)) {
  18093. this._lightSources.push(light);
  18094. }
  18095. }
  18096. this._markSubMeshesAsLightDirty();
  18097. };
  18098. AbstractMesh.prototype._resyncLighSource = function (light) {
  18099. var isIn = light.isEnabled() && light.canAffectMesh(this);
  18100. var index = this._lightSources.indexOf(light);
  18101. if (index === -1) {
  18102. if (!isIn) {
  18103. return;
  18104. }
  18105. this._lightSources.push(light);
  18106. }
  18107. else {
  18108. if (isIn) {
  18109. return;
  18110. }
  18111. this._lightSources.splice(index, 1);
  18112. }
  18113. this._markSubMeshesAsLightDirty();
  18114. };
  18115. AbstractMesh.prototype._removeLightSource = function (light) {
  18116. var index = this._lightSources.indexOf(light);
  18117. if (index === -1) {
  18118. return;
  18119. }
  18120. this._lightSources.splice(index, 1);
  18121. this._markSubMeshesAsLightDirty();
  18122. };
  18123. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  18124. if (!this.subMeshes) {
  18125. return;
  18126. }
  18127. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18128. var subMesh = _a[_i];
  18129. if (subMesh._materialDefines) {
  18130. func(subMesh._materialDefines);
  18131. }
  18132. }
  18133. };
  18134. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  18135. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  18136. };
  18137. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  18138. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  18139. };
  18140. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  18141. if (!this.subMeshes) {
  18142. return;
  18143. }
  18144. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18145. var subMesh = _a[_i];
  18146. var material = subMesh.getMaterial();
  18147. if (material) {
  18148. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  18149. }
  18150. }
  18151. };
  18152. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  18153. /**
  18154. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18155. * Default : (1.0, 1.0, 1.0)
  18156. */
  18157. get: function () {
  18158. return this._scaling;
  18159. },
  18160. /**
  18161. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18162. * Default : (1.0, 1.0, 1.0)
  18163. */
  18164. set: function (newScaling) {
  18165. this._scaling = newScaling;
  18166. if (this.physicsImpostor) {
  18167. this.physicsImpostor.forceUpdate();
  18168. }
  18169. },
  18170. enumerable: true,
  18171. configurable: true
  18172. });
  18173. // Methods
  18174. /**
  18175. * Disables the mesh edger rendering mode.
  18176. * Returns the AbstractMesh.
  18177. */
  18178. AbstractMesh.prototype.disableEdgesRendering = function () {
  18179. if (this._edgesRenderer) {
  18180. this._edgesRenderer.dispose();
  18181. this._edgesRenderer = null;
  18182. }
  18183. return this;
  18184. };
  18185. /**
  18186. * Enables the edge rendering mode on the mesh.
  18187. * This mode makes the mesh edges visible.
  18188. * Returns the AbstractMesh.
  18189. */
  18190. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  18191. if (epsilon === void 0) { epsilon = 0.95; }
  18192. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  18193. this.disableEdgesRendering();
  18194. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  18195. return this;
  18196. };
  18197. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  18198. /**
  18199. * Returns true if the mesh is blocked. Used by the class Mesh.
  18200. * Returns the boolean `false` by default.
  18201. */
  18202. get: function () {
  18203. return false;
  18204. },
  18205. enumerable: true,
  18206. configurable: true
  18207. });
  18208. /**
  18209. * Returns the mesh itself by default, used by the class Mesh.
  18210. * Returned type : AbstractMesh
  18211. */
  18212. AbstractMesh.prototype.getLOD = function (camera) {
  18213. return this;
  18214. };
  18215. /**
  18216. * Returns 0 by default, used by the class Mesh.
  18217. * Returns an integer.
  18218. */
  18219. AbstractMesh.prototype.getTotalVertices = function () {
  18220. return 0;
  18221. };
  18222. /**
  18223. * Returns null by default, used by the class Mesh.
  18224. * Returned type : integer array
  18225. */
  18226. AbstractMesh.prototype.getIndices = function () {
  18227. return null;
  18228. };
  18229. /**
  18230. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  18231. * Returned type : float array or Float32Array
  18232. */
  18233. AbstractMesh.prototype.getVerticesData = function (kind) {
  18234. return null;
  18235. };
  18236. /**
  18237. * Sets the vertex data of the mesh geometry for the requested `kind`.
  18238. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  18239. * The `data` are either a numeric array either a Float32Array.
  18240. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  18241. * 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).
  18242. * Note that a new underlying VertexBuffer object is created each call.
  18243. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  18244. *
  18245. * Possible `kind` values :
  18246. * - BABYLON.VertexBuffer.PositionKind
  18247. * - BABYLON.VertexBuffer.UVKind
  18248. * - BABYLON.VertexBuffer.UV2Kind
  18249. * - BABYLON.VertexBuffer.UV3Kind
  18250. * - BABYLON.VertexBuffer.UV4Kind
  18251. * - BABYLON.VertexBuffer.UV5Kind
  18252. * - BABYLON.VertexBuffer.UV6Kind
  18253. * - BABYLON.VertexBuffer.ColorKind
  18254. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18255. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18256. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18257. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18258. *
  18259. * Returns the Mesh.
  18260. */
  18261. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  18262. return this;
  18263. };
  18264. /**
  18265. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  18266. * If the mesh has no geometry, it is simply returned as it is.
  18267. * The `data` are either a numeric array either a Float32Array.
  18268. * No new underlying VertexBuffer object is created.
  18269. * 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.
  18270. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  18271. *
  18272. * Possible `kind` values :
  18273. * - BABYLON.VertexBuffer.PositionKind
  18274. * - BABYLON.VertexBuffer.UVKind
  18275. * - BABYLON.VertexBuffer.UV2Kind
  18276. * - BABYLON.VertexBuffer.UV3Kind
  18277. * - BABYLON.VertexBuffer.UV4Kind
  18278. * - BABYLON.VertexBuffer.UV5Kind
  18279. * - BABYLON.VertexBuffer.UV6Kind
  18280. * - BABYLON.VertexBuffer.ColorKind
  18281. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18282. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18283. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18284. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18285. *
  18286. * Returns the Mesh.
  18287. */
  18288. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  18289. return this;
  18290. };
  18291. /**
  18292. * Sets the mesh indices.
  18293. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  18294. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  18295. * This method creates a new index buffer each call.
  18296. * Returns the Mesh.
  18297. */
  18298. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  18299. return this;
  18300. };
  18301. /** Returns false by default, used by the class Mesh.
  18302. * Returns a boolean
  18303. */
  18304. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  18305. return false;
  18306. };
  18307. /**
  18308. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  18309. * Returns a BoundingInfo
  18310. */
  18311. AbstractMesh.prototype.getBoundingInfo = function () {
  18312. if (this._masterMesh) {
  18313. return this._masterMesh.getBoundingInfo();
  18314. }
  18315. if (!this._boundingInfo) {
  18316. // this._boundingInfo is being created here
  18317. this._updateBoundingInfo();
  18318. }
  18319. // cannot be null.
  18320. return this._boundingInfo;
  18321. };
  18322. /**
  18323. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  18324. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  18325. */
  18326. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  18327. if (includeDescendants === void 0) { includeDescendants = true; }
  18328. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  18329. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  18330. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  18331. if (maxDimension === 0) {
  18332. return this;
  18333. }
  18334. var scale = 1 / maxDimension;
  18335. this.scaling.scaleInPlace(scale);
  18336. return this;
  18337. };
  18338. /**
  18339. * Sets a mesh new object BoundingInfo.
  18340. * Returns the AbstractMesh.
  18341. */
  18342. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  18343. this._boundingInfo = boundingInfo;
  18344. return this;
  18345. };
  18346. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  18347. get: function () {
  18348. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  18349. },
  18350. enumerable: true,
  18351. configurable: true
  18352. });
  18353. AbstractMesh.prototype._preActivate = function () {
  18354. };
  18355. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18356. };
  18357. AbstractMesh.prototype._activate = function (renderId) {
  18358. this._renderId = renderId;
  18359. };
  18360. /**
  18361. * Returns the latest update of the World matrix
  18362. * Returns a Matrix.
  18363. */
  18364. AbstractMesh.prototype.getWorldMatrix = function () {
  18365. if (this._masterMesh) {
  18366. return this._masterMesh.getWorldMatrix();
  18367. }
  18368. return _super.prototype.getWorldMatrix.call(this);
  18369. };
  18370. /**
  18371. * Returns the latest update of the World matrix determinant.
  18372. */
  18373. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  18374. if (this._masterMesh) {
  18375. return this._masterMesh._getWorldMatrixDeterminant();
  18376. }
  18377. return _super.prototype._getWorldMatrixDeterminant.call(this);
  18378. };
  18379. // ================================== Point of View Movement =================================
  18380. /**
  18381. * Perform relative position change from the point of view of behind the front of the mesh.
  18382. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18383. * Supports definition of mesh facing forward or backward.
  18384. * @param {number} amountRight
  18385. * @param {number} amountUp
  18386. * @param {number} amountForward
  18387. *
  18388. * Returns the AbstractMesh.
  18389. */
  18390. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  18391. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  18392. return this;
  18393. };
  18394. /**
  18395. * Calculate relative position change from the point of view of behind the front of the mesh.
  18396. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18397. * Supports definition of mesh facing forward or backward.
  18398. * @param {number} amountRight
  18399. * @param {number} amountUp
  18400. * @param {number} amountForward
  18401. *
  18402. * Returns a new Vector3.
  18403. */
  18404. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  18405. var rotMatrix = new BABYLON.Matrix();
  18406. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18407. rotQuaternion.toRotationMatrix(rotMatrix);
  18408. var translationDelta = BABYLON.Vector3.Zero();
  18409. var defForwardMult = this.definedFacingForward ? -1 : 1;
  18410. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  18411. return translationDelta;
  18412. };
  18413. // ================================== Point of View Rotation =================================
  18414. /**
  18415. * Perform relative rotation change from the point of view of behind the front of the mesh.
  18416. * Supports definition of mesh facing forward or backward.
  18417. * @param {number} flipBack
  18418. * @param {number} twirlClockwise
  18419. * @param {number} tiltRight
  18420. *
  18421. * Returns the AbstractMesh.
  18422. */
  18423. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18424. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  18425. return this;
  18426. };
  18427. /**
  18428. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  18429. * Supports definition of mesh facing forward or backward.
  18430. * @param {number} flipBack
  18431. * @param {number} twirlClockwise
  18432. * @param {number} tiltRight
  18433. *
  18434. * Returns a new Vector3.
  18435. */
  18436. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18437. var defForwardMult = this.definedFacingForward ? 1 : -1;
  18438. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  18439. };
  18440. /**
  18441. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  18442. * @param includeDescendants Include bounding info from descendants as well (true by default).
  18443. */
  18444. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  18445. if (includeDescendants === void 0) { includeDescendants = true; }
  18446. this.computeWorldMatrix(true);
  18447. var min;
  18448. var max;
  18449. var boundingInfo = this.getBoundingInfo();
  18450. if (!this.subMeshes) {
  18451. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18452. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18453. }
  18454. else {
  18455. min = boundingInfo.boundingBox.minimumWorld;
  18456. max = boundingInfo.boundingBox.maximumWorld;
  18457. }
  18458. if (includeDescendants) {
  18459. var descendants = this.getDescendants(false);
  18460. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  18461. var descendant = descendants_1[_i];
  18462. var childMesh = descendant;
  18463. childMesh.computeWorldMatrix(true);
  18464. //make sure we have the needed params to get mix and max
  18465. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  18466. continue;
  18467. }
  18468. var childBoundingInfo = childMesh.getBoundingInfo();
  18469. var boundingBox = childBoundingInfo.boundingBox;
  18470. var minBox = boundingBox.minimumWorld;
  18471. var maxBox = boundingBox.maximumWorld;
  18472. BABYLON.Tools.CheckExtends(minBox, min, max);
  18473. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18474. }
  18475. }
  18476. return {
  18477. min: min,
  18478. max: max
  18479. };
  18480. };
  18481. /**
  18482. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  18483. * Returns the AbstractMesh.
  18484. */
  18485. AbstractMesh.prototype._updateBoundingInfo = function () {
  18486. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  18487. this._boundingInfo.update(this.worldMatrixFromCache);
  18488. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18489. return this;
  18490. };
  18491. /**
  18492. * Update a mesh's children BoundingInfo objects only.
  18493. * Returns the AbstractMesh.
  18494. */
  18495. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  18496. if (!this.subMeshes) {
  18497. return this;
  18498. }
  18499. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  18500. var subMesh = this.subMeshes[subIndex];
  18501. if (!subMesh.IsGlobal) {
  18502. subMesh.updateBoundingInfo(matrix);
  18503. }
  18504. }
  18505. return this;
  18506. };
  18507. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  18508. // Bounding info
  18509. this._updateBoundingInfo();
  18510. };
  18511. /**
  18512. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  18513. * A mesh is in the frustum if its bounding box intersects the frustum.
  18514. * Boolean returned.
  18515. */
  18516. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  18517. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  18518. };
  18519. /**
  18520. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  18521. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  18522. * Boolean returned.
  18523. */
  18524. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18525. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  18526. ;
  18527. };
  18528. /**
  18529. * True if the mesh intersects another mesh or a SolidParticle object.
  18530. * 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)
  18531. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  18532. * Returns a boolean.
  18533. */
  18534. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  18535. if (precise === void 0) { precise = false; }
  18536. if (!this._boundingInfo || !mesh._boundingInfo) {
  18537. return false;
  18538. }
  18539. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  18540. return true;
  18541. }
  18542. if (includeDescendants) {
  18543. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  18544. var child = _a[_i];
  18545. if (child.intersectsMesh(mesh, precise, true)) {
  18546. return true;
  18547. }
  18548. }
  18549. }
  18550. return false;
  18551. };
  18552. /**
  18553. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  18554. * Returns a boolean.
  18555. */
  18556. AbstractMesh.prototype.intersectsPoint = function (point) {
  18557. if (!this._boundingInfo) {
  18558. return false;
  18559. }
  18560. return this._boundingInfo.intersectsPoint(point);
  18561. };
  18562. AbstractMesh.prototype.getPhysicsImpostor = function () {
  18563. return this.physicsImpostor;
  18564. };
  18565. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  18566. if (camera === void 0) { camera = null; }
  18567. if (!camera) {
  18568. camera = this.getScene().activeCamera;
  18569. }
  18570. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  18571. };
  18572. /**
  18573. * Returns the distance from the mesh to the active camera.
  18574. * Returns a float.
  18575. */
  18576. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  18577. if (camera === void 0) { camera = null; }
  18578. if (!camera) {
  18579. camera = this.getScene().activeCamera;
  18580. }
  18581. return this.absolutePosition.subtract(camera.position).length();
  18582. };
  18583. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  18584. if (!this.physicsImpostor) {
  18585. return this;
  18586. }
  18587. this.physicsImpostor.applyImpulse(force, contactPoint);
  18588. return this;
  18589. };
  18590. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  18591. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  18592. return this;
  18593. }
  18594. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  18595. mainPivot: pivot1,
  18596. connectedPivot: pivot2,
  18597. nativeParams: options
  18598. });
  18599. return this;
  18600. };
  18601. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  18602. // Collisions
  18603. /**
  18604. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  18605. * Default `false`.
  18606. */
  18607. get: function () {
  18608. return this._checkCollisions;
  18609. },
  18610. set: function (collisionEnabled) {
  18611. this._checkCollisions = collisionEnabled;
  18612. if (this.getScene().workerCollisions) {
  18613. this.getScene().collisionCoordinator.onMeshUpdated(this);
  18614. }
  18615. },
  18616. enumerable: true,
  18617. configurable: true
  18618. });
  18619. Object.defineProperty(AbstractMesh.prototype, "collider", {
  18620. /**
  18621. * Gets Collider object used to compute collisions (not physics)
  18622. */
  18623. get: function () {
  18624. return this._collider;
  18625. },
  18626. enumerable: true,
  18627. configurable: true
  18628. });
  18629. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  18630. var globalPosition = this.getAbsolutePosition();
  18631. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  18632. if (!this._collider) {
  18633. this._collider = new BABYLON.Collider();
  18634. }
  18635. this._collider._radius = this.ellipsoid;
  18636. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  18637. return this;
  18638. };
  18639. // Submeshes octree
  18640. /**
  18641. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  18642. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  18643. * Returns an Octree of submeshes.
  18644. */
  18645. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  18646. if (maxCapacity === void 0) { maxCapacity = 64; }
  18647. if (maxDepth === void 0) { maxDepth = 2; }
  18648. if (!this._submeshesOctree) {
  18649. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  18650. }
  18651. this.computeWorldMatrix(true);
  18652. var boundingInfo = this.getBoundingInfo();
  18653. // Update octree
  18654. var bbox = boundingInfo.boundingBox;
  18655. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  18656. return this._submeshesOctree;
  18657. };
  18658. // Collisions
  18659. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  18660. this._generatePointsArray();
  18661. if (!this._positions) {
  18662. return this;
  18663. }
  18664. // Transformation
  18665. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  18666. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  18667. subMesh._lastColliderWorldVertices = [];
  18668. subMesh._trianglePlanes = [];
  18669. var start = subMesh.verticesStart;
  18670. var end = (subMesh.verticesStart + subMesh.verticesCount);
  18671. for (var i = start; i < end; i++) {
  18672. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  18673. }
  18674. }
  18675. // Collide
  18676. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  18677. if (collider.collisionFound) {
  18678. collider.collidedMesh = this;
  18679. }
  18680. return this;
  18681. };
  18682. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  18683. var subMeshes;
  18684. var len;
  18685. // Octrees
  18686. if (this._submeshesOctree && this.useOctreeForCollisions) {
  18687. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  18688. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  18689. len = intersections.length;
  18690. subMeshes = intersections.data;
  18691. }
  18692. else {
  18693. subMeshes = this.subMeshes;
  18694. len = subMeshes.length;
  18695. }
  18696. for (var index = 0; index < len; index++) {
  18697. var subMesh = subMeshes[index];
  18698. // Bounding test
  18699. if (len > 1 && !subMesh._checkCollision(collider))
  18700. continue;
  18701. this._collideForSubMesh(subMesh, transformMatrix, collider);
  18702. }
  18703. return this;
  18704. };
  18705. AbstractMesh.prototype._checkCollision = function (collider) {
  18706. // Bounding box test
  18707. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  18708. return this;
  18709. // Transformation matrix
  18710. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  18711. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  18712. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  18713. return this;
  18714. };
  18715. // Picking
  18716. AbstractMesh.prototype._generatePointsArray = function () {
  18717. return false;
  18718. };
  18719. /**
  18720. * Checks if the passed Ray intersects with the mesh.
  18721. * Returns an object PickingInfo.
  18722. */
  18723. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  18724. var pickingInfo = new BABYLON.PickingInfo();
  18725. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18726. return pickingInfo;
  18727. }
  18728. if (!this._generatePointsArray()) {
  18729. return pickingInfo;
  18730. }
  18731. var intersectInfo = null;
  18732. // Octrees
  18733. var subMeshes;
  18734. var len;
  18735. if (this._submeshesOctree && this.useOctreeForPicking) {
  18736. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18737. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18738. len = intersections.length;
  18739. subMeshes = intersections.data;
  18740. }
  18741. else {
  18742. subMeshes = this.subMeshes;
  18743. len = subMeshes.length;
  18744. }
  18745. for (var index = 0; index < len; index++) {
  18746. var subMesh = subMeshes[index];
  18747. // Bounding test
  18748. if (len > 1 && !subMesh.canIntersects(ray))
  18749. continue;
  18750. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18751. if (currentIntersectInfo) {
  18752. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18753. intersectInfo = currentIntersectInfo;
  18754. intersectInfo.subMeshId = index;
  18755. if (fastCheck) {
  18756. break;
  18757. }
  18758. }
  18759. }
  18760. }
  18761. if (intersectInfo) {
  18762. // Get picked point
  18763. var world = this.getWorldMatrix();
  18764. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18765. var direction = ray.direction.clone();
  18766. direction = direction.scale(intersectInfo.distance);
  18767. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18768. var pickedPoint = worldOrigin.add(worldDirection);
  18769. // Return result
  18770. pickingInfo.hit = true;
  18771. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18772. pickingInfo.pickedPoint = pickedPoint;
  18773. pickingInfo.pickedMesh = this;
  18774. pickingInfo.bu = intersectInfo.bu || 0;
  18775. pickingInfo.bv = intersectInfo.bv || 0;
  18776. pickingInfo.faceId = intersectInfo.faceId;
  18777. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18778. return pickingInfo;
  18779. }
  18780. return pickingInfo;
  18781. };
  18782. /**
  18783. * Clones the mesh, used by the class Mesh.
  18784. * Just returns `null` for an AbstractMesh.
  18785. */
  18786. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18787. return null;
  18788. };
  18789. /**
  18790. * Disposes all the mesh submeshes.
  18791. * Returns the AbstractMesh.
  18792. */
  18793. AbstractMesh.prototype.releaseSubMeshes = function () {
  18794. if (this.subMeshes) {
  18795. while (this.subMeshes.length) {
  18796. this.subMeshes[0].dispose();
  18797. }
  18798. }
  18799. else {
  18800. this.subMeshes = new Array();
  18801. }
  18802. return this;
  18803. };
  18804. /**
  18805. * Releases resources associated with this abstract mesh.
  18806. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18807. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18808. */
  18809. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18810. var _this = this;
  18811. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18812. var index;
  18813. // Smart Array Retainers.
  18814. this.getScene().freeActiveMeshes();
  18815. this.getScene().freeRenderingGroups();
  18816. // Action manager
  18817. if (this.actionManager !== undefined && this.actionManager !== null) {
  18818. this.actionManager.dispose();
  18819. this.actionManager = null;
  18820. }
  18821. // Skeleton
  18822. this._skeleton = null;
  18823. // Physics
  18824. if (this.physicsImpostor) {
  18825. this.physicsImpostor.dispose();
  18826. }
  18827. // Intersections in progress
  18828. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18829. var other = this._intersectionsInProgress[index];
  18830. var pos = other._intersectionsInProgress.indexOf(this);
  18831. other._intersectionsInProgress.splice(pos, 1);
  18832. }
  18833. this._intersectionsInProgress = [];
  18834. // Lights
  18835. var lights = this.getScene().lights;
  18836. lights.forEach(function (light) {
  18837. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18838. if (meshIndex !== -1) {
  18839. light.includedOnlyMeshes.splice(meshIndex, 1);
  18840. }
  18841. meshIndex = light.excludedMeshes.indexOf(_this);
  18842. if (meshIndex !== -1) {
  18843. light.excludedMeshes.splice(meshIndex, 1);
  18844. }
  18845. // Shadow generators
  18846. var generator = light.getShadowGenerator();
  18847. if (generator) {
  18848. var shadowMap = generator.getShadowMap();
  18849. if (shadowMap && shadowMap.renderList) {
  18850. meshIndex = shadowMap.renderList.indexOf(_this);
  18851. if (meshIndex !== -1) {
  18852. shadowMap.renderList.splice(meshIndex, 1);
  18853. }
  18854. }
  18855. }
  18856. });
  18857. // Edges
  18858. if (this._edgesRenderer) {
  18859. this._edgesRenderer.dispose();
  18860. this._edgesRenderer = null;
  18861. }
  18862. // SubMeshes
  18863. if (this.getClassName() !== "InstancedMesh") {
  18864. this.releaseSubMeshes();
  18865. }
  18866. // Octree
  18867. var sceneOctree = this.getScene().selectionOctree;
  18868. if (sceneOctree !== undefined && sceneOctree !== null) {
  18869. var index = sceneOctree.dynamicContent.indexOf(this);
  18870. if (index !== -1) {
  18871. sceneOctree.dynamicContent.splice(index, 1);
  18872. }
  18873. }
  18874. // Query
  18875. var engine = this.getScene().getEngine();
  18876. if (this._occlusionQuery) {
  18877. this._isOcclusionQueryInProgress = false;
  18878. engine.deleteQuery(this._occlusionQuery);
  18879. this._occlusionQuery = null;
  18880. }
  18881. // Engine
  18882. engine.wipeCaches();
  18883. // Remove from scene
  18884. this.getScene().removeMesh(this);
  18885. if (disposeMaterialAndTextures) {
  18886. if (this.material) {
  18887. this.material.dispose(false, true);
  18888. }
  18889. }
  18890. if (!doNotRecurse) {
  18891. // Particles
  18892. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18893. if (this.getScene().particleSystems[index].emitter === this) {
  18894. this.getScene().particleSystems[index].dispose();
  18895. index--;
  18896. }
  18897. }
  18898. }
  18899. // facet data
  18900. if (this._facetDataEnabled) {
  18901. this.disableFacetData();
  18902. }
  18903. this.onAfterWorldMatrixUpdateObservable.clear();
  18904. this.onCollideObservable.clear();
  18905. this.onCollisionPositionChangeObservable.clear();
  18906. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  18907. };
  18908. /**
  18909. * Adds the passed mesh as a child to the current mesh.
  18910. * Returns the AbstractMesh.
  18911. */
  18912. AbstractMesh.prototype.addChild = function (mesh) {
  18913. mesh.setParent(this);
  18914. return this;
  18915. };
  18916. /**
  18917. * Removes the passed mesh from the current mesh children list.
  18918. * Returns the AbstractMesh.
  18919. */
  18920. AbstractMesh.prototype.removeChild = function (mesh) {
  18921. mesh.setParent(null);
  18922. return this;
  18923. };
  18924. // Facet data
  18925. /**
  18926. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18927. * Returns the AbstractMesh.
  18928. */
  18929. AbstractMesh.prototype._initFacetData = function () {
  18930. if (!this._facetNormals) {
  18931. this._facetNormals = new Array();
  18932. }
  18933. if (!this._facetPositions) {
  18934. this._facetPositions = new Array();
  18935. }
  18936. if (!this._facetPartitioning) {
  18937. this._facetPartitioning = new Array();
  18938. }
  18939. this._facetNb = (this.getIndices().length / 3) | 0;
  18940. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18941. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18942. for (var f = 0; f < this._facetNb; f++) {
  18943. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18944. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18945. }
  18946. this._facetDataEnabled = true;
  18947. return this;
  18948. };
  18949. /**
  18950. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18951. * This method can be called within the render loop.
  18952. * 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.
  18953. * Returns the AbstractMesh.
  18954. */
  18955. AbstractMesh.prototype.updateFacetData = function () {
  18956. if (!this._facetDataEnabled) {
  18957. this._initFacetData();
  18958. }
  18959. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18960. var indices = this.getIndices();
  18961. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18962. var bInfo = this.getBoundingInfo();
  18963. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18964. // init arrays, matrix and sort function on first call
  18965. this._facetDepthSortEnabled = true;
  18966. if (indices instanceof Uint16Array) {
  18967. this._depthSortedIndices = new Uint16Array(indices);
  18968. }
  18969. else if (indices instanceof Uint32Array) {
  18970. this._depthSortedIndices = new Uint32Array(indices);
  18971. }
  18972. else {
  18973. var needs32bits = false;
  18974. for (var i = 0; i < indices.length; i++) {
  18975. if (indices[i] > 65535) {
  18976. needs32bits = true;
  18977. break;
  18978. }
  18979. }
  18980. if (needs32bits) {
  18981. this._depthSortedIndices = new Uint32Array(indices);
  18982. }
  18983. else {
  18984. this._depthSortedIndices = new Uint16Array(indices);
  18985. }
  18986. }
  18987. this._facetDepthSortFunction = function (f1, f2) {
  18988. return (f2.sqDistance - f1.sqDistance);
  18989. };
  18990. if (!this._facetDepthSortFrom) {
  18991. var camera = this.getScene().activeCamera;
  18992. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18993. }
  18994. this._depthSortedFacets = [];
  18995. for (var f = 0; f < this._facetNb; f++) {
  18996. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18997. this._depthSortedFacets.push(depthSortedFacet);
  18998. }
  18999. this._invertedMatrix = BABYLON.Matrix.Identity();
  19000. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  19001. }
  19002. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  19003. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  19004. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  19005. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  19006. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  19007. this._subDiv.max = this._partitioningSubdivisions;
  19008. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  19009. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  19010. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  19011. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  19012. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  19013. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  19014. // set the parameters for ComputeNormals()
  19015. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  19016. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  19017. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  19018. this._facetParameters.bInfo = bInfo;
  19019. this._facetParameters.bbSize = this._bbSize;
  19020. this._facetParameters.subDiv = this._subDiv;
  19021. this._facetParameters.ratio = this.partitioningBBoxRatio;
  19022. this._facetParameters.depthSort = this._facetDepthSort;
  19023. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  19024. this.computeWorldMatrix(true);
  19025. this._worldMatrix.invertToRef(this._invertedMatrix);
  19026. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  19027. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  19028. }
  19029. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  19030. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  19031. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  19032. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  19033. var l = (this._depthSortedIndices.length / 3) | 0;
  19034. for (var f = 0; f < l; f++) {
  19035. var sind = this._depthSortedFacets[f].ind;
  19036. this._depthSortedIndices[f * 3] = indices[sind];
  19037. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  19038. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  19039. }
  19040. this.updateIndices(this._depthSortedIndices);
  19041. }
  19042. return this;
  19043. };
  19044. /**
  19045. * Returns the facetLocalNormals array.
  19046. * The normals are expressed in the mesh local space.
  19047. */
  19048. AbstractMesh.prototype.getFacetLocalNormals = function () {
  19049. if (!this._facetNormals) {
  19050. this.updateFacetData();
  19051. }
  19052. return this._facetNormals;
  19053. };
  19054. /**
  19055. * Returns the facetLocalPositions array.
  19056. * The facet positions are expressed in the mesh local space.
  19057. */
  19058. AbstractMesh.prototype.getFacetLocalPositions = function () {
  19059. if (!this._facetPositions) {
  19060. this.updateFacetData();
  19061. }
  19062. return this._facetPositions;
  19063. };
  19064. /**
  19065. * Returns the facetLocalPartioning array.
  19066. */
  19067. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  19068. if (!this._facetPartitioning) {
  19069. this.updateFacetData();
  19070. }
  19071. return this._facetPartitioning;
  19072. };
  19073. /**
  19074. * Returns the i-th facet position in the world system.
  19075. * This method allocates a new Vector3 per call.
  19076. */
  19077. AbstractMesh.prototype.getFacetPosition = function (i) {
  19078. var pos = BABYLON.Vector3.Zero();
  19079. this.getFacetPositionToRef(i, pos);
  19080. return pos;
  19081. };
  19082. /**
  19083. * Sets the reference Vector3 with the i-th facet position in the world system.
  19084. * Returns the AbstractMesh.
  19085. */
  19086. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  19087. var localPos = (this.getFacetLocalPositions())[i];
  19088. var world = this.getWorldMatrix();
  19089. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  19090. return this;
  19091. };
  19092. /**
  19093. * Returns the i-th facet normal in the world system.
  19094. * This method allocates a new Vector3 per call.
  19095. */
  19096. AbstractMesh.prototype.getFacetNormal = function (i) {
  19097. var norm = BABYLON.Vector3.Zero();
  19098. this.getFacetNormalToRef(i, norm);
  19099. return norm;
  19100. };
  19101. /**
  19102. * Sets the reference Vector3 with the i-th facet normal in the world system.
  19103. * Returns the AbstractMesh.
  19104. */
  19105. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  19106. var localNorm = (this.getFacetLocalNormals())[i];
  19107. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  19108. return this;
  19109. };
  19110. /**
  19111. * 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).
  19112. */
  19113. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  19114. var bInfo = this.getBoundingInfo();
  19115. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  19116. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  19117. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  19118. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  19119. return null;
  19120. }
  19121. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  19122. };
  19123. /**
  19124. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  19125. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  19126. * If checkFace is 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.
  19127. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  19128. * 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.
  19129. */
  19130. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  19131. if (checkFace === void 0) { checkFace = false; }
  19132. if (facing === void 0) { facing = true; }
  19133. var world = this.getWorldMatrix();
  19134. var invMat = BABYLON.Tmp.Matrix[5];
  19135. world.invertToRef(invMat);
  19136. var invVect = BABYLON.Tmp.Vector3[8];
  19137. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  19138. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  19139. if (projected) {
  19140. // tranform the local computed projected vector to world coordinates
  19141. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  19142. }
  19143. return closest;
  19144. };
  19145. /**
  19146. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  19147. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  19148. * If checkFace is 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.
  19149. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  19150. * 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.
  19151. */
  19152. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  19153. if (checkFace === void 0) { checkFace = false; }
  19154. if (facing === void 0) { facing = true; }
  19155. var closest = null;
  19156. var tmpx = 0.0;
  19157. var tmpy = 0.0;
  19158. var tmpz = 0.0;
  19159. var d = 0.0; // tmp dot facet normal * facet position
  19160. var t0 = 0.0;
  19161. var projx = 0.0;
  19162. var projy = 0.0;
  19163. var projz = 0.0;
  19164. // Get all the facets in the same partitioning block than (x, y, z)
  19165. var facetPositions = this.getFacetLocalPositions();
  19166. var facetNormals = this.getFacetLocalNormals();
  19167. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  19168. if (!facetsInBlock) {
  19169. return null;
  19170. }
  19171. // Get the closest facet to (x, y, z)
  19172. var shortest = Number.MAX_VALUE; // init distance vars
  19173. var tmpDistance = shortest;
  19174. var fib; // current facet in the block
  19175. var norm; // current facet normal
  19176. var p0; // current facet barycenter position
  19177. // loop on all the facets in the current partitioning block
  19178. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  19179. fib = facetsInBlock[idx];
  19180. norm = facetNormals[fib];
  19181. p0 = facetPositions[fib];
  19182. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  19183. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  19184. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  19185. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  19186. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  19187. projx = x + norm.x * t0;
  19188. projy = y + norm.y * t0;
  19189. projz = z + norm.z * t0;
  19190. tmpx = projx - x;
  19191. tmpy = projy - y;
  19192. tmpz = projz - z;
  19193. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  19194. if (tmpDistance < shortest) {
  19195. shortest = tmpDistance;
  19196. closest = fib;
  19197. if (projected) {
  19198. projected.x = projx;
  19199. projected.y = projy;
  19200. projected.z = projz;
  19201. }
  19202. }
  19203. }
  19204. }
  19205. return closest;
  19206. };
  19207. /**
  19208. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  19209. */
  19210. AbstractMesh.prototype.getFacetDataParameters = function () {
  19211. return this._facetParameters;
  19212. };
  19213. /**
  19214. * Disables the feature FacetData and frees the related memory.
  19215. * Returns the AbstractMesh.
  19216. */
  19217. AbstractMesh.prototype.disableFacetData = function () {
  19218. if (this._facetDataEnabled) {
  19219. this._facetDataEnabled = false;
  19220. this._facetPositions = new Array();
  19221. this._facetNormals = new Array();
  19222. this._facetPartitioning = new Array();
  19223. this._facetParameters = null;
  19224. this._depthSortedIndices = new Uint32Array(0);
  19225. }
  19226. return this;
  19227. };
  19228. /**
  19229. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  19230. * Returns the mesh.
  19231. */
  19232. AbstractMesh.prototype.updateIndices = function (indices) {
  19233. return this;
  19234. };
  19235. /**
  19236. * The mesh Geometry. Actually used by the Mesh object.
  19237. * Returns a blank geometry object.
  19238. */
  19239. /**
  19240. * Creates new normals data for the mesh.
  19241. * @param updatable.
  19242. */
  19243. AbstractMesh.prototype.createNormals = function (updatable) {
  19244. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19245. var indices = this.getIndices();
  19246. var normals;
  19247. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19248. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19249. }
  19250. else {
  19251. normals = [];
  19252. }
  19253. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  19254. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  19255. };
  19256. /**
  19257. * Align the mesh with a normal.
  19258. * Returns the mesh.
  19259. */
  19260. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  19261. if (!upDirection) {
  19262. upDirection = BABYLON.Axis.Y;
  19263. }
  19264. var axisX = BABYLON.Tmp.Vector3[0];
  19265. var axisZ = BABYLON.Tmp.Vector3[1];
  19266. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  19267. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  19268. if (this.rotationQuaternion) {
  19269. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  19270. }
  19271. else {
  19272. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  19273. }
  19274. return this;
  19275. };
  19276. AbstractMesh.prototype.checkOcclusionQuery = function () {
  19277. var engine = this.getEngine();
  19278. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  19279. this._isOccluded = false;
  19280. return;
  19281. }
  19282. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  19283. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  19284. if (isOcclusionQueryAvailable) {
  19285. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  19286. this._isOcclusionQueryInProgress = false;
  19287. this._occlusionInternalRetryCounter = 0;
  19288. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  19289. }
  19290. else {
  19291. this._occlusionInternalRetryCounter++;
  19292. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  19293. this._isOcclusionQueryInProgress = false;
  19294. this._occlusionInternalRetryCounter = 0;
  19295. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  19296. // if strict continue the last state of the object.
  19297. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  19298. }
  19299. else {
  19300. return;
  19301. }
  19302. }
  19303. }
  19304. var scene = this.getScene();
  19305. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  19306. if (!this._occlusionQuery) {
  19307. this._occlusionQuery = engine.createQuery();
  19308. }
  19309. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  19310. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  19311. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  19312. this._isOcclusionQueryInProgress = true;
  19313. };
  19314. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  19315. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  19316. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  19317. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  19318. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  19319. return AbstractMesh;
  19320. }(BABYLON.TransformNode));
  19321. BABYLON.AbstractMesh = AbstractMesh;
  19322. })(BABYLON || (BABYLON = {}));
  19323. //# sourceMappingURL=babylon.abstractMesh.js.map
  19324. "use strict";
  19325. var BABYLON;
  19326. (function (BABYLON) {
  19327. /**
  19328. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  19329. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  19330. * 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.
  19331. */
  19332. var Light = /** @class */ (function (_super) {
  19333. __extends(Light, _super);
  19334. /**
  19335. * Creates a Light object in the scene.
  19336. * Documentation : http://doc.babylonjs.com/tutorials/lights
  19337. * @param name The firendly name of the light
  19338. * @param scene The scene the light belongs too
  19339. */
  19340. function Light(name, scene) {
  19341. var _this = _super.call(this, name, scene) || this;
  19342. /**
  19343. * Diffuse gives the basic color to an object.
  19344. */
  19345. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  19346. /**
  19347. * Specular produces a highlight color on an object.
  19348. * Note: This is note affecting PBR materials.
  19349. */
  19350. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  19351. /**
  19352. * Strength of the light.
  19353. * Note: By default it is define in the framework own unit.
  19354. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  19355. */
  19356. _this.intensity = 1.0;
  19357. /**
  19358. * Defines how far from the source the light is impacting in scene units.
  19359. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  19360. */
  19361. _this.range = Number.MAX_VALUE;
  19362. /**
  19363. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  19364. * of light.
  19365. */
  19366. _this._photometricScale = 1.0;
  19367. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  19368. _this._radius = 0.00001;
  19369. /**
  19370. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  19371. * exceeding the number allowed of the materials.
  19372. */
  19373. _this.renderPriority = 0;
  19374. /**
  19375. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  19376. * the current shadow generator.
  19377. */
  19378. _this.shadowEnabled = true;
  19379. _this._excludeWithLayerMask = 0;
  19380. _this._includeOnlyWithLayerMask = 0;
  19381. _this._lightmapMode = 0;
  19382. /**
  19383. * @ignore Internal use only.
  19384. */
  19385. _this._excludedMeshesIds = new Array();
  19386. /**
  19387. * @ignore Internal use only.
  19388. */
  19389. _this._includedOnlyMeshesIds = new Array();
  19390. _this.getScene().addLight(_this);
  19391. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  19392. _this._buildUniformLayout();
  19393. _this.includedOnlyMeshes = new Array();
  19394. _this.excludedMeshes = new Array();
  19395. _this._resyncMeshes();
  19396. return _this;
  19397. }
  19398. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  19399. /**
  19400. * If every light affecting the material is in this lightmapMode,
  19401. * material.lightmapTexture adds or multiplies
  19402. * (depends on material.useLightmapAsShadowmap)
  19403. * after every other light calculations.
  19404. */
  19405. get: function () {
  19406. return Light._LIGHTMAP_DEFAULT;
  19407. },
  19408. enumerable: true,
  19409. configurable: true
  19410. });
  19411. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  19412. /**
  19413. * material.lightmapTexture as only diffuse lighting from this light
  19414. * adds only specular lighting from this light
  19415. * adds dynamic shadows
  19416. */
  19417. get: function () {
  19418. return Light._LIGHTMAP_SPECULAR;
  19419. },
  19420. enumerable: true,
  19421. configurable: true
  19422. });
  19423. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  19424. /**
  19425. * material.lightmapTexture as only lighting
  19426. * no light calculation from this light
  19427. * only adds dynamic shadows from this light
  19428. */
  19429. get: function () {
  19430. return Light._LIGHTMAP_SHADOWSONLY;
  19431. },
  19432. enumerable: true,
  19433. configurable: true
  19434. });
  19435. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  19436. /**
  19437. * Each light type uses the default quantity according to its type:
  19438. * point/spot lights use luminous intensity
  19439. * directional lights use illuminance
  19440. */
  19441. get: function () {
  19442. return Light._INTENSITYMODE_AUTOMATIC;
  19443. },
  19444. enumerable: true,
  19445. configurable: true
  19446. });
  19447. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  19448. /**
  19449. * lumen (lm)
  19450. */
  19451. get: function () {
  19452. return Light._INTENSITYMODE_LUMINOUSPOWER;
  19453. },
  19454. enumerable: true,
  19455. configurable: true
  19456. });
  19457. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  19458. /**
  19459. * candela (lm/sr)
  19460. */
  19461. get: function () {
  19462. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  19463. },
  19464. enumerable: true,
  19465. configurable: true
  19466. });
  19467. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  19468. /**
  19469. * lux (lm/m^2)
  19470. */
  19471. get: function () {
  19472. return Light._INTENSITYMODE_ILLUMINANCE;
  19473. },
  19474. enumerable: true,
  19475. configurable: true
  19476. });
  19477. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  19478. /**
  19479. * nit (cd/m^2)
  19480. */
  19481. get: function () {
  19482. return Light._INTENSITYMODE_LUMINANCE;
  19483. },
  19484. enumerable: true,
  19485. configurable: true
  19486. });
  19487. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  19488. /**
  19489. * Light type const id of the point light.
  19490. */
  19491. get: function () {
  19492. return Light._LIGHTTYPEID_POINTLIGHT;
  19493. },
  19494. enumerable: true,
  19495. configurable: true
  19496. });
  19497. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  19498. /**
  19499. * Light type const id of the directional light.
  19500. */
  19501. get: function () {
  19502. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  19503. },
  19504. enumerable: true,
  19505. configurable: true
  19506. });
  19507. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  19508. /**
  19509. * Light type const id of the spot light.
  19510. */
  19511. get: function () {
  19512. return Light._LIGHTTYPEID_SPOTLIGHT;
  19513. },
  19514. enumerable: true,
  19515. configurable: true
  19516. });
  19517. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  19518. /**
  19519. * Light type const id of the hemispheric light.
  19520. */
  19521. get: function () {
  19522. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  19523. },
  19524. enumerable: true,
  19525. configurable: true
  19526. });
  19527. Object.defineProperty(Light.prototype, "intensityMode", {
  19528. /**
  19529. * Gets the photometric scale used to interpret the intensity.
  19530. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19531. */
  19532. get: function () {
  19533. return this._intensityMode;
  19534. },
  19535. /**
  19536. * Sets the photometric scale used to interpret the intensity.
  19537. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19538. */
  19539. set: function (value) {
  19540. this._intensityMode = value;
  19541. this._computePhotometricScale();
  19542. },
  19543. enumerable: true,
  19544. configurable: true
  19545. });
  19546. ;
  19547. ;
  19548. Object.defineProperty(Light.prototype, "radius", {
  19549. /**
  19550. * Gets the light radius used by PBR Materials to simulate soft area lights.
  19551. */
  19552. get: function () {
  19553. return this._radius;
  19554. },
  19555. /**
  19556. * sets the light radius used by PBR Materials to simulate soft area lights.
  19557. */
  19558. set: function (value) {
  19559. this._radius = value;
  19560. this._computePhotometricScale();
  19561. },
  19562. enumerable: true,
  19563. configurable: true
  19564. });
  19565. ;
  19566. ;
  19567. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  19568. /**
  19569. * Gets the only meshes impacted by this light.
  19570. */
  19571. get: function () {
  19572. return this._includedOnlyMeshes;
  19573. },
  19574. /**
  19575. * Sets the only meshes impacted by this light.
  19576. */
  19577. set: function (value) {
  19578. this._includedOnlyMeshes = value;
  19579. this._hookArrayForIncludedOnly(value);
  19580. },
  19581. enumerable: true,
  19582. configurable: true
  19583. });
  19584. Object.defineProperty(Light.prototype, "excludedMeshes", {
  19585. /**
  19586. * Gets the meshes not impacted by this light.
  19587. */
  19588. get: function () {
  19589. return this._excludedMeshes;
  19590. },
  19591. /**
  19592. * Sets the meshes not impacted by this light.
  19593. */
  19594. set: function (value) {
  19595. this._excludedMeshes = value;
  19596. this._hookArrayForExcluded(value);
  19597. },
  19598. enumerable: true,
  19599. configurable: true
  19600. });
  19601. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  19602. /**
  19603. * Gets the layer id use to find what meshes are not impacted by the light.
  19604. * Inactive if 0
  19605. */
  19606. get: function () {
  19607. return this._excludeWithLayerMask;
  19608. },
  19609. /**
  19610. * Sets the layer id use to find what meshes are not impacted by the light.
  19611. * Inactive if 0
  19612. */
  19613. set: function (value) {
  19614. this._excludeWithLayerMask = value;
  19615. this._resyncMeshes();
  19616. },
  19617. enumerable: true,
  19618. configurable: true
  19619. });
  19620. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  19621. /**
  19622. * Gets the layer id use to find what meshes are impacted by the light.
  19623. * Inactive if 0
  19624. */
  19625. get: function () {
  19626. return this._includeOnlyWithLayerMask;
  19627. },
  19628. /**
  19629. * Sets the layer id use to find what meshes are impacted by the light.
  19630. * Inactive if 0
  19631. */
  19632. set: function (value) {
  19633. this._includeOnlyWithLayerMask = value;
  19634. this._resyncMeshes();
  19635. },
  19636. enumerable: true,
  19637. configurable: true
  19638. });
  19639. Object.defineProperty(Light.prototype, "lightmapMode", {
  19640. /**
  19641. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19642. */
  19643. get: function () {
  19644. return this._lightmapMode;
  19645. },
  19646. /**
  19647. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19648. */
  19649. set: function (value) {
  19650. if (this._lightmapMode === value) {
  19651. return;
  19652. }
  19653. this._lightmapMode = value;
  19654. this._markMeshesAsLightDirty();
  19655. },
  19656. enumerable: true,
  19657. configurable: true
  19658. });
  19659. /**
  19660. * Returns the string "Light".
  19661. * @returns the class name
  19662. */
  19663. Light.prototype.getClassName = function () {
  19664. return "Light";
  19665. };
  19666. /**
  19667. * Converts the light information to a readable string for debug purpose.
  19668. * @param fullDetails Supports for multiple levels of logging within scene loading
  19669. * @returns the human readable light info
  19670. */
  19671. Light.prototype.toString = function (fullDetails) {
  19672. var ret = "Name: " + this.name;
  19673. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  19674. if (this.animations) {
  19675. for (var i = 0; i < this.animations.length; i++) {
  19676. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19677. }
  19678. }
  19679. if (fullDetails) {
  19680. }
  19681. return ret;
  19682. };
  19683. /**
  19684. * Set the enabled state of this node.
  19685. * @param value - the new enabled state
  19686. */
  19687. Light.prototype.setEnabled = function (value) {
  19688. _super.prototype.setEnabled.call(this, value);
  19689. this._resyncMeshes();
  19690. };
  19691. /**
  19692. * Returns the Light associated shadow generator if any.
  19693. * @return the associated shadow generator.
  19694. */
  19695. Light.prototype.getShadowGenerator = function () {
  19696. return this._shadowGenerator;
  19697. };
  19698. /**
  19699. * Returns a Vector3, the absolute light position in the World.
  19700. * @returns the world space position of the light
  19701. */
  19702. Light.prototype.getAbsolutePosition = function () {
  19703. return BABYLON.Vector3.Zero();
  19704. };
  19705. /**
  19706. * Specifies if the light will affect the passed mesh.
  19707. * @param mesh The mesh to test against the light
  19708. * @return true the mesh is affected otherwise, false.
  19709. */
  19710. Light.prototype.canAffectMesh = function (mesh) {
  19711. if (!mesh) {
  19712. return true;
  19713. }
  19714. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  19715. return false;
  19716. }
  19717. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  19718. return false;
  19719. }
  19720. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19721. return false;
  19722. }
  19723. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19724. return false;
  19725. }
  19726. return true;
  19727. };
  19728. /**
  19729. * Computes and Returns the light World matrix.
  19730. * @returns the world matrix
  19731. */
  19732. Light.prototype.getWorldMatrix = function () {
  19733. this._currentRenderId = this.getScene().getRenderId();
  19734. this._childRenderId = this._currentRenderId;
  19735. var worldMatrix = this._getWorldMatrix();
  19736. if (this.parent && this.parent.getWorldMatrix) {
  19737. if (!this._parentedWorldMatrix) {
  19738. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19739. }
  19740. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19741. this._markSyncedWithParent();
  19742. return this._parentedWorldMatrix;
  19743. }
  19744. return worldMatrix;
  19745. };
  19746. /**
  19747. * Sort function to order lights for rendering.
  19748. * @param a First Light object to compare to second.
  19749. * @param b Second Light object to compare first.
  19750. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19751. */
  19752. Light.CompareLightsPriority = function (a, b) {
  19753. //shadow-casting lights have priority over non-shadow-casting lights
  19754. //the renderPrioirty is a secondary sort criterion
  19755. if (a.shadowEnabled !== b.shadowEnabled) {
  19756. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19757. }
  19758. return b.renderPriority - a.renderPriority;
  19759. };
  19760. /**
  19761. * Releases resources associated with this node.
  19762. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19763. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19764. */
  19765. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19766. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19767. if (this._shadowGenerator) {
  19768. this._shadowGenerator.dispose();
  19769. this._shadowGenerator = null;
  19770. }
  19771. // Animations
  19772. this.getScene().stopAnimation(this);
  19773. // Remove from meshes
  19774. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19775. var mesh = _a[_i];
  19776. mesh._removeLightSource(this);
  19777. }
  19778. this._uniformBuffer.dispose();
  19779. // Remove from scene
  19780. this.getScene().removeLight(this);
  19781. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19782. };
  19783. /**
  19784. * Returns the light type ID (integer).
  19785. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19786. */
  19787. Light.prototype.getTypeID = function () {
  19788. return 0;
  19789. };
  19790. /**
  19791. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19792. * @returns the scaled intensity in intensity mode unit
  19793. */
  19794. Light.prototype.getScaledIntensity = function () {
  19795. return this._photometricScale * this.intensity;
  19796. };
  19797. /**
  19798. * Returns a new Light object, named "name", from the current one.
  19799. * @param name The name of the cloned light
  19800. * @returns the new created light
  19801. */
  19802. Light.prototype.clone = function (name) {
  19803. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19804. if (!constructor) {
  19805. return null;
  19806. }
  19807. return BABYLON.SerializationHelper.Clone(constructor, this);
  19808. };
  19809. /**
  19810. * Serializes the current light into a Serialization object.
  19811. * @returns the serialized object.
  19812. */
  19813. Light.prototype.serialize = function () {
  19814. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19815. // Type
  19816. serializationObject.type = this.getTypeID();
  19817. // Parent
  19818. if (this.parent) {
  19819. serializationObject.parentId = this.parent.id;
  19820. }
  19821. // Inclusion / exclusions
  19822. if (this.excludedMeshes.length > 0) {
  19823. serializationObject.excludedMeshesIds = [];
  19824. this.excludedMeshes.forEach(function (mesh) {
  19825. serializationObject.excludedMeshesIds.push(mesh.id);
  19826. });
  19827. }
  19828. if (this.includedOnlyMeshes.length > 0) {
  19829. serializationObject.includedOnlyMeshesIds = [];
  19830. this.includedOnlyMeshes.forEach(function (mesh) {
  19831. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19832. });
  19833. }
  19834. // Animations
  19835. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19836. serializationObject.ranges = this.serializeAnimationRanges();
  19837. return serializationObject;
  19838. };
  19839. /**
  19840. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19841. * This new light is named "name" and added to the passed scene.
  19842. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19843. * @param name The friendly name of the light
  19844. * @param scene The scene the new light will belong to
  19845. * @returns the constructor function
  19846. */
  19847. Light.GetConstructorFromName = function (type, name, scene) {
  19848. switch (type) {
  19849. case 0:
  19850. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19851. case 1:
  19852. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19853. case 2:
  19854. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19855. case 3:
  19856. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19857. }
  19858. return null;
  19859. };
  19860. /**
  19861. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19862. * @param parsedLight The JSON representation of the light
  19863. * @param scene The scene to create the parsed light in
  19864. * @returns the created light after parsing
  19865. */
  19866. Light.Parse = function (parsedLight, scene) {
  19867. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19868. if (!constructor) {
  19869. return null;
  19870. }
  19871. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19872. // Inclusion / exclusions
  19873. if (parsedLight.excludedMeshesIds) {
  19874. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19875. }
  19876. if (parsedLight.includedOnlyMeshesIds) {
  19877. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19878. }
  19879. // Parent
  19880. if (parsedLight.parentId) {
  19881. light._waitingParentId = parsedLight.parentId;
  19882. }
  19883. // Animations
  19884. if (parsedLight.animations) {
  19885. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19886. var parsedAnimation = parsedLight.animations[animationIndex];
  19887. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19888. }
  19889. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19890. }
  19891. if (parsedLight.autoAnimate) {
  19892. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19893. }
  19894. return light;
  19895. };
  19896. Light.prototype._hookArrayForExcluded = function (array) {
  19897. var _this = this;
  19898. var oldPush = array.push;
  19899. array.push = function () {
  19900. var items = [];
  19901. for (var _i = 0; _i < arguments.length; _i++) {
  19902. items[_i] = arguments[_i];
  19903. }
  19904. var result = oldPush.apply(array, items);
  19905. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19906. var item = items_1[_a];
  19907. item._resyncLighSource(_this);
  19908. }
  19909. return result;
  19910. };
  19911. var oldSplice = array.splice;
  19912. array.splice = function (index, deleteCount) {
  19913. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19914. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19915. var item = deleted_1[_i];
  19916. item._resyncLighSource(_this);
  19917. }
  19918. return deleted;
  19919. };
  19920. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19921. var item = array_1[_i];
  19922. item._resyncLighSource(this);
  19923. }
  19924. };
  19925. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19926. var _this = this;
  19927. var oldPush = array.push;
  19928. array.push = function () {
  19929. var items = [];
  19930. for (var _i = 0; _i < arguments.length; _i++) {
  19931. items[_i] = arguments[_i];
  19932. }
  19933. var result = oldPush.apply(array, items);
  19934. _this._resyncMeshes();
  19935. return result;
  19936. };
  19937. var oldSplice = array.splice;
  19938. array.splice = function (index, deleteCount) {
  19939. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19940. _this._resyncMeshes();
  19941. return deleted;
  19942. };
  19943. this._resyncMeshes();
  19944. };
  19945. Light.prototype._resyncMeshes = function () {
  19946. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19947. var mesh = _a[_i];
  19948. mesh._resyncLighSource(this);
  19949. }
  19950. };
  19951. /**
  19952. * Forces the meshes to update their light related information in their rendering used effects
  19953. * @ignore Internal Use Only
  19954. */
  19955. Light.prototype._markMeshesAsLightDirty = function () {
  19956. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19957. var mesh = _a[_i];
  19958. if (mesh._lightSources.indexOf(this) !== -1) {
  19959. mesh._markSubMeshesAsLightDirty();
  19960. }
  19961. }
  19962. };
  19963. /**
  19964. * Recomputes the cached photometric scale if needed.
  19965. */
  19966. Light.prototype._computePhotometricScale = function () {
  19967. this._photometricScale = this._getPhotometricScale();
  19968. this.getScene().resetCachedMaterial();
  19969. };
  19970. /**
  19971. * Returns the Photometric Scale according to the light type and intensity mode.
  19972. */
  19973. Light.prototype._getPhotometricScale = function () {
  19974. var photometricScale = 0.0;
  19975. var lightTypeID = this.getTypeID();
  19976. //get photometric mode
  19977. var photometricMode = this.intensityMode;
  19978. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19979. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19980. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19981. }
  19982. else {
  19983. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19984. }
  19985. }
  19986. //compute photometric scale
  19987. switch (lightTypeID) {
  19988. case Light.LIGHTTYPEID_POINTLIGHT:
  19989. case Light.LIGHTTYPEID_SPOTLIGHT:
  19990. switch (photometricMode) {
  19991. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19992. photometricScale = 1.0 / (4.0 * Math.PI);
  19993. break;
  19994. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19995. photometricScale = 1.0;
  19996. break;
  19997. case Light.INTENSITYMODE_LUMINANCE:
  19998. photometricScale = this.radius * this.radius;
  19999. break;
  20000. }
  20001. break;
  20002. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  20003. switch (photometricMode) {
  20004. case Light.INTENSITYMODE_ILLUMINANCE:
  20005. photometricScale = 1.0;
  20006. break;
  20007. case Light.INTENSITYMODE_LUMINANCE:
  20008. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  20009. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  20010. var apexAngleRadians = this.radius;
  20011. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  20012. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  20013. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  20014. photometricScale = solidAngle;
  20015. break;
  20016. }
  20017. break;
  20018. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  20019. // No fall off in hemisperic light.
  20020. photometricScale = 1.0;
  20021. break;
  20022. }
  20023. return photometricScale;
  20024. };
  20025. /**
  20026. * Reorder the light in the scene according to their defined priority.
  20027. * @ignore Internal Use Only
  20028. */
  20029. Light.prototype._reorderLightsInScene = function () {
  20030. var scene = this.getScene();
  20031. if (this._renderPriority != 0) {
  20032. scene.requireLightSorting = true;
  20033. }
  20034. this.getScene().sortLightsByPriority();
  20035. };
  20036. //lightmapMode Consts
  20037. Light._LIGHTMAP_DEFAULT = 0;
  20038. Light._LIGHTMAP_SPECULAR = 1;
  20039. Light._LIGHTMAP_SHADOWSONLY = 2;
  20040. // Intensity Mode Consts
  20041. Light._INTENSITYMODE_AUTOMATIC = 0;
  20042. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  20043. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  20044. Light._INTENSITYMODE_ILLUMINANCE = 3;
  20045. Light._INTENSITYMODE_LUMINANCE = 4;
  20046. // Light types ids const.
  20047. Light._LIGHTTYPEID_POINTLIGHT = 0;
  20048. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  20049. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  20050. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  20051. __decorate([
  20052. BABYLON.serializeAsColor3()
  20053. ], Light.prototype, "diffuse", void 0);
  20054. __decorate([
  20055. BABYLON.serializeAsColor3()
  20056. ], Light.prototype, "specular", void 0);
  20057. __decorate([
  20058. BABYLON.serialize()
  20059. ], Light.prototype, "intensity", void 0);
  20060. __decorate([
  20061. BABYLON.serialize()
  20062. ], Light.prototype, "range", void 0);
  20063. __decorate([
  20064. BABYLON.serialize()
  20065. ], Light.prototype, "intensityMode", null);
  20066. __decorate([
  20067. BABYLON.serialize()
  20068. ], Light.prototype, "radius", null);
  20069. __decorate([
  20070. BABYLON.serialize()
  20071. ], Light.prototype, "_renderPriority", void 0);
  20072. __decorate([
  20073. BABYLON.expandToProperty("_reorderLightsInScene")
  20074. ], Light.prototype, "renderPriority", void 0);
  20075. __decorate([
  20076. BABYLON.serialize()
  20077. ], Light.prototype, "shadowEnabled", void 0);
  20078. __decorate([
  20079. BABYLON.serialize("excludeWithLayerMask")
  20080. ], Light.prototype, "_excludeWithLayerMask", void 0);
  20081. __decorate([
  20082. BABYLON.serialize("includeOnlyWithLayerMask")
  20083. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  20084. __decorate([
  20085. BABYLON.serialize("lightmapMode")
  20086. ], Light.prototype, "_lightmapMode", void 0);
  20087. return Light;
  20088. }(BABYLON.Node));
  20089. BABYLON.Light = Light;
  20090. })(BABYLON || (BABYLON = {}));
  20091. //# sourceMappingURL=babylon.light.js.map
  20092. "use strict";
  20093. var BABYLON;
  20094. (function (BABYLON) {
  20095. var Camera = /** @class */ (function (_super) {
  20096. __extends(Camera, _super);
  20097. function Camera(name, position, scene) {
  20098. var _this = _super.call(this, name, scene) || this;
  20099. /**
  20100. * The vector the camera should consider as up.
  20101. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  20102. */
  20103. _this.upVector = BABYLON.Vector3.Up();
  20104. _this.orthoLeft = null;
  20105. _this.orthoRight = null;
  20106. _this.orthoBottom = null;
  20107. _this.orthoTop = null;
  20108. /**
  20109. * FOV is set in Radians. (default is 0.8)
  20110. */
  20111. _this.fov = 0.8;
  20112. _this.minZ = 1;
  20113. _this.maxZ = 10000.0;
  20114. _this.inertia = 0.9;
  20115. _this.mode = Camera.PERSPECTIVE_CAMERA;
  20116. _this.isIntermediate = false;
  20117. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  20118. /**
  20119. * Restricts the camera to viewing objects with the same layerMask.
  20120. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  20121. */
  20122. _this.layerMask = 0x0FFFFFFF;
  20123. /**
  20124. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  20125. */
  20126. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  20127. // Camera rig members
  20128. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  20129. _this._rigCameras = new Array();
  20130. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  20131. _this._skipRendering = false;
  20132. _this.customRenderTargets = new Array();
  20133. // Observables
  20134. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  20135. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  20136. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  20137. _this.onRestoreStateObservable = new BABYLON.Observable();
  20138. // Cache
  20139. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  20140. _this._projectionMatrix = new BABYLON.Matrix();
  20141. _this._doNotComputeProjectionMatrix = false;
  20142. _this._postProcesses = new Array();
  20143. _this._transformMatrix = BABYLON.Matrix.Zero();
  20144. _this._activeMeshes = new BABYLON.SmartArray(256);
  20145. _this._globalPosition = BABYLON.Vector3.Zero();
  20146. _this._refreshFrustumPlanes = true;
  20147. _this.getScene().addCamera(_this);
  20148. if (!_this.getScene().activeCamera) {
  20149. _this.getScene().activeCamera = _this;
  20150. }
  20151. _this.position = position;
  20152. return _this;
  20153. }
  20154. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  20155. get: function () {
  20156. return Camera._PERSPECTIVE_CAMERA;
  20157. },
  20158. enumerable: true,
  20159. configurable: true
  20160. });
  20161. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  20162. get: function () {
  20163. return Camera._ORTHOGRAPHIC_CAMERA;
  20164. },
  20165. enumerable: true,
  20166. configurable: true
  20167. });
  20168. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  20169. /**
  20170. * This is the default FOV mode for perspective cameras.
  20171. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  20172. *
  20173. */
  20174. get: function () {
  20175. return Camera._FOVMODE_VERTICAL_FIXED;
  20176. },
  20177. enumerable: true,
  20178. configurable: true
  20179. });
  20180. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  20181. /**
  20182. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  20183. *
  20184. */
  20185. get: function () {
  20186. return Camera._FOVMODE_HORIZONTAL_FIXED;
  20187. },
  20188. enumerable: true,
  20189. configurable: true
  20190. });
  20191. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  20192. get: function () {
  20193. return Camera._RIG_MODE_NONE;
  20194. },
  20195. enumerable: true,
  20196. configurable: true
  20197. });
  20198. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  20199. get: function () {
  20200. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  20201. },
  20202. enumerable: true,
  20203. configurable: true
  20204. });
  20205. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  20206. get: function () {
  20207. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  20208. },
  20209. enumerable: true,
  20210. configurable: true
  20211. });
  20212. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  20213. get: function () {
  20214. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20215. },
  20216. enumerable: true,
  20217. configurable: true
  20218. });
  20219. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  20220. get: function () {
  20221. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  20222. },
  20223. enumerable: true,
  20224. configurable: true
  20225. });
  20226. Object.defineProperty(Camera, "RIG_MODE_VR", {
  20227. get: function () {
  20228. return Camera._RIG_MODE_VR;
  20229. },
  20230. enumerable: true,
  20231. configurable: true
  20232. });
  20233. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  20234. get: function () {
  20235. return Camera._RIG_MODE_WEBVR;
  20236. },
  20237. enumerable: true,
  20238. configurable: true
  20239. });
  20240. /**
  20241. * Store current camera state (fov, position, etc..)
  20242. */
  20243. Camera.prototype.storeState = function () {
  20244. this._stateStored = true;
  20245. this._storedFov = this.fov;
  20246. return this;
  20247. };
  20248. /**
  20249. * Restores the camera state values if it has been stored. You must call storeState() first
  20250. */
  20251. Camera.prototype._restoreStateValues = function () {
  20252. if (!this._stateStored) {
  20253. return false;
  20254. }
  20255. this.fov = this._storedFov;
  20256. return true;
  20257. };
  20258. /**
  20259. * Restored camera state. You must call storeState() first
  20260. */
  20261. Camera.prototype.restoreState = function () {
  20262. if (this._restoreStateValues()) {
  20263. this.onRestoreStateObservable.notifyObservers(this);
  20264. return true;
  20265. }
  20266. return false;
  20267. };
  20268. Camera.prototype.getClassName = function () {
  20269. return "Camera";
  20270. };
  20271. /**
  20272. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  20273. */
  20274. Camera.prototype.toString = function (fullDetails) {
  20275. var ret = "Name: " + this.name;
  20276. ret += ", type: " + this.getClassName();
  20277. if (this.animations) {
  20278. for (var i = 0; i < this.animations.length; i++) {
  20279. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  20280. }
  20281. }
  20282. if (fullDetails) {
  20283. }
  20284. return ret;
  20285. };
  20286. Object.defineProperty(Camera.prototype, "globalPosition", {
  20287. get: function () {
  20288. return this._globalPosition;
  20289. },
  20290. enumerable: true,
  20291. configurable: true
  20292. });
  20293. Camera.prototype.getActiveMeshes = function () {
  20294. return this._activeMeshes;
  20295. };
  20296. Camera.prototype.isActiveMesh = function (mesh) {
  20297. return (this._activeMeshes.indexOf(mesh) !== -1);
  20298. };
  20299. /**
  20300. * Is this camera ready to be used/rendered
  20301. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  20302. * @return true if the camera is ready
  20303. */
  20304. Camera.prototype.isReady = function (completeCheck) {
  20305. if (completeCheck === void 0) { completeCheck = false; }
  20306. if (completeCheck) {
  20307. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  20308. var pp = _a[_i];
  20309. if (pp && !pp.isReady()) {
  20310. return false;
  20311. }
  20312. }
  20313. }
  20314. return _super.prototype.isReady.call(this, completeCheck);
  20315. };
  20316. //Cache
  20317. Camera.prototype._initCache = function () {
  20318. _super.prototype._initCache.call(this);
  20319. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20320. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20321. this._cache.mode = undefined;
  20322. this._cache.minZ = undefined;
  20323. this._cache.maxZ = undefined;
  20324. this._cache.fov = undefined;
  20325. this._cache.fovMode = undefined;
  20326. this._cache.aspectRatio = undefined;
  20327. this._cache.orthoLeft = undefined;
  20328. this._cache.orthoRight = undefined;
  20329. this._cache.orthoBottom = undefined;
  20330. this._cache.orthoTop = undefined;
  20331. this._cache.renderWidth = undefined;
  20332. this._cache.renderHeight = undefined;
  20333. };
  20334. Camera.prototype._updateCache = function (ignoreParentClass) {
  20335. if (!ignoreParentClass) {
  20336. _super.prototype._updateCache.call(this);
  20337. }
  20338. this._cache.position.copyFrom(this.position);
  20339. this._cache.upVector.copyFrom(this.upVector);
  20340. };
  20341. // Synchronized
  20342. Camera.prototype._isSynchronized = function () {
  20343. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  20344. };
  20345. Camera.prototype._isSynchronizedViewMatrix = function () {
  20346. if (!_super.prototype._isSynchronized.call(this))
  20347. return false;
  20348. return this._cache.position.equals(this.position)
  20349. && this._cache.upVector.equals(this.upVector)
  20350. && this.isSynchronizedWithParent();
  20351. };
  20352. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  20353. var check = this._cache.mode === this.mode
  20354. && this._cache.minZ === this.minZ
  20355. && this._cache.maxZ === this.maxZ;
  20356. if (!check) {
  20357. return false;
  20358. }
  20359. var engine = this.getEngine();
  20360. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20361. check = this._cache.fov === this.fov
  20362. && this._cache.fovMode === this.fovMode
  20363. && this._cache.aspectRatio === engine.getAspectRatio(this);
  20364. }
  20365. else {
  20366. check = this._cache.orthoLeft === this.orthoLeft
  20367. && this._cache.orthoRight === this.orthoRight
  20368. && this._cache.orthoBottom === this.orthoBottom
  20369. && this._cache.orthoTop === this.orthoTop
  20370. && this._cache.renderWidth === engine.getRenderWidth()
  20371. && this._cache.renderHeight === engine.getRenderHeight();
  20372. }
  20373. return check;
  20374. };
  20375. // Controls
  20376. Camera.prototype.attachControl = function (element, noPreventDefault) {
  20377. };
  20378. Camera.prototype.detachControl = function (element) {
  20379. };
  20380. Camera.prototype.update = function () {
  20381. this._checkInputs();
  20382. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20383. this._updateRigCameras();
  20384. }
  20385. };
  20386. Camera.prototype._checkInputs = function () {
  20387. this.onAfterCheckInputsObservable.notifyObservers(this);
  20388. };
  20389. Object.defineProperty(Camera.prototype, "rigCameras", {
  20390. get: function () {
  20391. return this._rigCameras;
  20392. },
  20393. enumerable: true,
  20394. configurable: true
  20395. });
  20396. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  20397. get: function () {
  20398. return this._rigPostProcess;
  20399. },
  20400. enumerable: true,
  20401. configurable: true
  20402. });
  20403. /**
  20404. * Internal, gets the first post proces.
  20405. * @returns the first post process to be run on this camera.
  20406. */
  20407. Camera.prototype._getFirstPostProcess = function () {
  20408. for (var pp in this._postProcesses) {
  20409. if (this._postProcesses[pp] !== null) {
  20410. return this._postProcesses[pp];
  20411. }
  20412. }
  20413. return null;
  20414. };
  20415. Camera.prototype._cascadePostProcessesToRigCams = function () {
  20416. // invalidate framebuffer
  20417. var firstPostProcess = this._getFirstPostProcess();
  20418. if (firstPostProcess) {
  20419. firstPostProcess.markTextureDirty();
  20420. }
  20421. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  20422. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  20423. var cam = this._rigCameras[i];
  20424. var rigPostProcess = cam._rigPostProcess;
  20425. // for VR rig, there does not have to be a post process
  20426. if (rigPostProcess) {
  20427. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  20428. if (isPass) {
  20429. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  20430. cam.isIntermediate = this._postProcesses.length === 0;
  20431. }
  20432. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  20433. rigPostProcess.markTextureDirty();
  20434. }
  20435. else {
  20436. cam._postProcesses = this._postProcesses.slice(0);
  20437. }
  20438. }
  20439. };
  20440. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  20441. if (insertAt === void 0) { insertAt = null; }
  20442. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  20443. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  20444. return 0;
  20445. }
  20446. if (insertAt == null || insertAt < 0) {
  20447. this._postProcesses.push(postProcess);
  20448. }
  20449. else if (this._postProcesses[insertAt] === null) {
  20450. this._postProcesses[insertAt] = postProcess;
  20451. }
  20452. else {
  20453. this._postProcesses.splice(insertAt, 0, postProcess);
  20454. }
  20455. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20456. return this._postProcesses.indexOf(postProcess);
  20457. };
  20458. Camera.prototype.detachPostProcess = function (postProcess) {
  20459. var idx = this._postProcesses.indexOf(postProcess);
  20460. if (idx !== -1) {
  20461. this._postProcesses[idx] = null;
  20462. }
  20463. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20464. };
  20465. Camera.prototype.getWorldMatrix = function () {
  20466. if (!this._worldMatrix) {
  20467. this._worldMatrix = BABYLON.Matrix.Identity();
  20468. }
  20469. var viewMatrix = this.getViewMatrix();
  20470. viewMatrix.invertToRef(this._worldMatrix);
  20471. return this._worldMatrix;
  20472. };
  20473. Camera.prototype._getViewMatrix = function () {
  20474. return BABYLON.Matrix.Identity();
  20475. };
  20476. Camera.prototype.getViewMatrix = function (force) {
  20477. if (!force && this._isSynchronizedViewMatrix()) {
  20478. return this._computedViewMatrix;
  20479. }
  20480. this.updateCache();
  20481. this._computedViewMatrix = this._getViewMatrix();
  20482. this._currentRenderId = this.getScene().getRenderId();
  20483. this._childRenderId = this._currentRenderId;
  20484. this._refreshFrustumPlanes = true;
  20485. if (!this.parent || !this.parent.getWorldMatrix) {
  20486. this._globalPosition.copyFrom(this.position);
  20487. }
  20488. else {
  20489. if (!this._worldMatrix) {
  20490. this._worldMatrix = BABYLON.Matrix.Identity();
  20491. }
  20492. this._computedViewMatrix.invertToRef(this._worldMatrix);
  20493. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  20494. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  20495. this._computedViewMatrix.invert();
  20496. this._markSyncedWithParent();
  20497. }
  20498. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  20499. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  20500. }
  20501. this.onViewMatrixChangedObservable.notifyObservers(this);
  20502. return this._computedViewMatrix;
  20503. };
  20504. Camera.prototype.freezeProjectionMatrix = function (projection) {
  20505. this._doNotComputeProjectionMatrix = true;
  20506. if (projection !== undefined) {
  20507. this._projectionMatrix = projection;
  20508. }
  20509. };
  20510. ;
  20511. Camera.prototype.unfreezeProjectionMatrix = function () {
  20512. this._doNotComputeProjectionMatrix = false;
  20513. };
  20514. ;
  20515. Camera.prototype.getProjectionMatrix = function (force) {
  20516. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  20517. return this._projectionMatrix;
  20518. }
  20519. // Cache
  20520. this._cache.mode = this.mode;
  20521. this._cache.minZ = this.minZ;
  20522. this._cache.maxZ = this.maxZ;
  20523. // Matrix
  20524. this._refreshFrustumPlanes = true;
  20525. var engine = this.getEngine();
  20526. var scene = this.getScene();
  20527. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20528. this._cache.fov = this.fov;
  20529. this._cache.fovMode = this.fovMode;
  20530. this._cache.aspectRatio = engine.getAspectRatio(this);
  20531. if (this.minZ <= 0) {
  20532. this.minZ = 0.1;
  20533. }
  20534. if (scene.useRightHandedSystem) {
  20535. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20536. }
  20537. else {
  20538. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20539. }
  20540. }
  20541. else {
  20542. var halfWidth = engine.getRenderWidth() / 2.0;
  20543. var halfHeight = engine.getRenderHeight() / 2.0;
  20544. if (scene.useRightHandedSystem) {
  20545. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20546. }
  20547. else {
  20548. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20549. }
  20550. this._cache.orthoLeft = this.orthoLeft;
  20551. this._cache.orthoRight = this.orthoRight;
  20552. this._cache.orthoBottom = this.orthoBottom;
  20553. this._cache.orthoTop = this.orthoTop;
  20554. this._cache.renderWidth = engine.getRenderWidth();
  20555. this._cache.renderHeight = engine.getRenderHeight();
  20556. }
  20557. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  20558. return this._projectionMatrix;
  20559. };
  20560. Camera.prototype.getTranformationMatrix = function () {
  20561. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20562. return this._transformMatrix;
  20563. };
  20564. Camera.prototype.updateFrustumPlanes = function () {
  20565. if (!this._refreshFrustumPlanes) {
  20566. return;
  20567. }
  20568. this.getTranformationMatrix();
  20569. if (!this._frustumPlanes) {
  20570. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20571. }
  20572. else {
  20573. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20574. }
  20575. this._refreshFrustumPlanes = false;
  20576. };
  20577. Camera.prototype.isInFrustum = function (target) {
  20578. this.updateFrustumPlanes();
  20579. return target.isInFrustum(this._frustumPlanes);
  20580. };
  20581. Camera.prototype.isCompletelyInFrustum = function (target) {
  20582. this.updateFrustumPlanes();
  20583. return target.isCompletelyInFrustum(this._frustumPlanes);
  20584. };
  20585. Camera.prototype.getForwardRay = function (length, transform, origin) {
  20586. if (length === void 0) { length = 100; }
  20587. if (!transform) {
  20588. transform = this.getWorldMatrix();
  20589. }
  20590. if (!origin) {
  20591. origin = this.position;
  20592. }
  20593. var forward = new BABYLON.Vector3(0, 0, 1);
  20594. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  20595. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  20596. return new BABYLON.Ray(origin, direction, length);
  20597. };
  20598. /**
  20599. * Releases resources associated with this node.
  20600. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20601. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20602. */
  20603. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20604. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20605. // Observables
  20606. this.onViewMatrixChangedObservable.clear();
  20607. this.onProjectionMatrixChangedObservable.clear();
  20608. this.onAfterCheckInputsObservable.clear();
  20609. this.onRestoreStateObservable.clear();
  20610. // Inputs
  20611. if (this.inputs) {
  20612. this.inputs.clear();
  20613. }
  20614. // Animations
  20615. this.getScene().stopAnimation(this);
  20616. // Remove from scene
  20617. this.getScene().removeCamera(this);
  20618. while (this._rigCameras.length > 0) {
  20619. var camera = this._rigCameras.pop();
  20620. if (camera) {
  20621. camera.dispose();
  20622. }
  20623. }
  20624. // Postprocesses
  20625. if (this._rigPostProcess) {
  20626. this._rigPostProcess.dispose(this);
  20627. this._rigPostProcess = null;
  20628. this._postProcesses = [];
  20629. }
  20630. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20631. this._rigPostProcess = null;
  20632. this._postProcesses = [];
  20633. }
  20634. else {
  20635. var i = this._postProcesses.length;
  20636. while (--i >= 0) {
  20637. var postProcess = this._postProcesses[i];
  20638. if (postProcess) {
  20639. postProcess.dispose(this);
  20640. }
  20641. }
  20642. }
  20643. // Render targets
  20644. var i = this.customRenderTargets.length;
  20645. while (--i >= 0) {
  20646. this.customRenderTargets[i].dispose();
  20647. }
  20648. this.customRenderTargets = [];
  20649. // Active Meshes
  20650. this._activeMeshes.dispose();
  20651. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20652. };
  20653. Object.defineProperty(Camera.prototype, "leftCamera", {
  20654. // ---- Camera rigs section ----
  20655. get: function () {
  20656. if (this._rigCameras.length < 1) {
  20657. return null;
  20658. }
  20659. return this._rigCameras[0];
  20660. },
  20661. enumerable: true,
  20662. configurable: true
  20663. });
  20664. Object.defineProperty(Camera.prototype, "rightCamera", {
  20665. get: function () {
  20666. if (this._rigCameras.length < 2) {
  20667. return null;
  20668. }
  20669. return this._rigCameras[1];
  20670. },
  20671. enumerable: true,
  20672. configurable: true
  20673. });
  20674. Camera.prototype.getLeftTarget = function () {
  20675. if (this._rigCameras.length < 1) {
  20676. return null;
  20677. }
  20678. return this._rigCameras[0].getTarget();
  20679. };
  20680. Camera.prototype.getRightTarget = function () {
  20681. if (this._rigCameras.length < 2) {
  20682. return null;
  20683. }
  20684. return this._rigCameras[1].getTarget();
  20685. };
  20686. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  20687. if (this.cameraRigMode === mode) {
  20688. return;
  20689. }
  20690. while (this._rigCameras.length > 0) {
  20691. var camera = this._rigCameras.pop();
  20692. if (camera) {
  20693. camera.dispose();
  20694. }
  20695. }
  20696. this.cameraRigMode = mode;
  20697. this._cameraRigParams = {};
  20698. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  20699. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  20700. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  20701. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  20702. // create the rig cameras, unless none
  20703. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20704. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  20705. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  20706. if (leftCamera && rightCamera) {
  20707. this._rigCameras.push(leftCamera);
  20708. this._rigCameras.push(rightCamera);
  20709. }
  20710. }
  20711. switch (this.cameraRigMode) {
  20712. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  20713. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20714. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  20715. break;
  20716. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  20717. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  20718. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  20719. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20720. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20721. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  20722. break;
  20723. case Camera.RIG_MODE_VR:
  20724. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  20725. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  20726. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20727. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20728. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  20729. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  20730. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  20731. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  20732. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20733. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20734. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  20735. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  20736. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  20737. if (metrics.compensateDistortion) {
  20738. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  20739. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  20740. }
  20741. break;
  20742. case Camera.RIG_MODE_WEBVR:
  20743. if (rigParams.vrDisplay) {
  20744. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  20745. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  20746. //Left eye
  20747. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20748. this._rigCameras[0].setCameraRigParameter("left", true);
  20749. //leaving this for future reference
  20750. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  20751. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  20752. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  20753. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20754. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20755. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20756. this._rigCameras[0].parent = this;
  20757. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  20758. //Right eye
  20759. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20760. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  20761. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  20762. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  20763. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20764. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20765. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20766. this._rigCameras[1].parent = this;
  20767. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  20768. if (Camera.UseAlternateWebVRRendering) {
  20769. this._rigCameras[1]._skipRendering = true;
  20770. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20771. }
  20772. }
  20773. break;
  20774. }
  20775. this._cascadePostProcessesToRigCams();
  20776. this.update();
  20777. };
  20778. Camera.prototype._getVRProjectionMatrix = function () {
  20779. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20780. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20781. return this._projectionMatrix;
  20782. };
  20783. Camera.prototype._updateCameraRotationMatrix = function () {
  20784. //Here for WebVR
  20785. };
  20786. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20787. //Here for WebVR
  20788. };
  20789. /**
  20790. * This function MUST be overwritten by the different WebVR cameras available.
  20791. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20792. */
  20793. Camera.prototype._getWebVRProjectionMatrix = function () {
  20794. return BABYLON.Matrix.Identity();
  20795. };
  20796. /**
  20797. * This function MUST be overwritten by the different WebVR cameras available.
  20798. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20799. */
  20800. Camera.prototype._getWebVRViewMatrix = function () {
  20801. return BABYLON.Matrix.Identity();
  20802. };
  20803. Camera.prototype.setCameraRigParameter = function (name, value) {
  20804. if (!this._cameraRigParams) {
  20805. this._cameraRigParams = {};
  20806. }
  20807. this._cameraRigParams[name] = value;
  20808. //provisionnally:
  20809. if (name === "interaxialDistance") {
  20810. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20811. }
  20812. };
  20813. /**
  20814. * needs to be overridden by children so sub has required properties to be copied
  20815. */
  20816. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20817. return null;
  20818. };
  20819. /**
  20820. * May need to be overridden by children
  20821. */
  20822. Camera.prototype._updateRigCameras = function () {
  20823. for (var i = 0; i < this._rigCameras.length; i++) {
  20824. this._rigCameras[i].minZ = this.minZ;
  20825. this._rigCameras[i].maxZ = this.maxZ;
  20826. this._rigCameras[i].fov = this.fov;
  20827. }
  20828. // only update viewport when ANAGLYPH
  20829. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20830. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20831. }
  20832. };
  20833. Camera.prototype._setupInputs = function () {
  20834. };
  20835. Camera.prototype.serialize = function () {
  20836. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20837. // Type
  20838. serializationObject.type = this.getClassName();
  20839. // Parent
  20840. if (this.parent) {
  20841. serializationObject.parentId = this.parent.id;
  20842. }
  20843. if (this.inputs) {
  20844. this.inputs.serialize(serializationObject);
  20845. }
  20846. // Animations
  20847. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20848. serializationObject.ranges = this.serializeAnimationRanges();
  20849. return serializationObject;
  20850. };
  20851. Camera.prototype.clone = function (name) {
  20852. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20853. };
  20854. Camera.prototype.getDirection = function (localAxis) {
  20855. var result = BABYLON.Vector3.Zero();
  20856. this.getDirectionToRef(localAxis, result);
  20857. return result;
  20858. };
  20859. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20860. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20861. };
  20862. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20863. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20864. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20865. switch (type) {
  20866. case "ArcRotateCamera":
  20867. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20868. case "DeviceOrientationCamera":
  20869. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20870. case "FollowCamera":
  20871. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20872. case "ArcFollowCamera":
  20873. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20874. case "GamepadCamera":
  20875. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20876. case "TouchCamera":
  20877. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20878. case "VirtualJoysticksCamera":
  20879. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20880. case "WebVRFreeCamera":
  20881. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20882. case "WebVRGamepadCamera":
  20883. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20884. case "VRDeviceOrientationFreeCamera":
  20885. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20886. case "VRDeviceOrientationGamepadCamera":
  20887. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20888. case "AnaglyphArcRotateCamera":
  20889. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20890. case "AnaglyphFreeCamera":
  20891. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20892. case "AnaglyphGamepadCamera":
  20893. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20894. case "AnaglyphUniversalCamera":
  20895. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20896. case "StereoscopicArcRotateCamera":
  20897. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20898. case "StereoscopicFreeCamera":
  20899. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20900. case "StereoscopicGamepadCamera":
  20901. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20902. case "StereoscopicUniversalCamera":
  20903. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20904. case "FreeCamera":// Forcing Universal here
  20905. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20906. default:// Universal Camera is the default value
  20907. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20908. }
  20909. };
  20910. Camera.prototype.computeWorldMatrix = function () {
  20911. return this.getWorldMatrix();
  20912. };
  20913. Camera.Parse = function (parsedCamera, scene) {
  20914. var type = parsedCamera.type;
  20915. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20916. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20917. // Parent
  20918. if (parsedCamera.parentId) {
  20919. camera._waitingParentId = parsedCamera.parentId;
  20920. }
  20921. //If camera has an input manager, let it parse inputs settings
  20922. if (camera.inputs) {
  20923. camera.inputs.parse(parsedCamera);
  20924. camera._setupInputs();
  20925. }
  20926. if (camera.setPosition) {
  20927. camera.position.copyFromFloats(0, 0, 0);
  20928. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20929. }
  20930. // Target
  20931. if (parsedCamera.target) {
  20932. if (camera.setTarget) {
  20933. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20934. }
  20935. }
  20936. // Apply 3d rig, when found
  20937. if (parsedCamera.cameraRigMode) {
  20938. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20939. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20940. }
  20941. // Animations
  20942. if (parsedCamera.animations) {
  20943. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20944. var parsedAnimation = parsedCamera.animations[animationIndex];
  20945. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20946. }
  20947. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20948. }
  20949. if (parsedCamera.autoAnimate) {
  20950. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20951. }
  20952. return camera;
  20953. };
  20954. // Statics
  20955. Camera._PERSPECTIVE_CAMERA = 0;
  20956. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20957. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20958. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20959. Camera._RIG_MODE_NONE = 0;
  20960. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20961. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20962. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20963. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20964. Camera._RIG_MODE_VR = 20;
  20965. Camera._RIG_MODE_WEBVR = 21;
  20966. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20967. Camera.UseAlternateWebVRRendering = false;
  20968. __decorate([
  20969. BABYLON.serializeAsVector3()
  20970. ], Camera.prototype, "position", void 0);
  20971. __decorate([
  20972. BABYLON.serializeAsVector3()
  20973. ], Camera.prototype, "upVector", void 0);
  20974. __decorate([
  20975. BABYLON.serialize()
  20976. ], Camera.prototype, "orthoLeft", void 0);
  20977. __decorate([
  20978. BABYLON.serialize()
  20979. ], Camera.prototype, "orthoRight", void 0);
  20980. __decorate([
  20981. BABYLON.serialize()
  20982. ], Camera.prototype, "orthoBottom", void 0);
  20983. __decorate([
  20984. BABYLON.serialize()
  20985. ], Camera.prototype, "orthoTop", void 0);
  20986. __decorate([
  20987. BABYLON.serialize()
  20988. ], Camera.prototype, "fov", void 0);
  20989. __decorate([
  20990. BABYLON.serialize()
  20991. ], Camera.prototype, "minZ", void 0);
  20992. __decorate([
  20993. BABYLON.serialize()
  20994. ], Camera.prototype, "maxZ", void 0);
  20995. __decorate([
  20996. BABYLON.serialize()
  20997. ], Camera.prototype, "inertia", void 0);
  20998. __decorate([
  20999. BABYLON.serialize()
  21000. ], Camera.prototype, "mode", void 0);
  21001. __decorate([
  21002. BABYLON.serialize()
  21003. ], Camera.prototype, "layerMask", void 0);
  21004. __decorate([
  21005. BABYLON.serialize()
  21006. ], Camera.prototype, "fovMode", void 0);
  21007. __decorate([
  21008. BABYLON.serialize()
  21009. ], Camera.prototype, "cameraRigMode", void 0);
  21010. __decorate([
  21011. BABYLON.serialize()
  21012. ], Camera.prototype, "interaxialDistance", void 0);
  21013. __decorate([
  21014. BABYLON.serialize()
  21015. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  21016. return Camera;
  21017. }(BABYLON.Node));
  21018. BABYLON.Camera = Camera;
  21019. })(BABYLON || (BABYLON = {}));
  21020. //# sourceMappingURL=babylon.camera.js.map
  21021. "use strict";
  21022. var BABYLON;
  21023. (function (BABYLON) {
  21024. var RenderingManager = /** @class */ (function () {
  21025. function RenderingManager(scene) {
  21026. this._renderingGroups = new Array();
  21027. this._autoClearDepthStencil = {};
  21028. this._customOpaqueSortCompareFn = {};
  21029. this._customAlphaTestSortCompareFn = {};
  21030. this._customTransparentSortCompareFn = {};
  21031. this._renderinGroupInfo = null;
  21032. this._scene = scene;
  21033. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  21034. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  21035. }
  21036. }
  21037. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  21038. if (depth === void 0) { depth = true; }
  21039. if (stencil === void 0) { stencil = true; }
  21040. if (this._depthStencilBufferAlreadyCleaned) {
  21041. return;
  21042. }
  21043. this._scene.getEngine().clear(null, false, depth, stencil);
  21044. this._depthStencilBufferAlreadyCleaned = true;
  21045. };
  21046. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  21047. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  21048. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  21049. var info = null;
  21050. if (observable) {
  21051. if (!this._renderinGroupInfo) {
  21052. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  21053. }
  21054. info = this._renderinGroupInfo;
  21055. info.scene = this._scene;
  21056. info.camera = this._scene.activeCamera;
  21057. }
  21058. // Dispatch sprites
  21059. if (renderSprites) {
  21060. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  21061. var manager = this._scene.spriteManagers[index];
  21062. this.dispatchSprites(manager);
  21063. }
  21064. }
  21065. // Render
  21066. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  21067. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  21068. var renderingGroup = this._renderingGroups[index];
  21069. if (!renderingGroup && !observable)
  21070. continue;
  21071. var renderingGroupMask = 0;
  21072. // Fire PRECLEAR stage
  21073. if (observable && info) {
  21074. renderingGroupMask = Math.pow(2, index);
  21075. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  21076. info.renderingGroupId = index;
  21077. observable.notifyObservers(info, renderingGroupMask);
  21078. }
  21079. // Clear depth/stencil if needed
  21080. if (RenderingManager.AUTOCLEAR) {
  21081. var autoClear = this._autoClearDepthStencil[index];
  21082. if (autoClear && autoClear.autoClear) {
  21083. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  21084. }
  21085. }
  21086. if (observable && info) {
  21087. // Fire PREOPAQUE stage
  21088. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  21089. observable.notifyObservers(info, renderingGroupMask);
  21090. // Fire PRETRANSPARENT stage
  21091. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  21092. observable.notifyObservers(info, renderingGroupMask);
  21093. }
  21094. if (renderingGroup)
  21095. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  21096. // Fire POSTTRANSPARENT stage
  21097. if (observable && info) {
  21098. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  21099. observable.notifyObservers(info, renderingGroupMask);
  21100. }
  21101. }
  21102. };
  21103. RenderingManager.prototype.reset = function () {
  21104. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  21105. var renderingGroup = this._renderingGroups[index];
  21106. if (renderingGroup) {
  21107. renderingGroup.prepare();
  21108. }
  21109. }
  21110. };
  21111. RenderingManager.prototype.dispose = function () {
  21112. this.freeRenderingGroups();
  21113. this._renderingGroups.length = 0;
  21114. };
  21115. /**
  21116. * Clear the info related to rendering groups preventing retention points during dispose.
  21117. */
  21118. RenderingManager.prototype.freeRenderingGroups = function () {
  21119. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  21120. var renderingGroup = this._renderingGroups[index];
  21121. if (renderingGroup) {
  21122. renderingGroup.dispose();
  21123. }
  21124. }
  21125. };
  21126. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  21127. if (this._renderingGroups[renderingGroupId] === undefined) {
  21128. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  21129. }
  21130. };
  21131. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  21132. var renderingGroupId = spriteManager.renderingGroupId || 0;
  21133. this._prepareRenderingGroup(renderingGroupId);
  21134. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  21135. };
  21136. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  21137. var renderingGroupId = particleSystem.renderingGroupId || 0;
  21138. this._prepareRenderingGroup(renderingGroupId);
  21139. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  21140. };
  21141. /**
  21142. * @param subMesh The submesh to dispatch
  21143. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21144. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21145. */
  21146. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  21147. if (mesh === undefined) {
  21148. mesh = subMesh.getMesh();
  21149. }
  21150. var renderingGroupId = mesh.renderingGroupId || 0;
  21151. this._prepareRenderingGroup(renderingGroupId);
  21152. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  21153. };
  21154. /**
  21155. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  21156. * This allowed control for front to back rendering or reversly depending of the special needs.
  21157. *
  21158. * @param renderingGroupId The rendering group id corresponding to its index
  21159. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  21160. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  21161. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  21162. */
  21163. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21164. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21165. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21166. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21167. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  21168. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  21169. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  21170. if (this._renderingGroups[renderingGroupId]) {
  21171. var group = this._renderingGroups[renderingGroupId];
  21172. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  21173. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  21174. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  21175. }
  21176. };
  21177. /**
  21178. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  21179. *
  21180. * @param renderingGroupId The rendering group id corresponding to its index
  21181. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  21182. * @param depth Automatically clears depth between groups if true and autoClear is true.
  21183. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  21184. */
  21185. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  21186. if (depth === void 0) { depth = true; }
  21187. if (stencil === void 0) { stencil = true; }
  21188. this._autoClearDepthStencil[renderingGroupId] = {
  21189. autoClear: autoClearDepthStencil,
  21190. depth: depth,
  21191. stencil: stencil
  21192. };
  21193. };
  21194. /**
  21195. * The max id used for rendering groups (not included)
  21196. */
  21197. RenderingManager.MAX_RENDERINGGROUPS = 4;
  21198. /**
  21199. * The min id used for rendering groups (included)
  21200. */
  21201. RenderingManager.MIN_RENDERINGGROUPS = 0;
  21202. /**
  21203. * Used to globally prevent autoclearing scenes.
  21204. */
  21205. RenderingManager.AUTOCLEAR = true;
  21206. return RenderingManager;
  21207. }());
  21208. BABYLON.RenderingManager = RenderingManager;
  21209. })(BABYLON || (BABYLON = {}));
  21210. //# sourceMappingURL=babylon.renderingManager.js.map
  21211. "use strict";
  21212. var BABYLON;
  21213. (function (BABYLON) {
  21214. var RenderingGroup = /** @class */ (function () {
  21215. /**
  21216. * Creates a new rendering group.
  21217. * @param index The rendering group index
  21218. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  21219. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  21220. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  21221. */
  21222. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21223. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21224. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21225. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21226. this.index = index;
  21227. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  21228. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  21229. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  21230. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  21231. this._particleSystems = new BABYLON.SmartArray(256);
  21232. this._spriteManagers = new BABYLON.SmartArray(256);
  21233. this._edgesRenderers = new BABYLON.SmartArray(16);
  21234. this._scene = scene;
  21235. this.opaqueSortCompareFn = opaqueSortCompareFn;
  21236. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  21237. this.transparentSortCompareFn = transparentSortCompareFn;
  21238. }
  21239. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  21240. /**
  21241. * Set the opaque sort comparison function.
  21242. * If null the sub meshes will be render in the order they were created
  21243. */
  21244. set: function (value) {
  21245. this._opaqueSortCompareFn = value;
  21246. if (value) {
  21247. this._renderOpaque = this.renderOpaqueSorted;
  21248. }
  21249. else {
  21250. this._renderOpaque = RenderingGroup.renderUnsorted;
  21251. }
  21252. },
  21253. enumerable: true,
  21254. configurable: true
  21255. });
  21256. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  21257. /**
  21258. * Set the alpha test sort comparison function.
  21259. * If null the sub meshes will be render in the order they were created
  21260. */
  21261. set: function (value) {
  21262. this._alphaTestSortCompareFn = value;
  21263. if (value) {
  21264. this._renderAlphaTest = this.renderAlphaTestSorted;
  21265. }
  21266. else {
  21267. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  21268. }
  21269. },
  21270. enumerable: true,
  21271. configurable: true
  21272. });
  21273. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  21274. /**
  21275. * Set the transparent sort comparison function.
  21276. * If null the sub meshes will be render in the order they were created
  21277. */
  21278. set: function (value) {
  21279. if (value) {
  21280. this._transparentSortCompareFn = value;
  21281. }
  21282. else {
  21283. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  21284. }
  21285. this._renderTransparent = this.renderTransparentSorted;
  21286. },
  21287. enumerable: true,
  21288. configurable: true
  21289. });
  21290. /**
  21291. * Render all the sub meshes contained in the group.
  21292. * @param customRenderFunction Used to override the default render behaviour of the group.
  21293. * @returns true if rendered some submeshes.
  21294. */
  21295. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  21296. if (customRenderFunction) {
  21297. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  21298. return;
  21299. }
  21300. var engine = this._scene.getEngine();
  21301. // Depth only
  21302. if (this._depthOnlySubMeshes.length !== 0) {
  21303. engine.setColorWrite(false);
  21304. this._renderAlphaTest(this._depthOnlySubMeshes);
  21305. engine.setColorWrite(true);
  21306. }
  21307. // Opaque
  21308. if (this._opaqueSubMeshes.length !== 0) {
  21309. this._renderOpaque(this._opaqueSubMeshes);
  21310. }
  21311. // Alpha test
  21312. if (this._alphaTestSubMeshes.length !== 0) {
  21313. this._renderAlphaTest(this._alphaTestSubMeshes);
  21314. }
  21315. var stencilState = engine.getStencilBuffer();
  21316. engine.setStencilBuffer(false);
  21317. // Sprites
  21318. if (renderSprites) {
  21319. this._renderSprites();
  21320. }
  21321. // Particles
  21322. if (renderParticles) {
  21323. this._renderParticles(activeMeshes);
  21324. }
  21325. if (this.onBeforeTransparentRendering) {
  21326. this.onBeforeTransparentRendering();
  21327. }
  21328. // Transparent
  21329. if (this._transparentSubMeshes.length !== 0) {
  21330. this._renderTransparent(this._transparentSubMeshes);
  21331. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21332. }
  21333. // Set back stencil to false in case it changes before the edge renderer.
  21334. engine.setStencilBuffer(false);
  21335. // Edges
  21336. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  21337. this._edgesRenderers.data[edgesRendererIndex].render();
  21338. }
  21339. // Restore Stencil state.
  21340. engine.setStencilBuffer(stencilState);
  21341. };
  21342. /**
  21343. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  21344. * @param subMeshes The submeshes to render
  21345. */
  21346. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  21347. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  21348. };
  21349. /**
  21350. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  21351. * @param subMeshes The submeshes to render
  21352. */
  21353. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  21354. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  21355. };
  21356. /**
  21357. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  21358. * @param subMeshes The submeshes to render
  21359. */
  21360. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  21361. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  21362. };
  21363. /**
  21364. * Renders the submeshes in a specified order.
  21365. * @param subMeshes The submeshes to sort before render
  21366. * @param sortCompareFn The comparison function use to sort
  21367. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  21368. * @param transparent Specifies to activate blending if true
  21369. */
  21370. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  21371. var subIndex = 0;
  21372. var subMesh;
  21373. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  21374. for (; subIndex < subMeshes.length; subIndex++) {
  21375. subMesh = subMeshes.data[subIndex];
  21376. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  21377. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  21378. }
  21379. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  21380. if (sortCompareFn) {
  21381. sortedArray.sort(sortCompareFn);
  21382. }
  21383. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  21384. subMesh = sortedArray[subIndex];
  21385. if (transparent) {
  21386. var material = subMesh.getMaterial();
  21387. if (material && material.needDepthPrePass) {
  21388. var engine = material.getScene().getEngine();
  21389. engine.setColorWrite(false);
  21390. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21391. subMesh.render(false);
  21392. engine.setColorWrite(true);
  21393. }
  21394. }
  21395. subMesh.render(transparent);
  21396. }
  21397. };
  21398. /**
  21399. * Renders the submeshes in the order they were dispatched (no sort applied).
  21400. * @param subMeshes The submeshes to render
  21401. */
  21402. RenderingGroup.renderUnsorted = function (subMeshes) {
  21403. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  21404. var submesh = subMeshes.data[subIndex];
  21405. submesh.render(false);
  21406. }
  21407. };
  21408. /**
  21409. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21410. * are rendered back to front if in the same alpha index.
  21411. *
  21412. * @param a The first submesh
  21413. * @param b The second submesh
  21414. * @returns The result of the comparison
  21415. */
  21416. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  21417. // Alpha index first
  21418. if (a._alphaIndex > b._alphaIndex) {
  21419. return 1;
  21420. }
  21421. if (a._alphaIndex < b._alphaIndex) {
  21422. return -1;
  21423. }
  21424. // Then distance to camera
  21425. return RenderingGroup.backToFrontSortCompare(a, b);
  21426. };
  21427. /**
  21428. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21429. * are rendered back to front.
  21430. *
  21431. * @param a The first submesh
  21432. * @param b The second submesh
  21433. * @returns The result of the comparison
  21434. */
  21435. RenderingGroup.backToFrontSortCompare = function (a, b) {
  21436. // Then distance to camera
  21437. if (a._distanceToCamera < b._distanceToCamera) {
  21438. return 1;
  21439. }
  21440. if (a._distanceToCamera > b._distanceToCamera) {
  21441. return -1;
  21442. }
  21443. return 0;
  21444. };
  21445. /**
  21446. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21447. * are rendered front to back (prevent overdraw).
  21448. *
  21449. * @param a The first submesh
  21450. * @param b The second submesh
  21451. * @returns The result of the comparison
  21452. */
  21453. RenderingGroup.frontToBackSortCompare = function (a, b) {
  21454. // Then distance to camera
  21455. if (a._distanceToCamera < b._distanceToCamera) {
  21456. return -1;
  21457. }
  21458. if (a._distanceToCamera > b._distanceToCamera) {
  21459. return 1;
  21460. }
  21461. return 0;
  21462. };
  21463. /**
  21464. * Resets the different lists of submeshes to prepare a new frame.
  21465. */
  21466. RenderingGroup.prototype.prepare = function () {
  21467. this._opaqueSubMeshes.reset();
  21468. this._transparentSubMeshes.reset();
  21469. this._alphaTestSubMeshes.reset();
  21470. this._depthOnlySubMeshes.reset();
  21471. this._particleSystems.reset();
  21472. this._spriteManagers.reset();
  21473. this._edgesRenderers.reset();
  21474. };
  21475. RenderingGroup.prototype.dispose = function () {
  21476. this._opaqueSubMeshes.dispose();
  21477. this._transparentSubMeshes.dispose();
  21478. this._alphaTestSubMeshes.dispose();
  21479. this._depthOnlySubMeshes.dispose();
  21480. this._particleSystems.dispose();
  21481. this._spriteManagers.dispose();
  21482. this._edgesRenderers.dispose();
  21483. };
  21484. /**
  21485. * Inserts the submesh in its correct queue depending on its material.
  21486. * @param subMesh The submesh to dispatch
  21487. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21488. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21489. */
  21490. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  21491. // Get mesh and materials if not provided
  21492. if (mesh === undefined) {
  21493. mesh = subMesh.getMesh();
  21494. }
  21495. if (material === undefined) {
  21496. material = subMesh.getMaterial();
  21497. }
  21498. if (material === null || material === undefined) {
  21499. return;
  21500. }
  21501. if (material.needAlphaBlendingForMesh(mesh)) {
  21502. this._transparentSubMeshes.push(subMesh);
  21503. }
  21504. else if (material.needAlphaTesting()) {
  21505. if (material.needDepthPrePass) {
  21506. this._depthOnlySubMeshes.push(subMesh);
  21507. }
  21508. this._alphaTestSubMeshes.push(subMesh);
  21509. }
  21510. else {
  21511. if (material.needDepthPrePass) {
  21512. this._depthOnlySubMeshes.push(subMesh);
  21513. }
  21514. this._opaqueSubMeshes.push(subMesh); // Opaque
  21515. }
  21516. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  21517. this._edgesRenderers.push(mesh._edgesRenderer);
  21518. }
  21519. };
  21520. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  21521. this._spriteManagers.push(spriteManager);
  21522. };
  21523. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  21524. this._particleSystems.push(particleSystem);
  21525. };
  21526. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  21527. if (this._particleSystems.length === 0) {
  21528. return;
  21529. }
  21530. // Particles
  21531. var activeCamera = this._scene.activeCamera;
  21532. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  21533. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  21534. var particleSystem = this._particleSystems.data[particleIndex];
  21535. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  21536. continue;
  21537. }
  21538. var emitter = particleSystem.emitter;
  21539. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  21540. this._scene._activeParticles.addCount(particleSystem.render(), false);
  21541. }
  21542. }
  21543. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  21544. };
  21545. RenderingGroup.prototype._renderSprites = function () {
  21546. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  21547. return;
  21548. }
  21549. // Sprites
  21550. var activeCamera = this._scene.activeCamera;
  21551. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  21552. for (var id = 0; id < this._spriteManagers.length; id++) {
  21553. var spriteManager = this._spriteManagers.data[id];
  21554. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  21555. spriteManager.render();
  21556. }
  21557. }
  21558. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  21559. };
  21560. return RenderingGroup;
  21561. }());
  21562. BABYLON.RenderingGroup = RenderingGroup;
  21563. })(BABYLON || (BABYLON = {}));
  21564. //# sourceMappingURL=babylon.renderingGroup.js.map
  21565. "use strict";
  21566. var BABYLON;
  21567. (function (BABYLON) {
  21568. var ClickInfo = /** @class */ (function () {
  21569. function ClickInfo() {
  21570. this._singleClick = false;
  21571. this._doubleClick = false;
  21572. this._hasSwiped = false;
  21573. this._ignore = false;
  21574. }
  21575. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  21576. get: function () {
  21577. return this._singleClick;
  21578. },
  21579. set: function (b) {
  21580. this._singleClick = b;
  21581. },
  21582. enumerable: true,
  21583. configurable: true
  21584. });
  21585. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  21586. get: function () {
  21587. return this._doubleClick;
  21588. },
  21589. set: function (b) {
  21590. this._doubleClick = b;
  21591. },
  21592. enumerable: true,
  21593. configurable: true
  21594. });
  21595. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  21596. get: function () {
  21597. return this._hasSwiped;
  21598. },
  21599. set: function (b) {
  21600. this._hasSwiped = b;
  21601. },
  21602. enumerable: true,
  21603. configurable: true
  21604. });
  21605. Object.defineProperty(ClickInfo.prototype, "ignore", {
  21606. get: function () {
  21607. return this._ignore;
  21608. },
  21609. set: function (b) {
  21610. this._ignore = b;
  21611. },
  21612. enumerable: true,
  21613. configurable: true
  21614. });
  21615. return ClickInfo;
  21616. }());
  21617. /**
  21618. * This class is used by the onRenderingGroupObservable
  21619. */
  21620. var RenderingGroupInfo = /** @class */ (function () {
  21621. function RenderingGroupInfo() {
  21622. }
  21623. /**
  21624. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  21625. * This stage will be fired no matter what
  21626. */
  21627. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  21628. /**
  21629. * Called before opaque object are rendered.
  21630. * This stage will be fired only if there's 3D Opaque content to render
  21631. */
  21632. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  21633. /**
  21634. * Called after the opaque objects are rendered and before the transparent ones
  21635. * This stage will be fired only if there's 3D transparent content to render
  21636. */
  21637. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  21638. /**
  21639. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  21640. * This stage will be fired no matter what
  21641. */
  21642. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  21643. return RenderingGroupInfo;
  21644. }());
  21645. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  21646. /**
  21647. * Represents a scene to be rendered by the engine.
  21648. * @see http://doc.babylonjs.com/features/scene
  21649. */
  21650. var Scene = /** @class */ (function () {
  21651. /**
  21652. * @constructor
  21653. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  21654. */
  21655. function Scene(engine) {
  21656. // Members
  21657. this.autoClear = true;
  21658. this.autoClearDepthAndStencil = true;
  21659. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  21660. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21661. this._forceWireframe = false;
  21662. this._forcePointsCloud = false;
  21663. this.forceShowBoundingBoxes = false;
  21664. this.animationsEnabled = true;
  21665. this.useConstantAnimationDeltaTime = false;
  21666. this.constantlyUpdateMeshUnderPointer = false;
  21667. this.hoverCursor = "pointer";
  21668. this.defaultCursor = "";
  21669. /**
  21670. * This is used to call preventDefault() on pointer down
  21671. * in order to block unwanted artifacts like system double clicks
  21672. */
  21673. this.preventDefaultOnPointerDown = true;
  21674. // Metadata
  21675. this.metadata = null;
  21676. /**
  21677. * Use this array to add regular expressions used to disable offline support for specific urls
  21678. */
  21679. this.disableOfflineSupportExceptionRules = new Array();
  21680. /**
  21681. * An event triggered when the scene is disposed.
  21682. */
  21683. this.onDisposeObservable = new BABYLON.Observable();
  21684. this._onDisposeObserver = null;
  21685. /**
  21686. * An event triggered before rendering the scene (right after animations and physics)
  21687. */
  21688. this.onBeforeRenderObservable = new BABYLON.Observable();
  21689. this._onBeforeRenderObserver = null;
  21690. /**
  21691. * An event triggered after rendering the scene
  21692. */
  21693. this.onAfterRenderObservable = new BABYLON.Observable();
  21694. this._onAfterRenderObserver = null;
  21695. /**
  21696. * An event triggered before animating the scene
  21697. */
  21698. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  21699. /**
  21700. * An event triggered after animations processing
  21701. */
  21702. this.onAfterAnimationsObservable = new BABYLON.Observable();
  21703. /**
  21704. * An event triggered before draw calls are ready to be sent
  21705. */
  21706. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  21707. /**
  21708. * An event triggered after draw calls have been sent
  21709. */
  21710. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  21711. /**
  21712. * An event triggered when physic simulation is about to be run
  21713. */
  21714. this.onBeforePhysicsObservable = new BABYLON.Observable();
  21715. /**
  21716. * An event triggered when physic simulation has been done
  21717. */
  21718. this.onAfterPhysicsObservable = new BABYLON.Observable();
  21719. /**
  21720. * An event triggered when the scene is ready
  21721. */
  21722. this.onReadyObservable = new BABYLON.Observable();
  21723. /**
  21724. * An event triggered before rendering a camera
  21725. */
  21726. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  21727. this._onBeforeCameraRenderObserver = null;
  21728. /**
  21729. * An event triggered after rendering a camera
  21730. */
  21731. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  21732. this._onAfterCameraRenderObserver = null;
  21733. /**
  21734. * An event triggered when active meshes evaluation is about to start
  21735. */
  21736. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21737. /**
  21738. * An event triggered when active meshes evaluation is done
  21739. */
  21740. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21741. /**
  21742. * An event triggered when particles rendering is about to start
  21743. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21744. */
  21745. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  21746. /**
  21747. * An event triggered when particles rendering is done
  21748. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21749. */
  21750. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  21751. /**
  21752. * An event triggered when sprites rendering is about to start
  21753. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21754. */
  21755. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  21756. /**
  21757. * An event triggered when sprites rendering is done
  21758. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21759. */
  21760. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  21761. /**
  21762. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  21763. */
  21764. this.onDataLoadedObservable = new BABYLON.Observable();
  21765. /**
  21766. * An event triggered when a camera is created
  21767. */
  21768. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21769. /**
  21770. * An event triggered when a camera is removed
  21771. */
  21772. this.onCameraRemovedObservable = new BABYLON.Observable();
  21773. /**
  21774. * An event triggered when a light is created
  21775. */
  21776. this.onNewLightAddedObservable = new BABYLON.Observable();
  21777. /**
  21778. * An event triggered when a light is removed
  21779. */
  21780. this.onLightRemovedObservable = new BABYLON.Observable();
  21781. /**
  21782. * An event triggered when a geometry is created
  21783. */
  21784. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21785. /**
  21786. * An event triggered when a geometry is removed
  21787. */
  21788. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21789. /**
  21790. * An event triggered when a transform node is created
  21791. */
  21792. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21793. /**
  21794. * An event triggered when a transform node is removed
  21795. */
  21796. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21797. /**
  21798. * An event triggered when a mesh is created
  21799. */
  21800. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21801. /**
  21802. * An event triggered when a mesh is removed
  21803. */
  21804. this.onMeshRemovedObservable = new BABYLON.Observable();
  21805. /**
  21806. * An event triggered when render targets are about to be rendered
  21807. * Can happen multiple times per frame.
  21808. */
  21809. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21810. /**
  21811. * An event triggered when render targets were rendered.
  21812. * Can happen multiple times per frame.
  21813. */
  21814. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21815. /**
  21816. * An event triggered before calculating deterministic simulation step
  21817. */
  21818. this.onBeforeStepObservable = new BABYLON.Observable();
  21819. /**
  21820. * An event triggered after calculating deterministic simulation step
  21821. */
  21822. this.onAfterStepObservable = new BABYLON.Observable();
  21823. /**
  21824. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21825. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21826. * 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)
  21827. */
  21828. this.onRenderingGroupObservable = new BABYLON.Observable();
  21829. // Animations
  21830. this.animations = [];
  21831. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  21832. /**
  21833. * 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).
  21834. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21835. */
  21836. this.onPrePointerObservable = new BABYLON.Observable();
  21837. /**
  21838. * Observable event triggered each time an input event is received from the rendering canvas
  21839. */
  21840. this.onPointerObservable = new BABYLON.Observable();
  21841. this._meshPickProceed = false;
  21842. this._currentPickResult = null;
  21843. this._previousPickResult = null;
  21844. this._totalPointersPressed = 0;
  21845. this._doubleClickOccured = false;
  21846. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21847. this.cameraToUseForPointers = null;
  21848. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21849. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21850. this._startingPointerTime = 0;
  21851. this._previousStartingPointerTime = 0;
  21852. // Deterministic lockstep
  21853. this._timeAccumulator = 0;
  21854. this._currentStepId = 0;
  21855. this._currentInternalStep = 0;
  21856. // Keyboard
  21857. /**
  21858. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21859. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21860. */
  21861. this.onPreKeyboardObservable = new BABYLON.Observable();
  21862. /**
  21863. * Observable event triggered each time an keyboard event is received from the hosting window
  21864. */
  21865. this.onKeyboardObservable = new BABYLON.Observable();
  21866. // Coordinate system
  21867. /**
  21868. * use right-handed coordinate system on this scene.
  21869. */
  21870. this._useRightHandedSystem = false;
  21871. // Fog
  21872. this._fogEnabled = true;
  21873. this._fogMode = Scene.FOGMODE_NONE;
  21874. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21875. this.fogDensity = 0.1;
  21876. this.fogStart = 0;
  21877. this.fogEnd = 1000.0;
  21878. // Lights
  21879. /**
  21880. * is shadow enabled on this scene.
  21881. */
  21882. this._shadowsEnabled = true;
  21883. /**
  21884. * is light enabled on this scene.
  21885. */
  21886. this._lightsEnabled = true;
  21887. /**
  21888. * All of the lights added to this scene.
  21889. */
  21890. this.lights = new Array();
  21891. // Cameras
  21892. /** All of the cameras added to this scene. */
  21893. this.cameras = new Array();
  21894. /** All of the active cameras added to this scene. */
  21895. this.activeCameras = new Array();
  21896. // Meshes
  21897. /**
  21898. * All of the tranform nodes added to this scene.
  21899. */
  21900. this.transformNodes = new Array();
  21901. /**
  21902. * All of the (abstract) meshes added to this scene.
  21903. */
  21904. this.meshes = new Array();
  21905. /**
  21906. * All of the animation groups added to this scene.
  21907. */
  21908. this.animationGroups = new Array();
  21909. // Geometries
  21910. this._geometries = new Array();
  21911. this.materials = new Array();
  21912. this.multiMaterials = new Array();
  21913. // Textures
  21914. this._texturesEnabled = true;
  21915. this.textures = new Array();
  21916. // Particles
  21917. this.particlesEnabled = true;
  21918. this.particleSystems = new Array();
  21919. // Sprites
  21920. this.spritesEnabled = true;
  21921. this.spriteManagers = new Array();
  21922. /**
  21923. * The list of layers (background and foreground) of the scene.
  21924. */
  21925. this.layers = new Array();
  21926. /**
  21927. * The list of effect layers (highlights/glow) contained in the scene.
  21928. */
  21929. this.effectLayers = new Array();
  21930. // Skeletons
  21931. this._skeletonsEnabled = true;
  21932. this.skeletons = new Array();
  21933. // Morph targets
  21934. this.morphTargetManagers = new Array();
  21935. // Lens flares
  21936. this.lensFlaresEnabled = true;
  21937. this.lensFlareSystems = new Array();
  21938. // Collisions
  21939. this.collisionsEnabled = true;
  21940. /** Defines the gravity applied to this scene */
  21941. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21942. // Postprocesses
  21943. this.postProcesses = new Array();
  21944. this.postProcessesEnabled = true;
  21945. // Customs render targets
  21946. this.renderTargetsEnabled = true;
  21947. this.dumpNextRenderTargets = false;
  21948. this.customRenderTargets = new Array();
  21949. // Imported meshes
  21950. this.importedMeshesFiles = new Array();
  21951. // Probes
  21952. this.probesEnabled = true;
  21953. this.reflectionProbes = new Array();
  21954. this._actionManagers = new Array();
  21955. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21956. // Procedural textures
  21957. this.proceduralTexturesEnabled = true;
  21958. this._proceduralTextures = new Array();
  21959. this.soundTracks = new Array();
  21960. this._audioEnabled = true;
  21961. this._headphone = false;
  21962. // Performance counters
  21963. this._totalVertices = new BABYLON.PerfCounter();
  21964. this._activeIndices = new BABYLON.PerfCounter();
  21965. this._activeParticles = new BABYLON.PerfCounter();
  21966. this._activeBones = new BABYLON.PerfCounter();
  21967. this._animationTime = 0;
  21968. this.animationTimeScale = 1;
  21969. this._renderId = 0;
  21970. this._executeWhenReadyTimeoutId = -1;
  21971. this._intermediateRendering = false;
  21972. this._viewUpdateFlag = -1;
  21973. this._projectionUpdateFlag = -1;
  21974. this._alternateViewUpdateFlag = -1;
  21975. this._alternateProjectionUpdateFlag = -1;
  21976. this._toBeDisposed = new BABYLON.SmartArray(256);
  21977. this._activeRequests = new Array();
  21978. this._pendingData = new Array();
  21979. this._isDisposed = false;
  21980. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21981. this._activeMeshes = new BABYLON.SmartArray(256);
  21982. this._processedMaterials = new BABYLON.SmartArray(256);
  21983. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21984. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21985. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21986. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21987. this._activeAnimatables = new Array();
  21988. this._transformMatrix = BABYLON.Matrix.Zero();
  21989. this._useAlternateCameraConfiguration = false;
  21990. this._alternateRendering = false;
  21991. this.requireLightSorting = false;
  21992. this._depthRenderer = {};
  21993. this._activeMeshesFrozen = false;
  21994. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21995. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21996. this._engine.scenes.push(this);
  21997. this._uid = null;
  21998. this._renderingManager = new BABYLON.RenderingManager(this);
  21999. this.postProcessManager = new BABYLON.PostProcessManager(this);
  22000. if (BABYLON.OutlineRenderer) {
  22001. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  22002. }
  22003. if (BABYLON.Tools.IsWindowObjectExist()) {
  22004. this.attachControl();
  22005. }
  22006. //simplification queue
  22007. if (BABYLON.SimplificationQueue) {
  22008. this.simplificationQueue = new BABYLON.SimplificationQueue();
  22009. }
  22010. //collision coordinator initialization. For now legacy per default.
  22011. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  22012. // Uniform Buffer
  22013. this._createUbo();
  22014. // Default Image processing definition.
  22015. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  22016. }
  22017. Object.defineProperty(Scene, "FOGMODE_NONE", {
  22018. /** The fog is deactivated */
  22019. get: function () {
  22020. return Scene._FOGMODE_NONE;
  22021. },
  22022. enumerable: true,
  22023. configurable: true
  22024. });
  22025. Object.defineProperty(Scene, "FOGMODE_EXP", {
  22026. /** The fog density is following an exponential function */
  22027. get: function () {
  22028. return Scene._FOGMODE_EXP;
  22029. },
  22030. enumerable: true,
  22031. configurable: true
  22032. });
  22033. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  22034. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  22035. get: function () {
  22036. return Scene._FOGMODE_EXP2;
  22037. },
  22038. enumerable: true,
  22039. configurable: true
  22040. });
  22041. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  22042. /** The fog density is following a linear function. */
  22043. get: function () {
  22044. return Scene._FOGMODE_LINEAR;
  22045. },
  22046. enumerable: true,
  22047. configurable: true
  22048. });
  22049. Object.defineProperty(Scene.prototype, "environmentTexture", {
  22050. /**
  22051. * Texture used in all pbr material as the reflection texture.
  22052. * As in the majority of the scene they are the same (exception for multi room and so on),
  22053. * this is easier to reference from here than from all the materials.
  22054. */
  22055. get: function () {
  22056. return this._environmentTexture;
  22057. },
  22058. /**
  22059. * Texture used in all pbr material as the reflection texture.
  22060. * As in the majority of the scene they are the same (exception for multi room and so on),
  22061. * this is easier to set here than in all the materials.
  22062. */
  22063. set: function (value) {
  22064. if (this._environmentTexture === value) {
  22065. return;
  22066. }
  22067. this._environmentTexture = value;
  22068. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22069. },
  22070. enumerable: true,
  22071. configurable: true
  22072. });
  22073. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  22074. /**
  22075. * Default image processing configuration used either in the rendering
  22076. * Forward main pass or through the imageProcessingPostProcess if present.
  22077. * As in the majority of the scene they are the same (exception for multi camera),
  22078. * this is easier to reference from here than from all the materials and post process.
  22079. *
  22080. * No setter as we it is a shared configuration, you can set the values instead.
  22081. */
  22082. get: function () {
  22083. return this._imageProcessingConfiguration;
  22084. },
  22085. enumerable: true,
  22086. configurable: true
  22087. });
  22088. Object.defineProperty(Scene.prototype, "forceWireframe", {
  22089. get: function () {
  22090. return this._forceWireframe;
  22091. },
  22092. set: function (value) {
  22093. if (this._forceWireframe === value) {
  22094. return;
  22095. }
  22096. this._forceWireframe = value;
  22097. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22098. },
  22099. enumerable: true,
  22100. configurable: true
  22101. });
  22102. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  22103. get: function () {
  22104. return this._forcePointsCloud;
  22105. },
  22106. set: function (value) {
  22107. if (this._forcePointsCloud === value) {
  22108. return;
  22109. }
  22110. this._forcePointsCloud = value;
  22111. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22112. },
  22113. enumerable: true,
  22114. configurable: true
  22115. });
  22116. Object.defineProperty(Scene.prototype, "onDispose", {
  22117. /** A function to be executed when this scene is disposed. */
  22118. set: function (callback) {
  22119. if (this._onDisposeObserver) {
  22120. this.onDisposeObservable.remove(this._onDisposeObserver);
  22121. }
  22122. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22123. },
  22124. enumerable: true,
  22125. configurable: true
  22126. });
  22127. Object.defineProperty(Scene.prototype, "beforeRender", {
  22128. /** A function to be executed before rendering this scene */
  22129. set: function (callback) {
  22130. if (this._onBeforeRenderObserver) {
  22131. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  22132. }
  22133. if (callback) {
  22134. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  22135. }
  22136. },
  22137. enumerable: true,
  22138. configurable: true
  22139. });
  22140. Object.defineProperty(Scene.prototype, "afterRender", {
  22141. /** A function to be executed after rendering this scene */
  22142. set: function (callback) {
  22143. if (this._onAfterRenderObserver) {
  22144. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  22145. }
  22146. if (callback) {
  22147. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  22148. }
  22149. },
  22150. enumerable: true,
  22151. configurable: true
  22152. });
  22153. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  22154. set: function (callback) {
  22155. if (this._onBeforeCameraRenderObserver) {
  22156. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  22157. }
  22158. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  22159. },
  22160. enumerable: true,
  22161. configurable: true
  22162. });
  22163. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  22164. set: function (callback) {
  22165. if (this._onAfterCameraRenderObserver) {
  22166. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  22167. }
  22168. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  22169. },
  22170. enumerable: true,
  22171. configurable: true
  22172. });
  22173. Object.defineProperty(Scene.prototype, "gamepadManager", {
  22174. get: function () {
  22175. if (!this._gamepadManager) {
  22176. this._gamepadManager = new BABYLON.GamepadManager(this);
  22177. }
  22178. return this._gamepadManager;
  22179. },
  22180. enumerable: true,
  22181. configurable: true
  22182. });
  22183. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  22184. get: function () {
  22185. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  22186. },
  22187. enumerable: true,
  22188. configurable: true
  22189. });
  22190. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  22191. get: function () {
  22192. return this._useRightHandedSystem;
  22193. },
  22194. set: function (value) {
  22195. if (this._useRightHandedSystem === value) {
  22196. return;
  22197. }
  22198. this._useRightHandedSystem = value;
  22199. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22200. },
  22201. enumerable: true,
  22202. configurable: true
  22203. });
  22204. Scene.prototype.setStepId = function (newStepId) {
  22205. this._currentStepId = newStepId;
  22206. };
  22207. ;
  22208. Scene.prototype.getStepId = function () {
  22209. return this._currentStepId;
  22210. };
  22211. ;
  22212. Scene.prototype.getInternalStep = function () {
  22213. return this._currentInternalStep;
  22214. };
  22215. ;
  22216. Object.defineProperty(Scene.prototype, "fogEnabled", {
  22217. get: function () {
  22218. return this._fogEnabled;
  22219. },
  22220. /**
  22221. * is fog enabled on this scene.
  22222. */
  22223. set: function (value) {
  22224. if (this._fogEnabled === value) {
  22225. return;
  22226. }
  22227. this._fogEnabled = value;
  22228. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22229. },
  22230. enumerable: true,
  22231. configurable: true
  22232. });
  22233. Object.defineProperty(Scene.prototype, "fogMode", {
  22234. get: function () {
  22235. return this._fogMode;
  22236. },
  22237. set: function (value) {
  22238. if (this._fogMode === value) {
  22239. return;
  22240. }
  22241. this._fogMode = value;
  22242. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22243. },
  22244. enumerable: true,
  22245. configurable: true
  22246. });
  22247. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  22248. get: function () {
  22249. return this._shadowsEnabled;
  22250. },
  22251. set: function (value) {
  22252. if (this._shadowsEnabled === value) {
  22253. return;
  22254. }
  22255. this._shadowsEnabled = value;
  22256. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22257. },
  22258. enumerable: true,
  22259. configurable: true
  22260. });
  22261. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  22262. get: function () {
  22263. return this._lightsEnabled;
  22264. },
  22265. set: function (value) {
  22266. if (this._lightsEnabled === value) {
  22267. return;
  22268. }
  22269. this._lightsEnabled = value;
  22270. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22271. },
  22272. enumerable: true,
  22273. configurable: true
  22274. });
  22275. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  22276. /** The default material used on meshes when no material is affected */
  22277. get: function () {
  22278. if (!this._defaultMaterial) {
  22279. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  22280. }
  22281. return this._defaultMaterial;
  22282. },
  22283. /** The default material used on meshes when no material is affected */
  22284. set: function (value) {
  22285. this._defaultMaterial = value;
  22286. },
  22287. enumerable: true,
  22288. configurable: true
  22289. });
  22290. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  22291. get: function () {
  22292. return this._texturesEnabled;
  22293. },
  22294. set: function (value) {
  22295. if (this._texturesEnabled === value) {
  22296. return;
  22297. }
  22298. this._texturesEnabled = value;
  22299. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22300. },
  22301. enumerable: true,
  22302. configurable: true
  22303. });
  22304. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  22305. get: function () {
  22306. return this._skeletonsEnabled;
  22307. },
  22308. set: function (value) {
  22309. if (this._skeletonsEnabled === value) {
  22310. return;
  22311. }
  22312. this._skeletonsEnabled = value;
  22313. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  22314. },
  22315. enumerable: true,
  22316. configurable: true
  22317. });
  22318. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  22319. get: function () {
  22320. if (!this._postProcessRenderPipelineManager) {
  22321. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  22322. }
  22323. return this._postProcessRenderPipelineManager;
  22324. },
  22325. enumerable: true,
  22326. configurable: true
  22327. });
  22328. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  22329. get: function () {
  22330. if (!this._mainSoundTrack) {
  22331. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  22332. }
  22333. return this._mainSoundTrack;
  22334. },
  22335. enumerable: true,
  22336. configurable: true
  22337. });
  22338. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  22339. get: function () {
  22340. return this._alternateRendering;
  22341. },
  22342. enumerable: true,
  22343. configurable: true
  22344. });
  22345. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  22346. get: function () {
  22347. return this._frustumPlanes;
  22348. },
  22349. enumerable: true,
  22350. configurable: true
  22351. });
  22352. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  22353. /**
  22354. * Gets the current geometry buffer associated to the scene.
  22355. */
  22356. get: function () {
  22357. return this._geometryBufferRenderer;
  22358. },
  22359. /**
  22360. * Sets the current geometry buffer for the scene.
  22361. */
  22362. set: function (geometryBufferRenderer) {
  22363. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  22364. this._geometryBufferRenderer = geometryBufferRenderer;
  22365. }
  22366. },
  22367. enumerable: true,
  22368. configurable: true
  22369. });
  22370. Object.defineProperty(Scene.prototype, "debugLayer", {
  22371. // Properties
  22372. get: function () {
  22373. if (!this._debugLayer) {
  22374. this._debugLayer = new BABYLON.DebugLayer(this);
  22375. }
  22376. return this._debugLayer;
  22377. },
  22378. enumerable: true,
  22379. configurable: true
  22380. });
  22381. Object.defineProperty(Scene.prototype, "workerCollisions", {
  22382. get: function () {
  22383. return this._workerCollisions;
  22384. },
  22385. set: function (enabled) {
  22386. if (!BABYLON.CollisionCoordinatorLegacy) {
  22387. return;
  22388. }
  22389. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  22390. this._workerCollisions = enabled;
  22391. if (this.collisionCoordinator) {
  22392. this.collisionCoordinator.destroy();
  22393. }
  22394. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  22395. this.collisionCoordinator.init(this);
  22396. },
  22397. enumerable: true,
  22398. configurable: true
  22399. });
  22400. Object.defineProperty(Scene.prototype, "selectionOctree", {
  22401. get: function () {
  22402. return this._selectionOctree;
  22403. },
  22404. enumerable: true,
  22405. configurable: true
  22406. });
  22407. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  22408. /**
  22409. * The mesh that is currently under the pointer.
  22410. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  22411. */
  22412. get: function () {
  22413. return this._pointerOverMesh;
  22414. },
  22415. enumerable: true,
  22416. configurable: true
  22417. });
  22418. Object.defineProperty(Scene.prototype, "pointerX", {
  22419. /**
  22420. * Current on-screen X position of the pointer
  22421. * @return {number} X position of the pointer
  22422. */
  22423. get: function () {
  22424. return this._pointerX;
  22425. },
  22426. enumerable: true,
  22427. configurable: true
  22428. });
  22429. Object.defineProperty(Scene.prototype, "pointerY", {
  22430. /**
  22431. * Current on-screen Y position of the pointer
  22432. * @return {number} Y position of the pointer
  22433. */
  22434. get: function () {
  22435. return this._pointerY;
  22436. },
  22437. enumerable: true,
  22438. configurable: true
  22439. });
  22440. Scene.prototype.getCachedMaterial = function () {
  22441. return this._cachedMaterial;
  22442. };
  22443. Scene.prototype.getCachedEffect = function () {
  22444. return this._cachedEffect;
  22445. };
  22446. Scene.prototype.getCachedVisibility = function () {
  22447. return this._cachedVisibility;
  22448. };
  22449. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  22450. if (visibility === void 0) { visibility = 1; }
  22451. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  22452. };
  22453. Scene.prototype.getBoundingBoxRenderer = function () {
  22454. if (!this._boundingBoxRenderer) {
  22455. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  22456. }
  22457. return this._boundingBoxRenderer;
  22458. };
  22459. Scene.prototype.getOutlineRenderer = function () {
  22460. return this._outlineRenderer;
  22461. };
  22462. Scene.prototype.getEngine = function () {
  22463. return this._engine;
  22464. };
  22465. Scene.prototype.getTotalVertices = function () {
  22466. return this._totalVertices.current;
  22467. };
  22468. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  22469. get: function () {
  22470. return this._totalVertices;
  22471. },
  22472. enumerable: true,
  22473. configurable: true
  22474. });
  22475. Scene.prototype.getActiveIndices = function () {
  22476. return this._activeIndices.current;
  22477. };
  22478. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  22479. get: function () {
  22480. return this._activeIndices;
  22481. },
  22482. enumerable: true,
  22483. configurable: true
  22484. });
  22485. Scene.prototype.getActiveParticles = function () {
  22486. return this._activeParticles.current;
  22487. };
  22488. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  22489. get: function () {
  22490. return this._activeParticles;
  22491. },
  22492. enumerable: true,
  22493. configurable: true
  22494. });
  22495. Scene.prototype.getActiveBones = function () {
  22496. return this._activeBones.current;
  22497. };
  22498. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  22499. get: function () {
  22500. return this._activeBones;
  22501. },
  22502. enumerable: true,
  22503. configurable: true
  22504. });
  22505. // Stats
  22506. Scene.prototype.getInterFramePerfCounter = function () {
  22507. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22508. return 0;
  22509. };
  22510. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  22511. get: function () {
  22512. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22513. return null;
  22514. },
  22515. enumerable: true,
  22516. configurable: true
  22517. });
  22518. Scene.prototype.getLastFrameDuration = function () {
  22519. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  22520. return 0;
  22521. };
  22522. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  22523. get: function () {
  22524. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22525. return null;
  22526. },
  22527. enumerable: true,
  22528. configurable: true
  22529. });
  22530. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  22531. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  22532. return 0;
  22533. };
  22534. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  22535. get: function () {
  22536. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22537. return null;
  22538. },
  22539. enumerable: true,
  22540. configurable: true
  22541. });
  22542. Scene.prototype.getActiveMeshes = function () {
  22543. return this._activeMeshes;
  22544. };
  22545. Scene.prototype.getRenderTargetsDuration = function () {
  22546. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  22547. return 0;
  22548. };
  22549. Scene.prototype.getRenderDuration = function () {
  22550. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  22551. return 0;
  22552. };
  22553. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  22554. get: function () {
  22555. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22556. return null;
  22557. },
  22558. enumerable: true,
  22559. configurable: true
  22560. });
  22561. Scene.prototype.getParticlesDuration = function () {
  22562. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  22563. return 0;
  22564. };
  22565. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  22566. get: function () {
  22567. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22568. return null;
  22569. },
  22570. enumerable: true,
  22571. configurable: true
  22572. });
  22573. Scene.prototype.getSpritesDuration = function () {
  22574. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  22575. return 0;
  22576. };
  22577. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  22578. get: function () {
  22579. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  22580. return null;
  22581. },
  22582. enumerable: true,
  22583. configurable: true
  22584. });
  22585. Scene.prototype.getAnimationRatio = function () {
  22586. return this._animationRatio;
  22587. };
  22588. Scene.prototype.getRenderId = function () {
  22589. return this._renderId;
  22590. };
  22591. Scene.prototype.incrementRenderId = function () {
  22592. this._renderId++;
  22593. };
  22594. Scene.prototype._updatePointerPosition = function (evt) {
  22595. var canvasRect = this._engine.getRenderingCanvasClientRect();
  22596. if (!canvasRect) {
  22597. return;
  22598. }
  22599. this._pointerX = evt.clientX - canvasRect.left;
  22600. this._pointerY = evt.clientY - canvasRect.top;
  22601. this._unTranslatedPointerX = this._pointerX;
  22602. this._unTranslatedPointerY = this._pointerY;
  22603. };
  22604. Scene.prototype._createUbo = function () {
  22605. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22606. this._sceneUbo.addUniform("viewProjection", 16);
  22607. this._sceneUbo.addUniform("view", 16);
  22608. };
  22609. Scene.prototype._createAlternateUbo = function () {
  22610. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22611. this._alternateSceneUbo.addUniform("viewProjection", 16);
  22612. this._alternateSceneUbo.addUniform("view", 16);
  22613. };
  22614. // Pointers handling
  22615. /**
  22616. * Use this method to simulate a pointer move on a mesh
  22617. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22618. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22619. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22620. */
  22621. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  22622. var evt = new PointerEvent("pointermove", pointerEventInit);
  22623. return this._processPointerMove(pickResult, evt);
  22624. };
  22625. Scene.prototype._processPointerMove = function (pickResult, evt) {
  22626. var canvas = this._engine.getRenderingCanvas();
  22627. if (!canvas) {
  22628. return this;
  22629. }
  22630. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22631. this.setPointerOverSprite(null);
  22632. this.setPointerOverMesh(pickResult.pickedMesh);
  22633. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  22634. if (this._pointerOverMesh.actionManager.hoverCursor) {
  22635. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  22636. }
  22637. else {
  22638. canvas.style.cursor = this.hoverCursor;
  22639. }
  22640. }
  22641. else {
  22642. canvas.style.cursor = this.defaultCursor;
  22643. }
  22644. }
  22645. else {
  22646. this.setPointerOverMesh(null);
  22647. // Sprites
  22648. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  22649. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22650. this.setPointerOverSprite(pickResult.pickedSprite);
  22651. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  22652. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  22653. }
  22654. else {
  22655. canvas.style.cursor = this.hoverCursor;
  22656. }
  22657. }
  22658. else {
  22659. this.setPointerOverSprite(null);
  22660. // Restore pointer
  22661. canvas.style.cursor = this.defaultCursor;
  22662. }
  22663. }
  22664. if (pickResult) {
  22665. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22666. if (this.onPointerMove) {
  22667. this.onPointerMove(evt, pickResult, type);
  22668. }
  22669. if (this.onPointerObservable.hasObservers()) {
  22670. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22671. this.onPointerObservable.notifyObservers(pi, type);
  22672. }
  22673. }
  22674. return this;
  22675. };
  22676. /**
  22677. * Use this method to simulate a pointer down on a mesh
  22678. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22679. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22680. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22681. */
  22682. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  22683. var evt = new PointerEvent("pointerdown", pointerEventInit);
  22684. return this._processPointerDown(pickResult, evt);
  22685. };
  22686. Scene.prototype._processPointerDown = function (pickResult, evt) {
  22687. var _this = this;
  22688. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22689. this._pickedDownMesh = pickResult.pickedMesh;
  22690. var actionManager = pickResult.pickedMesh.actionManager;
  22691. if (actionManager) {
  22692. if (actionManager.hasPickTriggers) {
  22693. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22694. switch (evt.button) {
  22695. case 0:
  22696. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22697. break;
  22698. case 1:
  22699. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22700. break;
  22701. case 2:
  22702. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22703. break;
  22704. }
  22705. }
  22706. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  22707. window.setTimeout(function () {
  22708. 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);
  22709. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  22710. if (_this._totalPointersPressed !== 0 &&
  22711. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  22712. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  22713. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  22714. _this._startingPointerTime = 0;
  22715. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22716. }
  22717. }
  22718. }, Scene.LongPressDelay);
  22719. }
  22720. }
  22721. }
  22722. if (pickResult) {
  22723. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22724. if (this.onPointerDown) {
  22725. this.onPointerDown(evt, pickResult, type);
  22726. }
  22727. if (this.onPointerObservable.hasObservers()) {
  22728. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22729. this.onPointerObservable.notifyObservers(pi, type);
  22730. }
  22731. }
  22732. return this;
  22733. };
  22734. /**
  22735. * Use this method to simulate a pointer up on a mesh
  22736. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22737. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22738. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22739. */
  22740. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  22741. var evt = new PointerEvent("pointerup", pointerEventInit);
  22742. var clickInfo = new ClickInfo();
  22743. clickInfo.singleClick = true;
  22744. clickInfo.ignore = true;
  22745. return this._processPointerUp(pickResult, evt, clickInfo);
  22746. };
  22747. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  22748. if (pickResult && pickResult && pickResult.pickedMesh) {
  22749. this._pickedUpMesh = pickResult.pickedMesh;
  22750. if (this._pickedDownMesh === this._pickedUpMesh) {
  22751. if (this.onPointerPick) {
  22752. this.onPointerPick(evt, pickResult);
  22753. }
  22754. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  22755. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  22756. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  22757. this.onPointerObservable.notifyObservers(pi, type_1);
  22758. }
  22759. }
  22760. if (pickResult.pickedMesh.actionManager) {
  22761. if (clickInfo.ignore) {
  22762. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22763. }
  22764. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22765. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22766. }
  22767. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22768. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22769. }
  22770. }
  22771. }
  22772. if (this._pickedDownMesh &&
  22773. this._pickedDownMesh.actionManager &&
  22774. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22775. this._pickedDownMesh !== this._pickedUpMesh) {
  22776. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22777. }
  22778. var type = BABYLON.PointerEventTypes.POINTERUP;
  22779. if (this.onPointerObservable.hasObservers()) {
  22780. if (!clickInfo.ignore) {
  22781. if (!clickInfo.hasSwiped) {
  22782. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22783. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  22784. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  22785. this.onPointerObservable.notifyObservers(pi, type_2);
  22786. }
  22787. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22788. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22789. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  22790. this.onPointerObservable.notifyObservers(pi, type_3);
  22791. }
  22792. }
  22793. }
  22794. else {
  22795. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22796. this.onPointerObservable.notifyObservers(pi, type);
  22797. }
  22798. }
  22799. if (this.onPointerUp) {
  22800. this.onPointerUp(evt, pickResult, type);
  22801. }
  22802. return this;
  22803. };
  22804. /**
  22805. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22806. * @param attachUp defines if you want to attach events to pointerup
  22807. * @param attachDown defines if you want to attach events to pointerdown
  22808. * @param attachMove defines if you want to attach events to pointermove
  22809. */
  22810. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22811. var _this = this;
  22812. if (attachUp === void 0) { attachUp = true; }
  22813. if (attachDown === void 0) { attachDown = true; }
  22814. if (attachMove === void 0) { attachMove = true; }
  22815. this._initActionManager = function (act, clickInfo) {
  22816. if (!_this._meshPickProceed) {
  22817. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22818. _this._currentPickResult = pickResult;
  22819. if (pickResult) {
  22820. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22821. }
  22822. _this._meshPickProceed = true;
  22823. }
  22824. return act;
  22825. };
  22826. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22827. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22828. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22829. btn !== _this._previousButtonPressed) {
  22830. _this._doubleClickOccured = false;
  22831. clickInfo.singleClick = true;
  22832. clickInfo.ignore = false;
  22833. cb(clickInfo, _this._currentPickResult);
  22834. }
  22835. };
  22836. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22837. var clickInfo = new ClickInfo();
  22838. _this._currentPickResult = null;
  22839. var act = null;
  22840. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22841. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22842. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22843. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22844. act = _this._initActionManager(act, clickInfo);
  22845. if (act)
  22846. checkPicking = act.hasPickTriggers;
  22847. }
  22848. if (checkPicking) {
  22849. var btn = evt.button;
  22850. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22851. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22852. if (!clickInfo.hasSwiped) {
  22853. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22854. if (!checkSingleClickImmediately) {
  22855. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22856. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22857. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22858. act = _this._initActionManager(act, clickInfo);
  22859. if (act)
  22860. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22861. }
  22862. }
  22863. if (checkSingleClickImmediately) {
  22864. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22865. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22866. btn !== _this._previousButtonPressed) {
  22867. clickInfo.singleClick = true;
  22868. cb(clickInfo, _this._currentPickResult);
  22869. }
  22870. }
  22871. else {
  22872. // wait that no double click has been raised during the double click delay
  22873. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22874. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22875. }
  22876. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22877. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22878. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22879. act = _this._initActionManager(act, clickInfo);
  22880. if (act)
  22881. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22882. }
  22883. if (checkDoubleClick) {
  22884. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22885. if (btn === _this._previousButtonPressed &&
  22886. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22887. !_this._doubleClickOccured) {
  22888. // pointer has not moved for 2 clicks, it's a double click
  22889. if (!clickInfo.hasSwiped &&
  22890. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22891. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22892. _this._previousStartingPointerTime = 0;
  22893. _this._doubleClickOccured = true;
  22894. clickInfo.doubleClick = true;
  22895. clickInfo.ignore = false;
  22896. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22897. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22898. }
  22899. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22900. cb(clickInfo, _this._currentPickResult);
  22901. }
  22902. else {
  22903. _this._doubleClickOccured = false;
  22904. _this._previousStartingPointerTime = _this._startingPointerTime;
  22905. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22906. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22907. _this._previousButtonPressed = btn;
  22908. if (Scene.ExclusiveDoubleClickMode) {
  22909. if (_this._previousDelayedSimpleClickTimeout) {
  22910. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22911. }
  22912. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22913. cb(clickInfo, _this._previousPickResult);
  22914. }
  22915. else {
  22916. cb(clickInfo, _this._currentPickResult);
  22917. }
  22918. }
  22919. }
  22920. else {
  22921. _this._doubleClickOccured = false;
  22922. _this._previousStartingPointerTime = _this._startingPointerTime;
  22923. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22924. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22925. _this._previousButtonPressed = btn;
  22926. }
  22927. }
  22928. }
  22929. }
  22930. clickInfo.ignore = true;
  22931. cb(clickInfo, _this._currentPickResult);
  22932. };
  22933. this._spritePredicate = function (sprite) {
  22934. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22935. };
  22936. this._onPointerMove = function (evt) {
  22937. _this._updatePointerPosition(evt);
  22938. // PreObservable support
  22939. if (_this.onPrePointerObservable.hasObservers()) {
  22940. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22941. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22942. _this.onPrePointerObservable.notifyObservers(pi, type);
  22943. if (pi.skipOnPointerObservable) {
  22944. return;
  22945. }
  22946. }
  22947. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22948. return;
  22949. }
  22950. if (!_this.pointerMovePredicate) {
  22951. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22952. }
  22953. // Meshes
  22954. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22955. _this._processPointerMove(pickResult, evt);
  22956. };
  22957. this._onPointerDown = function (evt) {
  22958. _this._totalPointersPressed++;
  22959. _this._pickedDownMesh = null;
  22960. _this._meshPickProceed = false;
  22961. _this._updatePointerPosition(evt);
  22962. if (_this.preventDefaultOnPointerDown && canvas) {
  22963. evt.preventDefault();
  22964. canvas.focus();
  22965. }
  22966. // PreObservable support
  22967. if (_this.onPrePointerObservable.hasObservers()) {
  22968. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22969. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22970. _this.onPrePointerObservable.notifyObservers(pi, type);
  22971. if (pi.skipOnPointerObservable) {
  22972. return;
  22973. }
  22974. }
  22975. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22976. return;
  22977. }
  22978. _this._startingPointerPosition.x = _this._pointerX;
  22979. _this._startingPointerPosition.y = _this._pointerY;
  22980. _this._startingPointerTime = new Date().getTime();
  22981. if (!_this.pointerDownPredicate) {
  22982. _this.pointerDownPredicate = function (mesh) {
  22983. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22984. };
  22985. }
  22986. // Meshes
  22987. _this._pickedDownMesh = null;
  22988. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22989. _this._processPointerDown(pickResult, evt);
  22990. // Sprites
  22991. _this._pickedDownSprite = null;
  22992. if (_this.spriteManagers.length > 0) {
  22993. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22994. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22995. if (pickResult.pickedSprite.actionManager) {
  22996. _this._pickedDownSprite = pickResult.pickedSprite;
  22997. switch (evt.button) {
  22998. case 0:
  22999. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  23000. break;
  23001. case 1:
  23002. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  23003. break;
  23004. case 2:
  23005. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  23006. break;
  23007. }
  23008. if (pickResult.pickedSprite.actionManager) {
  23009. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  23010. }
  23011. }
  23012. }
  23013. }
  23014. };
  23015. this._onPointerUp = function (evt) {
  23016. if (_this._totalPointersPressed === 0) {
  23017. return; // So we need to test it the pointer down was pressed before.
  23018. }
  23019. _this._totalPointersPressed--;
  23020. _this._pickedUpMesh = null;
  23021. _this._meshPickProceed = false;
  23022. _this._updatePointerPosition(evt);
  23023. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  23024. // PreObservable support
  23025. if (_this.onPrePointerObservable.hasObservers()) {
  23026. if (!clickInfo.ignore) {
  23027. if (!clickInfo.hasSwiped) {
  23028. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  23029. var type = BABYLON.PointerEventTypes.POINTERTAP;
  23030. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  23031. _this.onPrePointerObservable.notifyObservers(pi, type);
  23032. if (pi.skipOnPointerObservable) {
  23033. return;
  23034. }
  23035. }
  23036. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  23037. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  23038. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  23039. _this.onPrePointerObservable.notifyObservers(pi, type);
  23040. if (pi.skipOnPointerObservable) {
  23041. return;
  23042. }
  23043. }
  23044. }
  23045. }
  23046. else {
  23047. var type = BABYLON.PointerEventTypes.POINTERUP;
  23048. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  23049. _this.onPrePointerObservable.notifyObservers(pi, type);
  23050. if (pi.skipOnPointerObservable) {
  23051. return;
  23052. }
  23053. }
  23054. }
  23055. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  23056. return;
  23057. }
  23058. if (!_this.pointerUpPredicate) {
  23059. _this.pointerUpPredicate = function (mesh) {
  23060. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  23061. };
  23062. }
  23063. // Meshes
  23064. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  23065. _this._initActionManager(null, clickInfo);
  23066. }
  23067. if (!pickResult) {
  23068. pickResult = _this._currentPickResult;
  23069. }
  23070. _this._processPointerUp(pickResult, evt, clickInfo);
  23071. // Sprites
  23072. if (_this.spriteManagers.length > 0) {
  23073. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  23074. if (spritePickResult) {
  23075. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  23076. if (spritePickResult.pickedSprite.actionManager) {
  23077. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  23078. if (spritePickResult.pickedSprite.actionManager) {
  23079. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  23080. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  23081. }
  23082. }
  23083. }
  23084. }
  23085. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  23086. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  23087. }
  23088. }
  23089. }
  23090. _this._previousPickResult = _this._currentPickResult;
  23091. });
  23092. };
  23093. this._onKeyDown = function (evt) {
  23094. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  23095. if (_this.onPreKeyboardObservable.hasObservers()) {
  23096. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  23097. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  23098. if (pi.skipOnPointerObservable) {
  23099. return;
  23100. }
  23101. }
  23102. if (_this.onKeyboardObservable.hasObservers()) {
  23103. var pi = new BABYLON.KeyboardInfo(type, evt);
  23104. _this.onKeyboardObservable.notifyObservers(pi, type);
  23105. }
  23106. if (_this.actionManager) {
  23107. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  23108. }
  23109. };
  23110. this._onKeyUp = function (evt) {
  23111. var type = BABYLON.KeyboardEventTypes.KEYUP;
  23112. if (_this.onPreKeyboardObservable.hasObservers()) {
  23113. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  23114. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  23115. if (pi.skipOnPointerObservable) {
  23116. return;
  23117. }
  23118. }
  23119. if (_this.onKeyboardObservable.hasObservers()) {
  23120. var pi = new BABYLON.KeyboardInfo(type, evt);
  23121. _this.onKeyboardObservable.notifyObservers(pi, type);
  23122. }
  23123. if (_this.actionManager) {
  23124. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  23125. }
  23126. };
  23127. var engine = this.getEngine();
  23128. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  23129. if (!canvas) {
  23130. return;
  23131. }
  23132. canvas.addEventListener("keydown", _this._onKeyDown, false);
  23133. canvas.addEventListener("keyup", _this._onKeyUp, false);
  23134. });
  23135. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  23136. if (!canvas) {
  23137. return;
  23138. }
  23139. canvas.removeEventListener("keydown", _this._onKeyDown);
  23140. canvas.removeEventListener("keyup", _this._onKeyUp);
  23141. });
  23142. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  23143. var canvas = this._engine.getRenderingCanvas();
  23144. if (!canvas) {
  23145. return;
  23146. }
  23147. if (attachMove) {
  23148. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  23149. // Wheel
  23150. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  23151. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  23152. }
  23153. if (attachDown) {
  23154. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  23155. }
  23156. if (attachUp) {
  23157. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  23158. }
  23159. canvas.tabIndex = 1;
  23160. };
  23161. Scene.prototype.detachControl = function () {
  23162. var engine = this.getEngine();
  23163. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  23164. var canvas = engine.getRenderingCanvas();
  23165. if (!canvas) {
  23166. return;
  23167. }
  23168. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  23169. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  23170. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  23171. if (this._onCanvasBlurObserver) {
  23172. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  23173. }
  23174. if (this._onCanvasFocusObserver) {
  23175. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  23176. }
  23177. // Wheel
  23178. canvas.removeEventListener('mousewheel', this._onPointerMove);
  23179. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  23180. // Keyboard
  23181. canvas.removeEventListener("keydown", this._onKeyDown);
  23182. canvas.removeEventListener("keyup", this._onKeyUp);
  23183. // Observables
  23184. this.onKeyboardObservable.clear();
  23185. this.onPreKeyboardObservable.clear();
  23186. this.onPointerObservable.clear();
  23187. this.onPrePointerObservable.clear();
  23188. };
  23189. /**
  23190. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  23191. * Delay loaded resources are not taking in account
  23192. * @return true if all required resources are ready
  23193. */
  23194. Scene.prototype.isReady = function () {
  23195. if (this._isDisposed) {
  23196. return false;
  23197. }
  23198. if (this._pendingData.length > 0) {
  23199. return false;
  23200. }
  23201. var index;
  23202. var engine = this.getEngine();
  23203. // Geometries
  23204. for (index = 0; index < this._geometries.length; index++) {
  23205. var geometry = this._geometries[index];
  23206. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23207. return false;
  23208. }
  23209. }
  23210. // Meshes
  23211. for (index = 0; index < this.meshes.length; index++) {
  23212. var mesh = this.meshes[index];
  23213. if (!mesh.isEnabled()) {
  23214. continue;
  23215. }
  23216. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  23217. continue;
  23218. }
  23219. if (!mesh.isReady(true)) {
  23220. return false;
  23221. }
  23222. // Effect layers
  23223. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  23224. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  23225. var layer = _a[_i];
  23226. if (!layer.hasMesh(mesh)) {
  23227. continue;
  23228. }
  23229. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  23230. var subMesh = _c[_b];
  23231. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  23232. return false;
  23233. }
  23234. }
  23235. }
  23236. }
  23237. // Post-processes
  23238. if (this.activeCameras && this.activeCameras.length > 0) {
  23239. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  23240. var camera = _e[_d];
  23241. if (!camera.isReady(true)) {
  23242. return false;
  23243. }
  23244. }
  23245. }
  23246. else if (this.activeCamera) {
  23247. if (!this.activeCamera.isReady(true)) {
  23248. return false;
  23249. }
  23250. }
  23251. // Particles
  23252. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  23253. var particleSystem = _g[_f];
  23254. if (!particleSystem.isReady()) {
  23255. return false;
  23256. }
  23257. }
  23258. return true;
  23259. };
  23260. Scene.prototype.resetCachedMaterial = function () {
  23261. this._cachedMaterial = null;
  23262. this._cachedEffect = null;
  23263. this._cachedVisibility = null;
  23264. };
  23265. Scene.prototype.registerBeforeRender = function (func) {
  23266. this.onBeforeRenderObservable.add(func);
  23267. };
  23268. Scene.prototype.unregisterBeforeRender = function (func) {
  23269. this.onBeforeRenderObservable.removeCallback(func);
  23270. };
  23271. Scene.prototype.registerAfterRender = function (func) {
  23272. this.onAfterRenderObservable.add(func);
  23273. };
  23274. Scene.prototype.unregisterAfterRender = function (func) {
  23275. this.onAfterRenderObservable.removeCallback(func);
  23276. };
  23277. Scene.prototype._executeOnceBeforeRender = function (func) {
  23278. var _this = this;
  23279. var execFunc = function () {
  23280. func();
  23281. setTimeout(function () {
  23282. _this.unregisterBeforeRender(execFunc);
  23283. });
  23284. };
  23285. this.registerBeforeRender(execFunc);
  23286. };
  23287. /**
  23288. * The provided function will run before render once and will be disposed afterwards.
  23289. * A timeout delay can be provided so that the function will be executed in N ms.
  23290. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  23291. * @param func The function to be executed.
  23292. * @param timeout optional delay in ms
  23293. */
  23294. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  23295. var _this = this;
  23296. if (timeout !== undefined) {
  23297. setTimeout(function () {
  23298. _this._executeOnceBeforeRender(func);
  23299. }, timeout);
  23300. }
  23301. else {
  23302. this._executeOnceBeforeRender(func);
  23303. }
  23304. };
  23305. Scene.prototype._addPendingData = function (data) {
  23306. this._pendingData.push(data);
  23307. };
  23308. Scene.prototype._removePendingData = function (data) {
  23309. var wasLoading = this.isLoading;
  23310. var index = this._pendingData.indexOf(data);
  23311. if (index !== -1) {
  23312. this._pendingData.splice(index, 1);
  23313. }
  23314. if (wasLoading && !this.isLoading) {
  23315. this.onDataLoadedObservable.notifyObservers(this);
  23316. }
  23317. };
  23318. Scene.prototype.getWaitingItemsCount = function () {
  23319. return this._pendingData.length;
  23320. };
  23321. Object.defineProperty(Scene.prototype, "isLoading", {
  23322. get: function () {
  23323. return this._pendingData.length > 0;
  23324. },
  23325. enumerable: true,
  23326. configurable: true
  23327. });
  23328. /**
  23329. * Registers a function to be executed when the scene is ready.
  23330. * @param {Function} func - the function to be executed.
  23331. */
  23332. Scene.prototype.executeWhenReady = function (func) {
  23333. var _this = this;
  23334. this.onReadyObservable.add(func);
  23335. if (this._executeWhenReadyTimeoutId !== -1) {
  23336. return;
  23337. }
  23338. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23339. _this._checkIsReady();
  23340. }, 150);
  23341. };
  23342. /**
  23343. * Returns a promise that resolves when the scene is ready.
  23344. * @returns A promise that resolves when the scene is ready.
  23345. */
  23346. Scene.prototype.whenReadyAsync = function () {
  23347. var _this = this;
  23348. return new Promise(function (resolve) {
  23349. _this.executeWhenReady(function () {
  23350. resolve();
  23351. });
  23352. });
  23353. };
  23354. Scene.prototype._checkIsReady = function () {
  23355. var _this = this;
  23356. if (this.isReady()) {
  23357. this.onReadyObservable.notifyObservers(this);
  23358. this.onReadyObservable.clear();
  23359. this._executeWhenReadyTimeoutId = -1;
  23360. return;
  23361. }
  23362. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23363. _this._checkIsReady();
  23364. }, 150);
  23365. };
  23366. // Animations
  23367. /**
  23368. * Will start the animation sequence of a given target
  23369. * @param target defines the target
  23370. * @param from defines from which frame should animation start
  23371. * @param to defines until which frame should animation run.
  23372. * @param weight defines the weight to apply to the animation (1.0 by default)
  23373. * @param loop defines if the animation loops
  23374. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  23375. * @param onAnimationEnd defines the function to be executed when the animation ends
  23376. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  23377. * @returns the animatable object created for this animation
  23378. */
  23379. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  23380. if (weight === void 0) { weight = 1.0; }
  23381. if (speedRatio === void 0) { speedRatio = 1.0; }
  23382. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  23383. returnedAnimatable.weight = weight;
  23384. return returnedAnimatable;
  23385. };
  23386. /**
  23387. * Will start the animation sequence of a given target
  23388. * @param target defines the target
  23389. * @param from defines from which frame should animation start
  23390. * @param to defines until which frame should animation run.
  23391. * @param loop defines if the animation loops
  23392. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  23393. * @param onAnimationEnd defines the function to be executed when the animation ends
  23394. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  23395. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  23396. * @returns the animatable object created for this animation
  23397. */
  23398. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  23399. if (speedRatio === void 0) { speedRatio = 1.0; }
  23400. if (stopCurrent === void 0) { stopCurrent = true; }
  23401. if (from > to && speedRatio > 0) {
  23402. speedRatio *= -1;
  23403. }
  23404. if (stopCurrent) {
  23405. this.stopAnimation(target);
  23406. }
  23407. if (!animatable) {
  23408. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  23409. }
  23410. // Local animations
  23411. if (target.animations) {
  23412. animatable.appendAnimations(target, target.animations);
  23413. }
  23414. // Children animations
  23415. if (target.getAnimatables) {
  23416. var animatables = target.getAnimatables();
  23417. for (var index = 0; index < animatables.length; index++) {
  23418. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  23419. }
  23420. }
  23421. animatable.reset();
  23422. return animatable;
  23423. };
  23424. /**
  23425. * Begin a new animation on a given node
  23426. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23427. * @param {BABYLON.Animation[]} defines the list of animations to start
  23428. * @param {number} from defines the initial value
  23429. * @param {number} to defines the final value
  23430. * @param {boolean} loop defines if you want animation to loop (off by default)
  23431. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23432. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23433. * @returns the list of created animatables
  23434. */
  23435. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23436. if (speedRatio === undefined) {
  23437. speedRatio = 1.0;
  23438. }
  23439. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  23440. return animatable;
  23441. };
  23442. /**
  23443. * Begin a new animation on a given node and its hierarchy
  23444. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23445. * @param {boolean} 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.
  23446. * @param {BABYLON.Animation[]} defines the list of animations to start
  23447. * @param {number} from defines the initial value
  23448. * @param {number} to defines the final value
  23449. * @param {boolean} loop defines if you want animation to loop (off by default)
  23450. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23451. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23452. * @returns the list of animatables created for all nodes
  23453. */
  23454. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23455. var children = target.getDescendants(directDescendantsOnly);
  23456. var result = [];
  23457. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  23458. var child = children_1[_i];
  23459. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  23460. }
  23461. return result;
  23462. };
  23463. Scene.prototype.getAnimatableByTarget = function (target) {
  23464. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23465. if (this._activeAnimatables[index].target === target) {
  23466. return this._activeAnimatables[index];
  23467. }
  23468. }
  23469. return null;
  23470. };
  23471. /**
  23472. * Gets all animatables associated with a given target
  23473. * @param target defines the target to look animatables for
  23474. * @returns an array of Animatables
  23475. */
  23476. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  23477. var result = [];
  23478. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23479. if (this._activeAnimatables[index].target === target) {
  23480. result.push(this._activeAnimatables[index]);
  23481. }
  23482. }
  23483. return result;
  23484. };
  23485. Object.defineProperty(Scene.prototype, "animatables", {
  23486. get: function () {
  23487. return this._activeAnimatables;
  23488. },
  23489. enumerable: true,
  23490. configurable: true
  23491. });
  23492. /**
  23493. * Will stop the animation of the given target
  23494. * @param target - the target
  23495. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  23496. */
  23497. Scene.prototype.stopAnimation = function (target, animationName) {
  23498. var animatables = this.getAllAnimatablesByTarget(target);
  23499. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  23500. var animatable = animatables_1[_i];
  23501. animatable.stop(animationName);
  23502. }
  23503. };
  23504. /**
  23505. * Stops and removes all animations that have been applied to the scene
  23506. */
  23507. Scene.prototype.stopAllAnimations = function () {
  23508. if (this._activeAnimatables) {
  23509. for (var i = 0; i < this._activeAnimatables.length; i++) {
  23510. this._activeAnimatables[i].stop();
  23511. }
  23512. this._activeAnimatables = [];
  23513. }
  23514. };
  23515. Scene.prototype._animate = function () {
  23516. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  23517. return;
  23518. }
  23519. // Getting time
  23520. var now = BABYLON.Tools.Now;
  23521. if (!this._animationTimeLast) {
  23522. if (this._pendingData.length > 0) {
  23523. return;
  23524. }
  23525. this._animationTimeLast = now;
  23526. }
  23527. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  23528. this._animationTime += deltaTime;
  23529. this._animationTimeLast = now;
  23530. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23531. this._activeAnimatables[index]._animate(this._animationTime);
  23532. }
  23533. // Late animation bindings
  23534. this._processLateAnimationBindings();
  23535. };
  23536. /** @ignore */
  23537. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation) {
  23538. var target = runtimeAnimation.target;
  23539. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  23540. if (!target._lateAnimationHolders) {
  23541. target._lateAnimationHolders = {};
  23542. }
  23543. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  23544. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  23545. totalWeight: 0,
  23546. animations: []
  23547. };
  23548. }
  23549. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  23550. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  23551. };
  23552. Scene.prototype._processLateAnimationBindings = function () {
  23553. if (!this._registeredForLateAnimationBindings.length) {
  23554. return;
  23555. }
  23556. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  23557. var target = this._registeredForLateAnimationBindings.data[index];
  23558. for (var path in target._lateAnimationHolders) {
  23559. var holder = target._lateAnimationHolders[path];
  23560. // Sanity check
  23561. if (!holder.animations[0].originalValue.scaleAndAddToRef) {
  23562. continue;
  23563. }
  23564. var normalizer = 1.0;
  23565. var finalValue = void 0;
  23566. if (holder.totalWeight < 1.0) {
  23567. // We need to mix the original value in
  23568. var originalValue = holder.animations[0].originalValue;
  23569. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  23570. }
  23571. else {
  23572. // We need to normalize the weights
  23573. normalizer = holder.totalWeight;
  23574. }
  23575. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  23576. var runtimeAnimation = holder.animations[animIndex];
  23577. if (finalValue) {
  23578. runtimeAnimation.currentValue.scaleAndAddToRef(runtimeAnimation.weight / normalizer, finalValue);
  23579. }
  23580. else {
  23581. finalValue = runtimeAnimation.currentValue.scale(runtimeAnimation.weight / normalizer);
  23582. }
  23583. }
  23584. runtimeAnimation.target[path] = finalValue;
  23585. }
  23586. target._lateAnimationHolders = {};
  23587. }
  23588. this._registeredForLateAnimationBindings.reset();
  23589. };
  23590. // Matrix
  23591. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  23592. this._useAlternateCameraConfiguration = active;
  23593. };
  23594. Scene.prototype.getViewMatrix = function () {
  23595. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  23596. };
  23597. Scene.prototype.getProjectionMatrix = function () {
  23598. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  23599. };
  23600. Scene.prototype.getTransformMatrix = function () {
  23601. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  23602. };
  23603. Scene.prototype.setTransformMatrix = function (view, projection) {
  23604. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  23605. return;
  23606. }
  23607. this._viewUpdateFlag = view.updateFlag;
  23608. this._projectionUpdateFlag = projection.updateFlag;
  23609. this._viewMatrix = view;
  23610. this._projectionMatrix = projection;
  23611. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23612. // Update frustum
  23613. if (!this._frustumPlanes) {
  23614. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23615. }
  23616. else {
  23617. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23618. }
  23619. if (this.activeCamera && this.activeCamera._alternateCamera) {
  23620. var otherCamera = this.activeCamera._alternateCamera;
  23621. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  23622. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  23623. }
  23624. if (this._sceneUbo.useUbo) {
  23625. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  23626. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  23627. this._sceneUbo.update();
  23628. }
  23629. };
  23630. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  23631. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  23632. return;
  23633. }
  23634. this._alternateViewUpdateFlag = view.updateFlag;
  23635. this._alternateProjectionUpdateFlag = projection.updateFlag;
  23636. this._alternateViewMatrix = view;
  23637. this._alternateProjectionMatrix = projection;
  23638. if (!this._alternateTransformMatrix) {
  23639. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  23640. }
  23641. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  23642. if (!this._alternateSceneUbo) {
  23643. this._createAlternateUbo();
  23644. }
  23645. if (this._alternateSceneUbo.useUbo) {
  23646. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  23647. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  23648. this._alternateSceneUbo.update();
  23649. }
  23650. };
  23651. Scene.prototype.getSceneUniformBuffer = function () {
  23652. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  23653. };
  23654. // Methods
  23655. Scene.prototype.getUniqueId = function () {
  23656. var result = Scene._uniqueIdCounter;
  23657. Scene._uniqueIdCounter++;
  23658. return result;
  23659. };
  23660. Scene.prototype.addMesh = function (newMesh) {
  23661. this.meshes.push(newMesh);
  23662. //notify the collision coordinator
  23663. if (this.collisionCoordinator) {
  23664. this.collisionCoordinator.onMeshAdded(newMesh);
  23665. }
  23666. newMesh._resyncLightSources();
  23667. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  23668. };
  23669. Scene.prototype.removeMesh = function (toRemove) {
  23670. var index = this.meshes.indexOf(toRemove);
  23671. if (index !== -1) {
  23672. // Remove from the scene if mesh found
  23673. this.meshes.splice(index, 1);
  23674. }
  23675. this.onMeshRemovedObservable.notifyObservers(toRemove);
  23676. return index;
  23677. };
  23678. Scene.prototype.addTransformNode = function (newTransformNode) {
  23679. this.transformNodes.push(newTransformNode);
  23680. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  23681. };
  23682. Scene.prototype.removeTransformNode = function (toRemove) {
  23683. var index = this.transformNodes.indexOf(toRemove);
  23684. if (index !== -1) {
  23685. // Remove from the scene if found
  23686. this.transformNodes.splice(index, 1);
  23687. }
  23688. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  23689. return index;
  23690. };
  23691. Scene.prototype.removeSkeleton = function (toRemove) {
  23692. var index = this.skeletons.indexOf(toRemove);
  23693. if (index !== -1) {
  23694. // Remove from the scene if found
  23695. this.skeletons.splice(index, 1);
  23696. }
  23697. return index;
  23698. };
  23699. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  23700. var index = this.morphTargetManagers.indexOf(toRemove);
  23701. if (index !== -1) {
  23702. // Remove from the scene if found
  23703. this.morphTargetManagers.splice(index, 1);
  23704. }
  23705. return index;
  23706. };
  23707. Scene.prototype.removeLight = function (toRemove) {
  23708. var index = this.lights.indexOf(toRemove);
  23709. if (index !== -1) {
  23710. // Remove from meshes
  23711. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23712. var mesh = _a[_i];
  23713. mesh._removeLightSource(toRemove);
  23714. }
  23715. // Remove from the scene if mesh found
  23716. this.lights.splice(index, 1);
  23717. this.sortLightsByPriority();
  23718. }
  23719. this.onLightRemovedObservable.notifyObservers(toRemove);
  23720. return index;
  23721. };
  23722. Scene.prototype.removeCamera = function (toRemove) {
  23723. var index = this.cameras.indexOf(toRemove);
  23724. if (index !== -1) {
  23725. // Remove from the scene if mesh found
  23726. this.cameras.splice(index, 1);
  23727. }
  23728. // Remove from activeCameras
  23729. var index2 = this.activeCameras.indexOf(toRemove);
  23730. if (index2 !== -1) {
  23731. // Remove from the scene if mesh found
  23732. this.activeCameras.splice(index2, 1);
  23733. }
  23734. // Reset the activeCamera
  23735. if (this.activeCamera === toRemove) {
  23736. if (this.cameras.length > 0) {
  23737. this.activeCamera = this.cameras[0];
  23738. }
  23739. else {
  23740. this.activeCamera = null;
  23741. }
  23742. }
  23743. this.onCameraRemovedObservable.notifyObservers(toRemove);
  23744. return index;
  23745. };
  23746. Scene.prototype.removeParticleSystem = function (toRemove) {
  23747. var index = this.particleSystems.indexOf(toRemove);
  23748. if (index !== -1) {
  23749. this.particleSystems.splice(index, 1);
  23750. }
  23751. return index;
  23752. };
  23753. Scene.prototype.removeAnimation = function (toRemove) {
  23754. var index = this.animations.indexOf(toRemove);
  23755. if (index !== -1) {
  23756. this.animations.splice(index, 1);
  23757. }
  23758. return index;
  23759. };
  23760. /**
  23761. * Removes the given animation group from this scene.
  23762. * @param toRemove The animation group to remove
  23763. * @returns The index of the removed animation group
  23764. */
  23765. Scene.prototype.removeAnimationGroup = function (toRemove) {
  23766. var index = this.animationGroups.indexOf(toRemove);
  23767. if (index !== -1) {
  23768. this.animationGroups.splice(index, 1);
  23769. }
  23770. return index;
  23771. };
  23772. Scene.prototype.removeMultiMaterial = function (toRemove) {
  23773. var index = this.multiMaterials.indexOf(toRemove);
  23774. if (index !== -1) {
  23775. this.multiMaterials.splice(index, 1);
  23776. }
  23777. return index;
  23778. };
  23779. Scene.prototype.removeMaterial = function (toRemove) {
  23780. var index = this.materials.indexOf(toRemove);
  23781. if (index !== -1) {
  23782. this.materials.splice(index, 1);
  23783. }
  23784. return index;
  23785. };
  23786. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  23787. var index = this.lensFlareSystems.indexOf(toRemove);
  23788. if (index !== -1) {
  23789. this.lensFlareSystems.splice(index, 1);
  23790. }
  23791. return index;
  23792. };
  23793. Scene.prototype.removeActionManager = function (toRemove) {
  23794. var index = this._actionManagers.indexOf(toRemove);
  23795. if (index !== -1) {
  23796. this._actionManagers.splice(index, 1);
  23797. }
  23798. return index;
  23799. };
  23800. /**
  23801. * Removes the given texture from this scene.
  23802. * @param toRemove The texture to remove
  23803. * @returns The index of the removed texture
  23804. */
  23805. Scene.prototype.removeTexture = function (toRemove) {
  23806. var index = this.textures.indexOf(toRemove);
  23807. if (index !== -1) {
  23808. this.textures.splice(index, 1);
  23809. }
  23810. return index;
  23811. };
  23812. Scene.prototype.addLight = function (newLight) {
  23813. this.lights.push(newLight);
  23814. this.sortLightsByPriority();
  23815. // Add light to all meshes (To support if the light is removed and then readded)
  23816. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23817. var mesh = _a[_i];
  23818. if (mesh._lightSources.indexOf(newLight) === -1) {
  23819. mesh._lightSources.push(newLight);
  23820. mesh._resyncLightSources();
  23821. }
  23822. }
  23823. this.onNewLightAddedObservable.notifyObservers(newLight);
  23824. };
  23825. Scene.prototype.sortLightsByPriority = function () {
  23826. if (this.requireLightSorting) {
  23827. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  23828. }
  23829. };
  23830. Scene.prototype.addCamera = function (newCamera) {
  23831. this.cameras.push(newCamera);
  23832. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  23833. };
  23834. Scene.prototype.addSkeleton = function (newSkeleton) {
  23835. this.skeletons.push(newSkeleton);
  23836. };
  23837. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  23838. this.particleSystems.push(newParticleSystem);
  23839. };
  23840. Scene.prototype.addAnimation = function (newAnimation) {
  23841. this.animations.push(newAnimation);
  23842. };
  23843. /**
  23844. * Adds the given animation group to this scene.
  23845. * @param newAnimationGroup The animation group to add
  23846. */
  23847. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  23848. this.animationGroups.push(newAnimationGroup);
  23849. };
  23850. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  23851. this.multiMaterials.push(newMultiMaterial);
  23852. };
  23853. Scene.prototype.addMaterial = function (newMaterial) {
  23854. this.materials.push(newMaterial);
  23855. };
  23856. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  23857. this.morphTargetManagers.push(newMorphTargetManager);
  23858. };
  23859. Scene.prototype.addGeometry = function (newGeometrie) {
  23860. this._geometries.push(newGeometrie);
  23861. };
  23862. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  23863. this.lensFlareSystems.push(newLensFlareSystem);
  23864. };
  23865. Scene.prototype.addActionManager = function (newActionManager) {
  23866. this._actionManagers.push(newActionManager);
  23867. };
  23868. /**
  23869. * Adds the given texture to this scene.
  23870. * @param newTexture The texture to add
  23871. */
  23872. Scene.prototype.addTexture = function (newTexture) {
  23873. this.textures.push(newTexture);
  23874. };
  23875. /**
  23876. * Switch active camera
  23877. * @param {Camera} newCamera - new active camera
  23878. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  23879. */
  23880. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  23881. if (attachControl === void 0) { attachControl = true; }
  23882. var canvas = this._engine.getRenderingCanvas();
  23883. if (!canvas) {
  23884. return;
  23885. }
  23886. if (this.activeCamera) {
  23887. this.activeCamera.detachControl(canvas);
  23888. }
  23889. this.activeCamera = newCamera;
  23890. if (attachControl) {
  23891. newCamera.attachControl(canvas);
  23892. }
  23893. };
  23894. /**
  23895. * sets the active camera of the scene using its ID
  23896. * @param {string} id - the camera's ID
  23897. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23898. */
  23899. Scene.prototype.setActiveCameraByID = function (id) {
  23900. var camera = this.getCameraByID(id);
  23901. if (camera) {
  23902. this.activeCamera = camera;
  23903. return camera;
  23904. }
  23905. return null;
  23906. };
  23907. /**
  23908. * sets the active camera of the scene using its name
  23909. * @param {string} name - the camera's name
  23910. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23911. */
  23912. Scene.prototype.setActiveCameraByName = function (name) {
  23913. var camera = this.getCameraByName(name);
  23914. if (camera) {
  23915. this.activeCamera = camera;
  23916. return camera;
  23917. }
  23918. return null;
  23919. };
  23920. /**
  23921. * get an animation group using its name
  23922. * @param {string} the material's name
  23923. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23924. */
  23925. Scene.prototype.getAnimationGroupByName = function (name) {
  23926. for (var index = 0; index < this.animationGroups.length; index++) {
  23927. if (this.animationGroups[index].name === name) {
  23928. return this.animationGroups[index];
  23929. }
  23930. }
  23931. return null;
  23932. };
  23933. /**
  23934. * get a material using its id
  23935. * @param {string} the material's ID
  23936. * @return {BABYLON.Material|null} the material or null if none found.
  23937. */
  23938. Scene.prototype.getMaterialByID = function (id) {
  23939. for (var index = 0; index < this.materials.length; index++) {
  23940. if (this.materials[index].id === id) {
  23941. return this.materials[index];
  23942. }
  23943. }
  23944. return null;
  23945. };
  23946. /**
  23947. * get a material using its name
  23948. * @param {string} the material's name
  23949. * @return {BABYLON.Material|null} the material or null if none found.
  23950. */
  23951. Scene.prototype.getMaterialByName = function (name) {
  23952. for (var index = 0; index < this.materials.length; index++) {
  23953. if (this.materials[index].name === name) {
  23954. return this.materials[index];
  23955. }
  23956. }
  23957. return null;
  23958. };
  23959. Scene.prototype.getLensFlareSystemByName = function (name) {
  23960. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23961. if (this.lensFlareSystems[index].name === name) {
  23962. return this.lensFlareSystems[index];
  23963. }
  23964. }
  23965. return null;
  23966. };
  23967. Scene.prototype.getLensFlareSystemByID = function (id) {
  23968. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23969. if (this.lensFlareSystems[index].id === id) {
  23970. return this.lensFlareSystems[index];
  23971. }
  23972. }
  23973. return null;
  23974. };
  23975. Scene.prototype.getCameraByID = function (id) {
  23976. for (var index = 0; index < this.cameras.length; index++) {
  23977. if (this.cameras[index].id === id) {
  23978. return this.cameras[index];
  23979. }
  23980. }
  23981. return null;
  23982. };
  23983. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23984. for (var index = 0; index < this.cameras.length; index++) {
  23985. if (this.cameras[index].uniqueId === uniqueId) {
  23986. return this.cameras[index];
  23987. }
  23988. }
  23989. return null;
  23990. };
  23991. /**
  23992. * get a camera using its name
  23993. * @param {string} the camera's name
  23994. * @return {BABYLON.Camera|null} the camera or null if none found.
  23995. */
  23996. Scene.prototype.getCameraByName = function (name) {
  23997. for (var index = 0; index < this.cameras.length; index++) {
  23998. if (this.cameras[index].name === name) {
  23999. return this.cameras[index];
  24000. }
  24001. }
  24002. return null;
  24003. };
  24004. /**
  24005. * get a bone using its id
  24006. * @param {string} the bone's id
  24007. * @return {BABYLON.Bone|null} the bone or null if not found
  24008. */
  24009. Scene.prototype.getBoneByID = function (id) {
  24010. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  24011. var skeleton = this.skeletons[skeletonIndex];
  24012. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  24013. if (skeleton.bones[boneIndex].id === id) {
  24014. return skeleton.bones[boneIndex];
  24015. }
  24016. }
  24017. }
  24018. return null;
  24019. };
  24020. /**
  24021. * get a bone using its id
  24022. * @param {string} the bone's name
  24023. * @return {BABYLON.Bone|null} the bone or null if not found
  24024. */
  24025. Scene.prototype.getBoneByName = function (name) {
  24026. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  24027. var skeleton = this.skeletons[skeletonIndex];
  24028. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  24029. if (skeleton.bones[boneIndex].name === name) {
  24030. return skeleton.bones[boneIndex];
  24031. }
  24032. }
  24033. }
  24034. return null;
  24035. };
  24036. /**
  24037. * get a light node using its name
  24038. * @param {string} the light's name
  24039. * @return {BABYLON.Light|null} the light or null if none found.
  24040. */
  24041. Scene.prototype.getLightByName = function (name) {
  24042. for (var index = 0; index < this.lights.length; index++) {
  24043. if (this.lights[index].name === name) {
  24044. return this.lights[index];
  24045. }
  24046. }
  24047. return null;
  24048. };
  24049. /**
  24050. * get a light node using its ID
  24051. * @param {string} the light's id
  24052. * @return {BABYLON.Light|null} the light or null if none found.
  24053. */
  24054. Scene.prototype.getLightByID = function (id) {
  24055. for (var index = 0; index < this.lights.length; index++) {
  24056. if (this.lights[index].id === id) {
  24057. return this.lights[index];
  24058. }
  24059. }
  24060. return null;
  24061. };
  24062. /**
  24063. * get a light node using its scene-generated unique ID
  24064. * @param {number} the light's unique id
  24065. * @return {BABYLON.Light|null} the light or null if none found.
  24066. */
  24067. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  24068. for (var index = 0; index < this.lights.length; index++) {
  24069. if (this.lights[index].uniqueId === uniqueId) {
  24070. return this.lights[index];
  24071. }
  24072. }
  24073. return null;
  24074. };
  24075. /**
  24076. * get a particle system by id
  24077. * @param id {number} the particle system id
  24078. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  24079. */
  24080. Scene.prototype.getParticleSystemByID = function (id) {
  24081. for (var index = 0; index < this.particleSystems.length; index++) {
  24082. if (this.particleSystems[index].id === id) {
  24083. return this.particleSystems[index];
  24084. }
  24085. }
  24086. return null;
  24087. };
  24088. /**
  24089. * get a geometry using its ID
  24090. * @param {string} the geometry's id
  24091. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  24092. */
  24093. Scene.prototype.getGeometryByID = function (id) {
  24094. for (var index = 0; index < this._geometries.length; index++) {
  24095. if (this._geometries[index].id === id) {
  24096. return this._geometries[index];
  24097. }
  24098. }
  24099. return null;
  24100. };
  24101. /**
  24102. * add a new geometry to this scene.
  24103. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  24104. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  24105. * @return {boolean} was the geometry added or not
  24106. */
  24107. Scene.prototype.pushGeometry = function (geometry, force) {
  24108. if (!force && this.getGeometryByID(geometry.id)) {
  24109. return false;
  24110. }
  24111. this._geometries.push(geometry);
  24112. //notify the collision coordinator
  24113. if (this.collisionCoordinator) {
  24114. this.collisionCoordinator.onGeometryAdded(geometry);
  24115. }
  24116. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  24117. return true;
  24118. };
  24119. /**
  24120. * Removes an existing geometry
  24121. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  24122. * @return {boolean} was the geometry removed or not
  24123. */
  24124. Scene.prototype.removeGeometry = function (geometry) {
  24125. var index = this._geometries.indexOf(geometry);
  24126. if (index > -1) {
  24127. this._geometries.splice(index, 1);
  24128. //notify the collision coordinator
  24129. if (this.collisionCoordinator) {
  24130. this.collisionCoordinator.onGeometryDeleted(geometry);
  24131. }
  24132. this.onGeometryRemovedObservable.notifyObservers(geometry);
  24133. return true;
  24134. }
  24135. return false;
  24136. };
  24137. Scene.prototype.getGeometries = function () {
  24138. return this._geometries;
  24139. };
  24140. /**
  24141. * Get the first added mesh found of a given ID
  24142. * @param {string} id - the id to search for
  24143. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24144. */
  24145. Scene.prototype.getMeshByID = function (id) {
  24146. for (var index = 0; index < this.meshes.length; index++) {
  24147. if (this.meshes[index].id === id) {
  24148. return this.meshes[index];
  24149. }
  24150. }
  24151. return null;
  24152. };
  24153. Scene.prototype.getMeshesByID = function (id) {
  24154. return this.meshes.filter(function (m) {
  24155. return m.id === id;
  24156. });
  24157. };
  24158. /**
  24159. * Get the first added transform node found of a given ID
  24160. * @param {string} id - the id to search for
  24161. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  24162. */
  24163. Scene.prototype.getTransformNodeByID = function (id) {
  24164. for (var index = 0; index < this.transformNodes.length; index++) {
  24165. if (this.transformNodes[index].id === id) {
  24166. return this.transformNodes[index];
  24167. }
  24168. }
  24169. return null;
  24170. };
  24171. Scene.prototype.getTransformNodesByID = function (id) {
  24172. return this.transformNodes.filter(function (m) {
  24173. return m.id === id;
  24174. });
  24175. };
  24176. /**
  24177. * Get a mesh with its auto-generated unique id
  24178. * @param {number} uniqueId - the unique id to search for
  24179. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24180. */
  24181. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  24182. for (var index = 0; index < this.meshes.length; index++) {
  24183. if (this.meshes[index].uniqueId === uniqueId) {
  24184. return this.meshes[index];
  24185. }
  24186. }
  24187. return null;
  24188. };
  24189. /**
  24190. * Get a the last added mesh found of a given ID
  24191. * @param {string} id - the id to search for
  24192. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24193. */
  24194. Scene.prototype.getLastMeshByID = function (id) {
  24195. for (var index = this.meshes.length - 1; index >= 0; index--) {
  24196. if (this.meshes[index].id === id) {
  24197. return this.meshes[index];
  24198. }
  24199. }
  24200. return null;
  24201. };
  24202. /**
  24203. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  24204. * @param {string} id - the id to search for
  24205. * @return {BABYLON.Node|null} the node found or null if not found at all.
  24206. */
  24207. Scene.prototype.getLastEntryByID = function (id) {
  24208. var index;
  24209. for (index = this.meshes.length - 1; index >= 0; index--) {
  24210. if (this.meshes[index].id === id) {
  24211. return this.meshes[index];
  24212. }
  24213. }
  24214. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  24215. if (this.transformNodes[index].id === id) {
  24216. return this.transformNodes[index];
  24217. }
  24218. }
  24219. for (index = this.cameras.length - 1; index >= 0; index--) {
  24220. if (this.cameras[index].id === id) {
  24221. return this.cameras[index];
  24222. }
  24223. }
  24224. for (index = this.lights.length - 1; index >= 0; index--) {
  24225. if (this.lights[index].id === id) {
  24226. return this.lights[index];
  24227. }
  24228. }
  24229. return null;
  24230. };
  24231. Scene.prototype.getNodeByID = function (id) {
  24232. var mesh = this.getMeshByID(id);
  24233. if (mesh) {
  24234. return mesh;
  24235. }
  24236. var light = this.getLightByID(id);
  24237. if (light) {
  24238. return light;
  24239. }
  24240. var camera = this.getCameraByID(id);
  24241. if (camera) {
  24242. return camera;
  24243. }
  24244. var bone = this.getBoneByID(id);
  24245. return bone;
  24246. };
  24247. Scene.prototype.getNodeByName = function (name) {
  24248. var mesh = this.getMeshByName(name);
  24249. if (mesh) {
  24250. return mesh;
  24251. }
  24252. var light = this.getLightByName(name);
  24253. if (light) {
  24254. return light;
  24255. }
  24256. var camera = this.getCameraByName(name);
  24257. if (camera) {
  24258. return camera;
  24259. }
  24260. var bone = this.getBoneByName(name);
  24261. return bone;
  24262. };
  24263. Scene.prototype.getMeshByName = function (name) {
  24264. for (var index = 0; index < this.meshes.length; index++) {
  24265. if (this.meshes[index].name === name) {
  24266. return this.meshes[index];
  24267. }
  24268. }
  24269. return null;
  24270. };
  24271. Scene.prototype.getTransformNodeByName = function (name) {
  24272. for (var index = 0; index < this.transformNodes.length; index++) {
  24273. if (this.transformNodes[index].name === name) {
  24274. return this.transformNodes[index];
  24275. }
  24276. }
  24277. return null;
  24278. };
  24279. Scene.prototype.getSoundByName = function (name) {
  24280. var index;
  24281. if (BABYLON.AudioEngine) {
  24282. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  24283. if (this.mainSoundTrack.soundCollection[index].name === name) {
  24284. return this.mainSoundTrack.soundCollection[index];
  24285. }
  24286. }
  24287. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  24288. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  24289. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  24290. return this.soundTracks[sdIndex].soundCollection[index];
  24291. }
  24292. }
  24293. }
  24294. }
  24295. return null;
  24296. };
  24297. Scene.prototype.getLastSkeletonByID = function (id) {
  24298. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  24299. if (this.skeletons[index].id === id) {
  24300. return this.skeletons[index];
  24301. }
  24302. }
  24303. return null;
  24304. };
  24305. Scene.prototype.getSkeletonById = function (id) {
  24306. for (var index = 0; index < this.skeletons.length; index++) {
  24307. if (this.skeletons[index].id === id) {
  24308. return this.skeletons[index];
  24309. }
  24310. }
  24311. return null;
  24312. };
  24313. Scene.prototype.getSkeletonByName = function (name) {
  24314. for (var index = 0; index < this.skeletons.length; index++) {
  24315. if (this.skeletons[index].name === name) {
  24316. return this.skeletons[index];
  24317. }
  24318. }
  24319. return null;
  24320. };
  24321. Scene.prototype.getMorphTargetManagerById = function (id) {
  24322. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  24323. if (this.morphTargetManagers[index].uniqueId === id) {
  24324. return this.morphTargetManagers[index];
  24325. }
  24326. }
  24327. return null;
  24328. };
  24329. Scene.prototype.isActiveMesh = function (mesh) {
  24330. return (this._activeMeshes.indexOf(mesh) !== -1);
  24331. };
  24332. /**
  24333. * Return a the first highlight layer of the scene with a given name.
  24334. * @param name The name of the highlight layer to look for.
  24335. * @return The highlight layer if found otherwise null.
  24336. */
  24337. Scene.prototype.getHighlightLayerByName = function (name) {
  24338. for (var index = 0; index < this.effectLayers.length; index++) {
  24339. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  24340. return this.effectLayers[index];
  24341. }
  24342. }
  24343. return null;
  24344. };
  24345. /**
  24346. * Return a the first highlight layer of the scene with a given name.
  24347. * @param name The name of the highlight layer to look for.
  24348. * @return The highlight layer if found otherwise null.
  24349. */
  24350. Scene.prototype.getGlowLayerByName = function (name) {
  24351. for (var index = 0; index < this.effectLayers.length; index++) {
  24352. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  24353. return this.effectLayers[index];
  24354. }
  24355. }
  24356. return null;
  24357. };
  24358. Object.defineProperty(Scene.prototype, "uid", {
  24359. /**
  24360. * Return a unique id as a string which can serve as an identifier for the scene
  24361. */
  24362. get: function () {
  24363. if (!this._uid) {
  24364. this._uid = BABYLON.Tools.RandomId();
  24365. }
  24366. return this._uid;
  24367. },
  24368. enumerable: true,
  24369. configurable: true
  24370. });
  24371. /**
  24372. * Add an externaly attached data from its key.
  24373. * This method call will fail and return false, if such key already exists.
  24374. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  24375. * @param key the unique key that identifies the data
  24376. * @param data the data object to associate to the key for this Engine instance
  24377. * @return true if no such key were already present and the data was added successfully, false otherwise
  24378. */
  24379. Scene.prototype.addExternalData = function (key, data) {
  24380. if (!this._externalData) {
  24381. this._externalData = new BABYLON.StringDictionary();
  24382. }
  24383. return this._externalData.add(key, data);
  24384. };
  24385. /**
  24386. * Get an externaly attached data from its key
  24387. * @param key the unique key that identifies the data
  24388. * @return the associated data, if present (can be null), or undefined if not present
  24389. */
  24390. Scene.prototype.getExternalData = function (key) {
  24391. if (!this._externalData) {
  24392. return null;
  24393. }
  24394. return this._externalData.get(key);
  24395. };
  24396. /**
  24397. * Get an externaly attached data from its key, create it using a factory if it's not already present
  24398. * @param key the unique key that identifies the data
  24399. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  24400. * @return the associated data, can be null if the factory returned null.
  24401. */
  24402. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  24403. if (!this._externalData) {
  24404. this._externalData = new BABYLON.StringDictionary();
  24405. }
  24406. return this._externalData.getOrAddWithFactory(key, factory);
  24407. };
  24408. /**
  24409. * Remove an externaly attached data from the Engine instance
  24410. * @param key the unique key that identifies the data
  24411. * @return true if the data was successfully removed, false if it doesn't exist
  24412. */
  24413. Scene.prototype.removeExternalData = function (key) {
  24414. return this._externalData.remove(key);
  24415. };
  24416. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  24417. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  24418. if (mesh.showSubMeshesBoundingBox) {
  24419. var boundingInfo = subMesh.getBoundingInfo();
  24420. if (boundingInfo !== null && boundingInfo !== undefined) {
  24421. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24422. }
  24423. }
  24424. var material = subMesh.getMaterial();
  24425. if (material !== null && material !== undefined) {
  24426. // Render targets
  24427. if (material.getRenderTargetTextures !== undefined) {
  24428. if (this._processedMaterials.indexOf(material) === -1) {
  24429. this._processedMaterials.push(material);
  24430. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  24431. }
  24432. }
  24433. // Dispatch
  24434. this._activeIndices.addCount(subMesh.indexCount, false);
  24435. this._renderingManager.dispatch(subMesh, mesh, material);
  24436. }
  24437. }
  24438. };
  24439. /**
  24440. * Clear the processed materials smart array preventing retention point in material dispose.
  24441. */
  24442. Scene.prototype.freeProcessedMaterials = function () {
  24443. this._processedMaterials.dispose();
  24444. };
  24445. /**
  24446. * Clear the active meshes smart array preventing retention point in mesh dispose.
  24447. */
  24448. Scene.prototype.freeActiveMeshes = function () {
  24449. this._activeMeshes.dispose();
  24450. if (this.activeCamera && this.activeCamera._activeMeshes) {
  24451. this.activeCamera._activeMeshes.dispose();
  24452. }
  24453. if (this.activeCameras) {
  24454. for (var i = 0; i < this.activeCameras.length; i++) {
  24455. var activeCamera = this.activeCameras[i];
  24456. if (activeCamera && activeCamera._activeMeshes) {
  24457. activeCamera._activeMeshes.dispose();
  24458. }
  24459. }
  24460. }
  24461. };
  24462. /**
  24463. * Clear the info related to rendering groups preventing retention points during dispose.
  24464. */
  24465. Scene.prototype.freeRenderingGroups = function () {
  24466. if (this._renderingManager) {
  24467. this._renderingManager.freeRenderingGroups();
  24468. }
  24469. if (this.textures) {
  24470. for (var i = 0; i < this.textures.length; i++) {
  24471. var texture = this.textures[i];
  24472. if (texture && texture.renderList) {
  24473. texture.freeRenderingGroups();
  24474. }
  24475. }
  24476. }
  24477. };
  24478. Scene.prototype._isInIntermediateRendering = function () {
  24479. return this._intermediateRendering;
  24480. };
  24481. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  24482. this._activeMeshCandidateProvider = provider;
  24483. };
  24484. Scene.prototype.getActiveMeshCandidateProvider = function () {
  24485. return this._activeMeshCandidateProvider;
  24486. };
  24487. /**
  24488. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  24489. */
  24490. Scene.prototype.freezeActiveMeshes = function () {
  24491. if (!this.activeCamera) {
  24492. return this;
  24493. }
  24494. if (!this._frustumPlanes) {
  24495. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24496. }
  24497. this._evaluateActiveMeshes();
  24498. this._activeMeshesFrozen = true;
  24499. return this;
  24500. };
  24501. /**
  24502. * Use this function to restart evaluating active meshes on every frame
  24503. */
  24504. Scene.prototype.unfreezeActiveMeshes = function () {
  24505. this._activeMeshesFrozen = false;
  24506. return this;
  24507. };
  24508. Scene.prototype._evaluateActiveMeshes = function () {
  24509. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  24510. return;
  24511. }
  24512. if (!this.activeCamera) {
  24513. return;
  24514. }
  24515. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  24516. this.activeCamera._activeMeshes.reset();
  24517. this._activeMeshes.reset();
  24518. this._renderingManager.reset();
  24519. this._processedMaterials.reset();
  24520. this._activeParticleSystems.reset();
  24521. this._activeSkeletons.reset();
  24522. this._softwareSkinnedMeshes.reset();
  24523. if (this._boundingBoxRenderer) {
  24524. this._boundingBoxRenderer.reset();
  24525. }
  24526. // Meshes
  24527. var meshes;
  24528. var len;
  24529. var checkIsEnabled = true;
  24530. // Determine mesh candidates
  24531. if (this._activeMeshCandidateProvider !== undefined) {
  24532. // Use _activeMeshCandidateProvider
  24533. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  24534. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  24535. if (meshes !== undefined) {
  24536. len = meshes.length;
  24537. }
  24538. else {
  24539. len = 0;
  24540. }
  24541. }
  24542. else if (this._selectionOctree !== undefined) {
  24543. // Octree
  24544. var selection = this._selectionOctree.select(this._frustumPlanes);
  24545. meshes = selection.data;
  24546. len = selection.length;
  24547. }
  24548. else {
  24549. // Full scene traversal
  24550. len = this.meshes.length;
  24551. meshes = this.meshes;
  24552. }
  24553. // Check each mesh
  24554. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  24555. mesh = meshes[meshIndex];
  24556. if (mesh.isBlocked) {
  24557. continue;
  24558. }
  24559. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  24560. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  24561. continue;
  24562. }
  24563. mesh.computeWorldMatrix();
  24564. // Intersections
  24565. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  24566. this._meshesForIntersections.pushNoDuplicate(mesh);
  24567. }
  24568. // Switch to current LOD
  24569. meshLOD = mesh.getLOD(this.activeCamera);
  24570. if (meshLOD === undefined || meshLOD === null) {
  24571. continue;
  24572. }
  24573. mesh._preActivate();
  24574. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  24575. this._activeMeshes.push(mesh);
  24576. this.activeCamera._activeMeshes.push(mesh);
  24577. mesh._activate(this._renderId);
  24578. if (meshLOD !== mesh) {
  24579. meshLOD._activate(this._renderId);
  24580. }
  24581. this._activeMesh(mesh, meshLOD);
  24582. }
  24583. }
  24584. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  24585. // Particle systems
  24586. if (this.particlesEnabled) {
  24587. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  24588. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  24589. var particleSystem = this.particleSystems[particleIndex];
  24590. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  24591. continue;
  24592. }
  24593. var emitter = particleSystem.emitter;
  24594. if (!emitter.position || emitter.isEnabled()) {
  24595. this._activeParticleSystems.push(particleSystem);
  24596. particleSystem.animate();
  24597. this._renderingManager.dispatchParticles(particleSystem);
  24598. }
  24599. }
  24600. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  24601. }
  24602. };
  24603. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  24604. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  24605. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  24606. mesh.skeleton.prepare();
  24607. }
  24608. if (!mesh.computeBonesUsingShaders) {
  24609. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  24610. }
  24611. }
  24612. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  24613. var boundingInfo = sourceMesh.getBoundingInfo();
  24614. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24615. }
  24616. if (mesh !== undefined && mesh !== null
  24617. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  24618. // Submeshes Octrees
  24619. var len;
  24620. var subMeshes;
  24621. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  24622. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  24623. len = intersections.length;
  24624. subMeshes = intersections.data;
  24625. }
  24626. else {
  24627. subMeshes = mesh.subMeshes;
  24628. len = subMeshes.length;
  24629. }
  24630. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  24631. subMesh = subMeshes[subIndex];
  24632. this._evaluateSubMesh(subMesh, mesh);
  24633. }
  24634. }
  24635. };
  24636. Scene.prototype.updateTransformMatrix = function (force) {
  24637. if (!this.activeCamera) {
  24638. return;
  24639. }
  24640. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  24641. };
  24642. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  24643. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  24644. };
  24645. Scene.prototype._renderForCamera = function (camera, rigParent) {
  24646. if (camera && camera._skipRendering) {
  24647. return;
  24648. }
  24649. var engine = this._engine;
  24650. this.activeCamera = camera;
  24651. if (!this.activeCamera)
  24652. throw new Error("Active camera not set");
  24653. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24654. // Viewport
  24655. engine.setViewport(this.activeCamera.viewport);
  24656. // Camera
  24657. this.resetCachedMaterial();
  24658. this._renderId++;
  24659. this.updateTransformMatrix();
  24660. if (camera._alternateCamera) {
  24661. this.updateAlternateTransformMatrix(camera._alternateCamera);
  24662. this._alternateRendering = true;
  24663. }
  24664. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  24665. // Meshes
  24666. this._evaluateActiveMeshes();
  24667. // Software skinning
  24668. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  24669. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  24670. mesh.applySkeleton(mesh.skeleton);
  24671. }
  24672. // Render targets
  24673. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24674. var needsRestoreFrameBuffer = false;
  24675. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  24676. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  24677. }
  24678. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  24679. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  24680. }
  24681. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  24682. this._intermediateRendering = true;
  24683. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24684. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  24685. var renderTarget = this._renderTargets.data[renderIndex];
  24686. if (renderTarget._shouldRender()) {
  24687. this._renderId++;
  24688. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  24689. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  24690. }
  24691. }
  24692. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24693. this._intermediateRendering = false;
  24694. this._renderId++;
  24695. needsRestoreFrameBuffer = true; // Restore back buffer
  24696. }
  24697. // Render EffecttLayer Texture
  24698. var stencilState = this._engine.getStencilBuffer();
  24699. var renderEffects = false;
  24700. var needStencil = false;
  24701. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  24702. this._intermediateRendering = true;
  24703. for (var i = 0; i < this.effectLayers.length; i++) {
  24704. var effectLayer = this.effectLayers[i];
  24705. if (effectLayer.shouldRender() &&
  24706. (!effectLayer.camera ||
  24707. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  24708. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  24709. renderEffects = true;
  24710. needStencil = needStencil || effectLayer.needStencil();
  24711. var renderTarget = effectLayer._mainTexture;
  24712. if (renderTarget._shouldRender()) {
  24713. this._renderId++;
  24714. renderTarget.render(false, false);
  24715. needsRestoreFrameBuffer = true;
  24716. }
  24717. }
  24718. }
  24719. this._intermediateRendering = false;
  24720. this._renderId++;
  24721. }
  24722. if (needsRestoreFrameBuffer) {
  24723. engine.restoreDefaultFramebuffer(); // Restore back buffer
  24724. }
  24725. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24726. // Prepare Frame
  24727. this.postProcessManager._prepareFrame();
  24728. // Backgrounds
  24729. var layerIndex;
  24730. var layer;
  24731. if (this.layers.length) {
  24732. engine.setDepthBuffer(false);
  24733. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24734. layer = this.layers[layerIndex];
  24735. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24736. layer.render();
  24737. }
  24738. }
  24739. engine.setDepthBuffer(true);
  24740. }
  24741. // Activate effect Layer stencil
  24742. if (needStencil) {
  24743. this._engine.setStencilBuffer(true);
  24744. }
  24745. // Render
  24746. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  24747. this._renderingManager.render(null, null, true, true);
  24748. this.onAfterDrawPhaseObservable.notifyObservers(this);
  24749. // Restore effect Layer stencil
  24750. if (needStencil) {
  24751. this._engine.setStencilBuffer(stencilState);
  24752. }
  24753. // Bounding boxes
  24754. if (this._boundingBoxRenderer) {
  24755. this._boundingBoxRenderer.render();
  24756. }
  24757. // Lens flares
  24758. if (this.lensFlaresEnabled) {
  24759. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24760. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  24761. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  24762. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  24763. lensFlareSystem.render();
  24764. }
  24765. }
  24766. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24767. }
  24768. // Foregrounds
  24769. if (this.layers.length) {
  24770. engine.setDepthBuffer(false);
  24771. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24772. layer = this.layers[layerIndex];
  24773. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24774. layer.render();
  24775. }
  24776. }
  24777. engine.setDepthBuffer(true);
  24778. }
  24779. // Effect Layer
  24780. if (renderEffects) {
  24781. engine.setDepthBuffer(false);
  24782. for (var i = 0; i < this.effectLayers.length; i++) {
  24783. if (this.effectLayers[i].shouldRender()) {
  24784. this.effectLayers[i].render();
  24785. }
  24786. }
  24787. engine.setDepthBuffer(true);
  24788. }
  24789. // Finalize frame
  24790. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  24791. // Reset some special arrays
  24792. this._renderTargets.reset();
  24793. this._alternateRendering = false;
  24794. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  24795. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24796. };
  24797. Scene.prototype._processSubCameras = function (camera) {
  24798. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  24799. this._renderForCamera(camera);
  24800. return;
  24801. }
  24802. // rig cameras
  24803. for (var index = 0; index < camera._rigCameras.length; index++) {
  24804. this._renderForCamera(camera._rigCameras[index], camera);
  24805. }
  24806. this.activeCamera = camera;
  24807. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24808. };
  24809. Scene.prototype._checkIntersections = function () {
  24810. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  24811. var sourceMesh = this._meshesForIntersections.data[index];
  24812. if (!sourceMesh.actionManager) {
  24813. continue;
  24814. }
  24815. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  24816. var action = sourceMesh.actionManager.actions[actionIndex];
  24817. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24818. var parameters = action.getTriggerParameter();
  24819. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  24820. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  24821. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  24822. if (areIntersecting && currentIntersectionInProgress === -1) {
  24823. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  24824. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24825. sourceMesh._intersectionsInProgress.push(otherMesh);
  24826. }
  24827. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24828. sourceMesh._intersectionsInProgress.push(otherMesh);
  24829. }
  24830. }
  24831. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  24832. //They intersected, and now they don't.
  24833. //is this trigger an exit trigger? execute an event.
  24834. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24835. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24836. }
  24837. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  24838. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24839. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  24840. }
  24841. }
  24842. }
  24843. }
  24844. }
  24845. };
  24846. Scene.prototype.render = function () {
  24847. if (this.isDisposed) {
  24848. return;
  24849. }
  24850. this._activeParticles.fetchNewFrame();
  24851. this._totalVertices.fetchNewFrame();
  24852. this._activeIndices.fetchNewFrame();
  24853. this._activeBones.fetchNewFrame();
  24854. this._meshesForIntersections.reset();
  24855. this.resetCachedMaterial();
  24856. this.onBeforeAnimationsObservable.notifyObservers(this);
  24857. // Actions
  24858. if (this.actionManager) {
  24859. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  24860. }
  24861. //Simplification Queue
  24862. if (this.simplificationQueue && !this.simplificationQueue.running) {
  24863. this.simplificationQueue.executeNext();
  24864. }
  24865. if (this._engine.isDeterministicLockStep()) {
  24866. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  24867. var defaultFPS = (60.0 / 1000.0);
  24868. var defaultFrameTime = 1000 / 60; // frame time in MS
  24869. if (this._physicsEngine) {
  24870. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  24871. }
  24872. var stepsTaken = 0;
  24873. var maxSubSteps = this._engine.getLockstepMaxSteps();
  24874. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  24875. internalSteps = Math.min(internalSteps, maxSubSteps);
  24876. do {
  24877. this.onBeforeStepObservable.notifyObservers(this);
  24878. // Animations
  24879. this._animationRatio = defaultFrameTime * defaultFPS;
  24880. this._animate();
  24881. this.onAfterAnimationsObservable.notifyObservers(this);
  24882. // Physics
  24883. if (this._physicsEngine) {
  24884. this.onBeforePhysicsObservable.notifyObservers(this);
  24885. this._physicsEngine._step(defaultFrameTime / 1000);
  24886. this.onAfterPhysicsObservable.notifyObservers(this);
  24887. }
  24888. this.onAfterStepObservable.notifyObservers(this);
  24889. this._currentStepId++;
  24890. stepsTaken++;
  24891. deltaTime -= defaultFrameTime;
  24892. } while (deltaTime > 0 && stepsTaken < internalSteps);
  24893. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  24894. }
  24895. else {
  24896. // Animations
  24897. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  24898. this._animationRatio = deltaTime * (60.0 / 1000.0);
  24899. this._animate();
  24900. this.onAfterAnimationsObservable.notifyObservers(this);
  24901. // Physics
  24902. if (this._physicsEngine) {
  24903. this.onBeforePhysicsObservable.notifyObservers(this);
  24904. this._physicsEngine._step(deltaTime / 1000.0);
  24905. this.onAfterPhysicsObservable.notifyObservers(this);
  24906. }
  24907. }
  24908. // update gamepad manager
  24909. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  24910. this._gamepadManager._checkGamepadsStatus();
  24911. }
  24912. // Update Cameras
  24913. if (this.activeCameras.length > 0) {
  24914. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24915. var camera = this.activeCameras[cameraIndex];
  24916. camera.update();
  24917. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24918. // rig cameras
  24919. for (var index = 0; index < camera._rigCameras.length; index++) {
  24920. camera._rigCameras[index].update();
  24921. }
  24922. }
  24923. }
  24924. }
  24925. else if (this.activeCamera) {
  24926. this.activeCamera.update();
  24927. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24928. // rig cameras
  24929. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  24930. this.activeCamera._rigCameras[index].update();
  24931. }
  24932. }
  24933. }
  24934. // Before render
  24935. this.onBeforeRenderObservable.notifyObservers(this);
  24936. // Customs render targets
  24937. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24938. var engine = this.getEngine();
  24939. var currentActiveCamera = this.activeCamera;
  24940. if (this.renderTargetsEnabled) {
  24941. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24942. this._intermediateRendering = true;
  24943. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  24944. var renderTarget = this.customRenderTargets[customIndex];
  24945. if (renderTarget._shouldRender()) {
  24946. this._renderId++;
  24947. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  24948. if (!this.activeCamera)
  24949. throw new Error("Active camera not set");
  24950. // Viewport
  24951. engine.setViewport(this.activeCamera.viewport);
  24952. // Camera
  24953. this.updateTransformMatrix();
  24954. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  24955. }
  24956. }
  24957. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24958. this._intermediateRendering = false;
  24959. this._renderId++;
  24960. }
  24961. // Restore back buffer
  24962. if (this.customRenderTargets.length > 0) {
  24963. engine.restoreDefaultFramebuffer();
  24964. }
  24965. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24966. this.activeCamera = currentActiveCamera;
  24967. // Procedural textures
  24968. if (this.proceduralTexturesEnabled) {
  24969. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24970. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  24971. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  24972. if (proceduralTexture._shouldRender()) {
  24973. proceduralTexture.render();
  24974. }
  24975. }
  24976. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24977. }
  24978. // Clear
  24979. if (this.autoClearDepthAndStencil || this.autoClear) {
  24980. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24981. }
  24982. // Shadows
  24983. if (this.shadowsEnabled) {
  24984. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24985. var light = this.lights[lightIndex];
  24986. var shadowGenerator = light.getShadowGenerator();
  24987. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24988. var shadowMap = (shadowGenerator.getShadowMap());
  24989. if (this.textures.indexOf(shadowMap) !== -1) {
  24990. this._renderTargets.push(shadowMap);
  24991. }
  24992. }
  24993. }
  24994. }
  24995. // Depth renderer
  24996. for (var key in this._depthRenderer) {
  24997. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  24998. }
  24999. // Geometry renderer
  25000. if (this._geometryBufferRenderer) {
  25001. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  25002. }
  25003. // RenderPipeline
  25004. if (this._postProcessRenderPipelineManager) {
  25005. this._postProcessRenderPipelineManager.update();
  25006. }
  25007. // Multi-cameras?
  25008. if (this.activeCameras.length > 0) {
  25009. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  25010. if (cameraIndex > 0) {
  25011. this._engine.clear(null, false, true, true);
  25012. }
  25013. this._processSubCameras(this.activeCameras[cameraIndex]);
  25014. }
  25015. }
  25016. else {
  25017. if (!this.activeCamera) {
  25018. throw new Error("No camera defined");
  25019. }
  25020. this._processSubCameras(this.activeCamera);
  25021. }
  25022. // Intersection checks
  25023. this._checkIntersections();
  25024. // Update the audio listener attached to the camera
  25025. if (BABYLON.AudioEngine) {
  25026. this._updateAudioParameters();
  25027. }
  25028. // After render
  25029. if (this.afterRender) {
  25030. this.afterRender();
  25031. }
  25032. this.onAfterRenderObservable.notifyObservers(this);
  25033. // Cleaning
  25034. for (var index = 0; index < this._toBeDisposed.length; index++) {
  25035. var data = this._toBeDisposed.data[index];
  25036. if (data) {
  25037. data.dispose();
  25038. }
  25039. this._toBeDisposed[index] = null;
  25040. }
  25041. this._toBeDisposed.reset();
  25042. if (this.dumpNextRenderTargets) {
  25043. this.dumpNextRenderTargets = false;
  25044. }
  25045. this._activeBones.addCount(0, true);
  25046. this._activeIndices.addCount(0, true);
  25047. this._activeParticles.addCount(0, true);
  25048. };
  25049. Scene.prototype._updateAudioParameters = function () {
  25050. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  25051. return;
  25052. }
  25053. var listeningCamera;
  25054. var audioEngine = BABYLON.Engine.audioEngine;
  25055. if (this.activeCameras.length > 0) {
  25056. listeningCamera = this.activeCameras[0];
  25057. }
  25058. else {
  25059. listeningCamera = this.activeCamera;
  25060. }
  25061. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  25062. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  25063. // for VR cameras
  25064. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  25065. listeningCamera = listeningCamera.rigCameras[0];
  25066. }
  25067. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  25068. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  25069. cameraDirection.normalize();
  25070. // To avoid some errors on GearVR
  25071. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  25072. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  25073. }
  25074. var i;
  25075. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  25076. var sound = this.mainSoundTrack.soundCollection[i];
  25077. if (sound.useCustomAttenuation) {
  25078. sound.updateDistanceFromListener();
  25079. }
  25080. }
  25081. for (i = 0; i < this.soundTracks.length; i++) {
  25082. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  25083. sound = this.soundTracks[i].soundCollection[j];
  25084. if (sound.useCustomAttenuation) {
  25085. sound.updateDistanceFromListener();
  25086. }
  25087. }
  25088. }
  25089. }
  25090. };
  25091. Object.defineProperty(Scene.prototype, "audioEnabled", {
  25092. // Audio
  25093. get: function () {
  25094. return this._audioEnabled;
  25095. },
  25096. set: function (value) {
  25097. this._audioEnabled = value;
  25098. if (BABYLON.AudioEngine) {
  25099. if (this._audioEnabled) {
  25100. this._enableAudio();
  25101. }
  25102. else {
  25103. this._disableAudio();
  25104. }
  25105. }
  25106. },
  25107. enumerable: true,
  25108. configurable: true
  25109. });
  25110. Scene.prototype._disableAudio = function () {
  25111. var i;
  25112. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  25113. this.mainSoundTrack.soundCollection[i].pause();
  25114. }
  25115. for (i = 0; i < this.soundTracks.length; i++) {
  25116. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  25117. this.soundTracks[i].soundCollection[j].pause();
  25118. }
  25119. }
  25120. };
  25121. Scene.prototype._enableAudio = function () {
  25122. var i;
  25123. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  25124. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  25125. this.mainSoundTrack.soundCollection[i].play();
  25126. }
  25127. }
  25128. for (i = 0; i < this.soundTracks.length; i++) {
  25129. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  25130. if (this.soundTracks[i].soundCollection[j].isPaused) {
  25131. this.soundTracks[i].soundCollection[j].play();
  25132. }
  25133. }
  25134. }
  25135. };
  25136. Object.defineProperty(Scene.prototype, "headphone", {
  25137. get: function () {
  25138. return this._headphone;
  25139. },
  25140. set: function (value) {
  25141. this._headphone = value;
  25142. if (BABYLON.AudioEngine) {
  25143. if (this._headphone) {
  25144. this._switchAudioModeForHeadphones();
  25145. }
  25146. else {
  25147. this._switchAudioModeForNormalSpeakers();
  25148. }
  25149. }
  25150. },
  25151. enumerable: true,
  25152. configurable: true
  25153. });
  25154. Scene.prototype._switchAudioModeForHeadphones = function () {
  25155. this.mainSoundTrack.switchPanningModelToHRTF();
  25156. for (var i = 0; i < this.soundTracks.length; i++) {
  25157. this.soundTracks[i].switchPanningModelToHRTF();
  25158. }
  25159. };
  25160. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  25161. this.mainSoundTrack.switchPanningModelToEqualPower();
  25162. for (var i = 0; i < this.soundTracks.length; i++) {
  25163. this.soundTracks[i].switchPanningModelToEqualPower();
  25164. }
  25165. };
  25166. /**
  25167. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  25168. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  25169. * @returns the created depth renderer
  25170. */
  25171. Scene.prototype.enableDepthRenderer = function (camera) {
  25172. camera = camera || this.activeCamera;
  25173. if (!camera) {
  25174. throw "No camera available to enable depth renderer";
  25175. }
  25176. if (!this._depthRenderer[camera.id]) {
  25177. var textureType = 0;
  25178. if (this._engine.getCaps().textureHalfFloatRender) {
  25179. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  25180. }
  25181. else if (this._engine.getCaps().textureFloatRender) {
  25182. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  25183. }
  25184. else {
  25185. throw "Depth renderer does not support int texture type";
  25186. }
  25187. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  25188. }
  25189. return this._depthRenderer[camera.id];
  25190. };
  25191. /**
  25192. * Disables a depth renderer for a given camera
  25193. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  25194. */
  25195. Scene.prototype.disableDepthRenderer = function (camera) {
  25196. camera = camera || this.activeCamera;
  25197. if (!camera || !this._depthRenderer[camera.id]) {
  25198. return;
  25199. }
  25200. this._depthRenderer[camera.id].dispose();
  25201. delete this._depthRenderer[camera.id];
  25202. };
  25203. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  25204. if (ratio === void 0) { ratio = 1; }
  25205. if (this._geometryBufferRenderer) {
  25206. return this._geometryBufferRenderer;
  25207. }
  25208. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  25209. if (!this._geometryBufferRenderer.isSupported) {
  25210. this._geometryBufferRenderer = null;
  25211. }
  25212. return this._geometryBufferRenderer;
  25213. };
  25214. Scene.prototype.disableGeometryBufferRenderer = function () {
  25215. if (!this._geometryBufferRenderer) {
  25216. return;
  25217. }
  25218. this._geometryBufferRenderer.dispose();
  25219. this._geometryBufferRenderer = null;
  25220. };
  25221. Scene.prototype.freezeMaterials = function () {
  25222. for (var i = 0; i < this.materials.length; i++) {
  25223. this.materials[i].freeze();
  25224. }
  25225. };
  25226. Scene.prototype.unfreezeMaterials = function () {
  25227. for (var i = 0; i < this.materials.length; i++) {
  25228. this.materials[i].unfreeze();
  25229. }
  25230. };
  25231. Scene.prototype.dispose = function () {
  25232. this.beforeRender = null;
  25233. this.afterRender = null;
  25234. this.skeletons = [];
  25235. this.morphTargetManagers = [];
  25236. this.importedMeshesFiles = new Array();
  25237. this.stopAllAnimations();
  25238. this.resetCachedMaterial();
  25239. for (var key in this._depthRenderer) {
  25240. this._depthRenderer[key].dispose();
  25241. }
  25242. if (this._gamepadManager) {
  25243. this._gamepadManager.dispose();
  25244. this._gamepadManager = null;
  25245. }
  25246. // Smart arrays
  25247. if (this.activeCamera) {
  25248. this.activeCamera._activeMeshes.dispose();
  25249. this.activeCamera = null;
  25250. }
  25251. this._activeMeshes.dispose();
  25252. this._renderingManager.dispose();
  25253. this._processedMaterials.dispose();
  25254. this._activeParticleSystems.dispose();
  25255. this._activeSkeletons.dispose();
  25256. this._softwareSkinnedMeshes.dispose();
  25257. this._renderTargets.dispose();
  25258. this._registeredForLateAnimationBindings.dispose();
  25259. if (this._boundingBoxRenderer) {
  25260. this._boundingBoxRenderer.dispose();
  25261. }
  25262. this._meshesForIntersections.dispose();
  25263. this._toBeDisposed.dispose();
  25264. // Abort active requests
  25265. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  25266. var request = _a[_i];
  25267. request.abort();
  25268. }
  25269. // Debug layer
  25270. if (this._debugLayer) {
  25271. this._debugLayer.hide();
  25272. }
  25273. // Events
  25274. this.onDisposeObservable.notifyObservers(this);
  25275. this.onDisposeObservable.clear();
  25276. this.onBeforeRenderObservable.clear();
  25277. this.onAfterRenderObservable.clear();
  25278. this.OnBeforeRenderTargetsRenderObservable.clear();
  25279. this.OnAfterRenderTargetsRenderObservable.clear();
  25280. this.onAfterStepObservable.clear();
  25281. this.onBeforeStepObservable.clear();
  25282. this.onBeforeActiveMeshesEvaluationObservable.clear();
  25283. this.onAfterActiveMeshesEvaluationObservable.clear();
  25284. this.onBeforeParticlesRenderingObservable.clear();
  25285. this.onAfterParticlesRenderingObservable.clear();
  25286. this.onBeforeSpritesRenderingObservable.clear();
  25287. this.onAfterSpritesRenderingObservable.clear();
  25288. this.onBeforeDrawPhaseObservable.clear();
  25289. this.onAfterDrawPhaseObservable.clear();
  25290. this.onBeforePhysicsObservable.clear();
  25291. this.onAfterPhysicsObservable.clear();
  25292. this.onBeforeAnimationsObservable.clear();
  25293. this.onAfterAnimationsObservable.clear();
  25294. this.onDataLoadedObservable.clear();
  25295. this.detachControl();
  25296. // Release sounds & sounds tracks
  25297. if (BABYLON.AudioEngine) {
  25298. this.disposeSounds();
  25299. }
  25300. // VR Helper
  25301. if (this.VRHelper) {
  25302. this.VRHelper.dispose();
  25303. }
  25304. // Detach cameras
  25305. var canvas = this._engine.getRenderingCanvas();
  25306. if (canvas) {
  25307. var index;
  25308. for (index = 0; index < this.cameras.length; index++) {
  25309. this.cameras[index].detachControl(canvas);
  25310. }
  25311. }
  25312. // Release animation groups
  25313. while (this.animationGroups.length) {
  25314. this.animationGroups[0].dispose();
  25315. }
  25316. // Release lights
  25317. while (this.lights.length) {
  25318. this.lights[0].dispose();
  25319. }
  25320. // Release meshes
  25321. while (this.meshes.length) {
  25322. this.meshes[0].dispose(true);
  25323. }
  25324. while (this.transformNodes.length) {
  25325. this.removeTransformNode(this.transformNodes[0]);
  25326. }
  25327. // Release cameras
  25328. while (this.cameras.length) {
  25329. this.cameras[0].dispose();
  25330. }
  25331. // Release materials
  25332. if (this.defaultMaterial) {
  25333. this.defaultMaterial.dispose();
  25334. }
  25335. while (this.multiMaterials.length) {
  25336. this.multiMaterials[0].dispose();
  25337. }
  25338. while (this.materials.length) {
  25339. this.materials[0].dispose();
  25340. }
  25341. // Release particles
  25342. while (this.particleSystems.length) {
  25343. this.particleSystems[0].dispose();
  25344. }
  25345. // Release sprites
  25346. while (this.spriteManagers.length) {
  25347. this.spriteManagers[0].dispose();
  25348. }
  25349. // Release postProcesses
  25350. while (this.postProcesses.length) {
  25351. this.postProcesses[0].dispose();
  25352. }
  25353. // Release layers
  25354. while (this.layers.length) {
  25355. this.layers[0].dispose();
  25356. }
  25357. while (this.effectLayers.length) {
  25358. this.effectLayers[0].dispose();
  25359. }
  25360. // Release textures
  25361. while (this.textures.length) {
  25362. this.textures[0].dispose();
  25363. }
  25364. // Release UBO
  25365. this._sceneUbo.dispose();
  25366. if (this._alternateSceneUbo) {
  25367. this._alternateSceneUbo.dispose();
  25368. }
  25369. // Post-processes
  25370. this.postProcessManager.dispose();
  25371. if (this._postProcessRenderPipelineManager) {
  25372. this._postProcessRenderPipelineManager.dispose();
  25373. }
  25374. // Physics
  25375. if (this._physicsEngine) {
  25376. this.disablePhysicsEngine();
  25377. }
  25378. // Remove from engine
  25379. index = this._engine.scenes.indexOf(this);
  25380. if (index > -1) {
  25381. this._engine.scenes.splice(index, 1);
  25382. }
  25383. this._engine.wipeCaches(true);
  25384. this._isDisposed = true;
  25385. };
  25386. Object.defineProperty(Scene.prototype, "isDisposed", {
  25387. get: function () {
  25388. return this._isDisposed;
  25389. },
  25390. enumerable: true,
  25391. configurable: true
  25392. });
  25393. // Release sounds & sounds tracks
  25394. Scene.prototype.disposeSounds = function () {
  25395. if (!this._mainSoundTrack) {
  25396. return;
  25397. }
  25398. this.mainSoundTrack.dispose();
  25399. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  25400. this.soundTracks[scIndex].dispose();
  25401. }
  25402. };
  25403. // Octrees
  25404. /**
  25405. * Get the world extend vectors with an optional filter
  25406. *
  25407. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  25408. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  25409. */
  25410. Scene.prototype.getWorldExtends = function (filterPredicate) {
  25411. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  25412. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  25413. filterPredicate = filterPredicate || (function () { return true; });
  25414. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  25415. mesh.computeWorldMatrix(true);
  25416. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  25417. return;
  25418. }
  25419. var boundingInfo = mesh.getBoundingInfo();
  25420. var minBox = boundingInfo.boundingBox.minimumWorld;
  25421. var maxBox = boundingInfo.boundingBox.maximumWorld;
  25422. BABYLON.Tools.CheckExtends(minBox, min, max);
  25423. BABYLON.Tools.CheckExtends(maxBox, min, max);
  25424. });
  25425. return {
  25426. min: min,
  25427. max: max
  25428. };
  25429. };
  25430. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  25431. if (maxCapacity === void 0) { maxCapacity = 64; }
  25432. if (maxDepth === void 0) { maxDepth = 2; }
  25433. if (!this._selectionOctree) {
  25434. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  25435. }
  25436. var worldExtends = this.getWorldExtends();
  25437. // Update octree
  25438. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  25439. return this._selectionOctree;
  25440. };
  25441. // Picking
  25442. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  25443. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25444. var result = BABYLON.Ray.Zero();
  25445. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  25446. return result;
  25447. };
  25448. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  25449. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25450. var engine = this._engine;
  25451. if (!camera) {
  25452. if (!this.activeCamera)
  25453. throw new Error("Active camera not set");
  25454. camera = this.activeCamera;
  25455. }
  25456. var cameraViewport = camera.viewport;
  25457. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25458. // Moving coordinates to local viewport world
  25459. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25460. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25461. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  25462. return this;
  25463. };
  25464. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  25465. var result = BABYLON.Ray.Zero();
  25466. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  25467. return result;
  25468. };
  25469. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  25470. if (!BABYLON.PickingInfo) {
  25471. return this;
  25472. }
  25473. var engine = this._engine;
  25474. if (!camera) {
  25475. if (!this.activeCamera)
  25476. throw new Error("Active camera not set");
  25477. camera = this.activeCamera;
  25478. }
  25479. var cameraViewport = camera.viewport;
  25480. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25481. var identity = BABYLON.Matrix.Identity();
  25482. // Moving coordinates to local viewport world
  25483. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25484. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25485. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  25486. return this;
  25487. };
  25488. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  25489. if (!BABYLON.PickingInfo) {
  25490. return null;
  25491. }
  25492. var pickingInfo = null;
  25493. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25494. var mesh = this.meshes[meshIndex];
  25495. if (predicate) {
  25496. if (!predicate(mesh)) {
  25497. continue;
  25498. }
  25499. }
  25500. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25501. continue;
  25502. }
  25503. var world = mesh.getWorldMatrix();
  25504. var ray = rayFunction(world);
  25505. var result = mesh.intersects(ray, fastCheck);
  25506. if (!result || !result.hit)
  25507. continue;
  25508. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25509. continue;
  25510. pickingInfo = result;
  25511. if (fastCheck) {
  25512. break;
  25513. }
  25514. }
  25515. return pickingInfo || new BABYLON.PickingInfo();
  25516. };
  25517. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  25518. if (!BABYLON.PickingInfo) {
  25519. return null;
  25520. }
  25521. var pickingInfos = new Array();
  25522. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25523. var mesh = this.meshes[meshIndex];
  25524. if (predicate) {
  25525. if (!predicate(mesh)) {
  25526. continue;
  25527. }
  25528. }
  25529. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25530. continue;
  25531. }
  25532. var world = mesh.getWorldMatrix();
  25533. var ray = rayFunction(world);
  25534. var result = mesh.intersects(ray, false);
  25535. if (!result || !result.hit)
  25536. continue;
  25537. pickingInfos.push(result);
  25538. }
  25539. return pickingInfos;
  25540. };
  25541. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  25542. if (!BABYLON.PickingInfo) {
  25543. return null;
  25544. }
  25545. var pickingInfo = null;
  25546. if (!camera) {
  25547. if (!this.activeCamera) {
  25548. return null;
  25549. }
  25550. camera = this.activeCamera;
  25551. }
  25552. if (this.spriteManagers.length > 0) {
  25553. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  25554. var spriteManager = this.spriteManagers[spriteIndex];
  25555. if (!spriteManager.isPickable) {
  25556. continue;
  25557. }
  25558. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  25559. if (!result || !result.hit)
  25560. continue;
  25561. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25562. continue;
  25563. pickingInfo = result;
  25564. if (fastCheck) {
  25565. break;
  25566. }
  25567. }
  25568. }
  25569. return pickingInfo || new BABYLON.PickingInfo();
  25570. };
  25571. /** Launch a ray to try to pick a mesh in the scene
  25572. * @param x position on screen
  25573. * @param y position on screen
  25574. * @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
  25575. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25576. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25577. */
  25578. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  25579. var _this = this;
  25580. if (!BABYLON.PickingInfo) {
  25581. return null;
  25582. }
  25583. return this._internalPick(function (world) {
  25584. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  25585. return _this._tempPickingRay;
  25586. }, predicate, fastCheck);
  25587. };
  25588. /** Launch a ray to try to pick a sprite in the scene
  25589. * @param x position on screen
  25590. * @param y position on screen
  25591. * @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
  25592. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25593. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25594. */
  25595. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  25596. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  25597. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  25598. };
  25599. /** Use the given ray to pick a mesh in the scene
  25600. * @param ray The ray to use to pick meshes
  25601. * @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
  25602. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25603. */
  25604. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  25605. var _this = this;
  25606. return this._internalPick(function (world) {
  25607. if (!_this._pickWithRayInverseMatrix) {
  25608. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25609. }
  25610. world.invertToRef(_this._pickWithRayInverseMatrix);
  25611. if (!_this._cachedRayForTransform) {
  25612. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25613. }
  25614. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25615. return _this._cachedRayForTransform;
  25616. }, predicate, fastCheck);
  25617. };
  25618. /**
  25619. * Launch a ray to try to pick a mesh in the scene
  25620. * @param x X position on screen
  25621. * @param y Y position on screen
  25622. * @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
  25623. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25624. */
  25625. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  25626. var _this = this;
  25627. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  25628. };
  25629. /**
  25630. * Launch a ray to try to pick a mesh in the scene
  25631. * @param ray Ray to use
  25632. * @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
  25633. */
  25634. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  25635. var _this = this;
  25636. return this._internalMultiPick(function (world) {
  25637. if (!_this._pickWithRayInverseMatrix) {
  25638. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25639. }
  25640. world.invertToRef(_this._pickWithRayInverseMatrix);
  25641. if (!_this._cachedRayForTransform) {
  25642. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25643. }
  25644. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25645. return _this._cachedRayForTransform;
  25646. }, predicate);
  25647. };
  25648. Scene.prototype.setPointerOverMesh = function (mesh) {
  25649. if (this._pointerOverMesh === mesh) {
  25650. return;
  25651. }
  25652. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25653. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25654. }
  25655. this._pointerOverMesh = mesh;
  25656. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25657. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25658. }
  25659. };
  25660. Scene.prototype.getPointerOverMesh = function () {
  25661. return this._pointerOverMesh;
  25662. };
  25663. Scene.prototype.setPointerOverSprite = function (sprite) {
  25664. if (this._pointerOverSprite === sprite) {
  25665. return;
  25666. }
  25667. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25668. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25669. }
  25670. this._pointerOverSprite = sprite;
  25671. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25672. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25673. }
  25674. };
  25675. Scene.prototype.getPointerOverSprite = function () {
  25676. return this._pointerOverSprite;
  25677. };
  25678. // Physics
  25679. Scene.prototype.getPhysicsEngine = function () {
  25680. return this._physicsEngine;
  25681. };
  25682. /**
  25683. * Enables physics to the current scene
  25684. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  25685. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  25686. * @return {boolean} was the physics engine initialized
  25687. */
  25688. Scene.prototype.enablePhysics = function (gravity, plugin) {
  25689. if (gravity === void 0) { gravity = null; }
  25690. if (this._physicsEngine) {
  25691. return true;
  25692. }
  25693. try {
  25694. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  25695. return true;
  25696. }
  25697. catch (e) {
  25698. BABYLON.Tools.Error(e.message);
  25699. return false;
  25700. }
  25701. };
  25702. Scene.prototype.disablePhysicsEngine = function () {
  25703. if (!this._physicsEngine) {
  25704. return;
  25705. }
  25706. this._physicsEngine.dispose();
  25707. this._physicsEngine = null;
  25708. };
  25709. Scene.prototype.isPhysicsEnabled = function () {
  25710. return this._physicsEngine !== undefined;
  25711. };
  25712. Scene.prototype.deleteCompoundImpostor = function (compound) {
  25713. var mesh = compound.parts[0].mesh;
  25714. if (mesh.physicsImpostor) {
  25715. mesh.physicsImpostor.dispose();
  25716. mesh.physicsImpostor = null;
  25717. }
  25718. };
  25719. // Misc.
  25720. Scene.prototype._rebuildGeometries = function () {
  25721. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  25722. var geometry = _a[_i];
  25723. geometry._rebuild();
  25724. }
  25725. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  25726. var mesh = _c[_b];
  25727. mesh._rebuild();
  25728. }
  25729. if (this.postProcessManager) {
  25730. this.postProcessManager._rebuild();
  25731. }
  25732. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  25733. var layer = _e[_d];
  25734. layer._rebuild();
  25735. }
  25736. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  25737. var effectLayer = _g[_f];
  25738. effectLayer._rebuild();
  25739. }
  25740. if (this._boundingBoxRenderer) {
  25741. this._boundingBoxRenderer._rebuild();
  25742. }
  25743. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  25744. var system = _j[_h];
  25745. system.rebuild();
  25746. }
  25747. if (this._postProcessRenderPipelineManager) {
  25748. this._postProcessRenderPipelineManager._rebuild();
  25749. }
  25750. };
  25751. Scene.prototype._rebuildTextures = function () {
  25752. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  25753. var texture = _a[_i];
  25754. texture._rebuild();
  25755. }
  25756. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25757. };
  25758. /**
  25759. * Creates a default light for the scene.
  25760. * @param replace Whether to replace the existing lights in the scene.
  25761. */
  25762. Scene.prototype.createDefaultLight = function (replace) {
  25763. if (replace === void 0) { replace = false; }
  25764. // Dispose existing light in replace mode.
  25765. if (replace) {
  25766. if (this.lights) {
  25767. for (var i = 0; i < this.lights.length; i++) {
  25768. this.lights[i].dispose();
  25769. }
  25770. }
  25771. }
  25772. // Light
  25773. if (this.lights.length === 0) {
  25774. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  25775. }
  25776. };
  25777. /**
  25778. * Creates a default camera for the scene.
  25779. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  25780. * @param replace Whether to replace the existing active camera in the scene.
  25781. * @param attachCameraControls Whether to attach camera controls to the canvas.
  25782. */
  25783. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  25784. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25785. if (replace === void 0) { replace = false; }
  25786. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25787. // Dispose existing camera in replace mode.
  25788. if (replace) {
  25789. if (this.activeCamera) {
  25790. this.activeCamera.dispose();
  25791. this.activeCamera = null;
  25792. }
  25793. }
  25794. // Camera
  25795. if (!this.activeCamera) {
  25796. var worldExtends = this.getWorldExtends();
  25797. var worldSize = worldExtends.max.subtract(worldExtends.min);
  25798. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  25799. var camera;
  25800. var radius = worldSize.length() * 1.5;
  25801. // empty scene scenario!
  25802. if (!isFinite(radius)) {
  25803. radius = 1;
  25804. worldCenter.copyFromFloats(0, 0, 0);
  25805. }
  25806. if (createArcRotateCamera) {
  25807. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  25808. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  25809. arcRotateCamera.wheelPrecision = 100 / radius;
  25810. camera = arcRotateCamera;
  25811. }
  25812. else {
  25813. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  25814. freeCamera.setTarget(worldCenter);
  25815. camera = freeCamera;
  25816. }
  25817. camera.minZ = radius * 0.01;
  25818. camera.maxZ = radius * 1000;
  25819. camera.speed = radius * 0.2;
  25820. this.activeCamera = camera;
  25821. var canvas = this.getEngine().getRenderingCanvas();
  25822. if (attachCameraControls && canvas) {
  25823. camera.attachControl(canvas);
  25824. }
  25825. }
  25826. };
  25827. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  25828. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25829. if (replace === void 0) { replace = false; }
  25830. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25831. this.createDefaultLight(replace);
  25832. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  25833. };
  25834. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  25835. if (pbr === void 0) { pbr = false; }
  25836. if (scale === void 0) { scale = 1000; }
  25837. if (blur === void 0) { blur = 0; }
  25838. if (environmentTexture) {
  25839. this.environmentTexture = environmentTexture;
  25840. }
  25841. if (!this.environmentTexture) {
  25842. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  25843. return null;
  25844. }
  25845. // Skybox
  25846. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  25847. if (pbr) {
  25848. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  25849. hdrSkyboxMaterial.backFaceCulling = false;
  25850. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25851. if (hdrSkyboxMaterial.reflectionTexture) {
  25852. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25853. }
  25854. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  25855. hdrSkyboxMaterial.disableLighting = true;
  25856. hdrSkyboxMaterial.twoSidedLighting = true;
  25857. hdrSkybox.infiniteDistance = true;
  25858. hdrSkybox.material = hdrSkyboxMaterial;
  25859. }
  25860. else {
  25861. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  25862. skyboxMaterial.backFaceCulling = false;
  25863. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25864. if (skyboxMaterial.reflectionTexture) {
  25865. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25866. }
  25867. skyboxMaterial.disableLighting = true;
  25868. hdrSkybox.infiniteDistance = true;
  25869. hdrSkybox.material = skyboxMaterial;
  25870. }
  25871. return hdrSkybox;
  25872. };
  25873. Scene.prototype.createDefaultEnvironment = function (options) {
  25874. if (BABYLON.EnvironmentHelper) {
  25875. return new BABYLON.EnvironmentHelper(options, this);
  25876. }
  25877. return null;
  25878. };
  25879. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  25880. if (webVROptions === void 0) { webVROptions = {}; }
  25881. return new BABYLON.VRExperienceHelper(this, webVROptions);
  25882. };
  25883. // Tags
  25884. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  25885. if (tagsQuery === undefined) {
  25886. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  25887. return list;
  25888. }
  25889. var listByTags = [];
  25890. forEach = forEach || (function (item) { return; });
  25891. for (var i in list) {
  25892. var item = list[i];
  25893. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  25894. listByTags.push(item);
  25895. forEach(item);
  25896. }
  25897. }
  25898. return listByTags;
  25899. };
  25900. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  25901. return this._getByTags(this.meshes, tagsQuery, forEach);
  25902. };
  25903. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  25904. return this._getByTags(this.cameras, tagsQuery, forEach);
  25905. };
  25906. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  25907. return this._getByTags(this.lights, tagsQuery, forEach);
  25908. };
  25909. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  25910. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  25911. };
  25912. /**
  25913. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  25914. * This allowed control for front to back rendering or reversly depending of the special needs.
  25915. *
  25916. * @param renderingGroupId The rendering group id corresponding to its index
  25917. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  25918. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  25919. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  25920. */
  25921. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25922. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25923. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25924. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25925. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  25926. };
  25927. /**
  25928. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25929. *
  25930. * @param renderingGroupId The rendering group id corresponding to its index
  25931. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25932. * @param depth Automatically clears depth between groups if true and autoClear is true.
  25933. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  25934. */
  25935. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  25936. if (depth === void 0) { depth = true; }
  25937. if (stencil === void 0) { stencil = true; }
  25938. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  25939. };
  25940. /**
  25941. * Will flag all materials as dirty to trigger new shader compilation
  25942. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  25943. */
  25944. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  25945. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  25946. var material = _a[_i];
  25947. if (predicate && !predicate(material)) {
  25948. continue;
  25949. }
  25950. material.markAsDirty(flag);
  25951. }
  25952. };
  25953. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  25954. var _this = this;
  25955. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  25956. this._activeRequests.push(request);
  25957. request.onCompleteObservable.add(function (request) {
  25958. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  25959. });
  25960. return request;
  25961. };
  25962. /** @ignore */
  25963. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  25964. var _this = this;
  25965. return new Promise(function (resolve, reject) {
  25966. _this._loadFile(url, function (data) {
  25967. resolve(data);
  25968. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  25969. reject(exception);
  25970. });
  25971. });
  25972. };
  25973. // Statics
  25974. Scene._FOGMODE_NONE = 0;
  25975. Scene._FOGMODE_EXP = 1;
  25976. Scene._FOGMODE_EXP2 = 2;
  25977. Scene._FOGMODE_LINEAR = 3;
  25978. Scene._uniqueIdCounter = 0;
  25979. Scene.MinDeltaTime = 1.0;
  25980. Scene.MaxDeltaTime = 1000.0;
  25981. /** The distance in pixel that you have to move to prevent some events */
  25982. Scene.DragMovementThreshold = 10; // in pixels
  25983. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  25984. Scene.LongPressDelay = 500; // in milliseconds
  25985. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  25986. Scene.DoubleClickDelay = 300; // in milliseconds
  25987. /** If you need to check double click without raising a single click at first click, enable this flag */
  25988. Scene.ExclusiveDoubleClickMode = false;
  25989. return Scene;
  25990. }());
  25991. BABYLON.Scene = Scene;
  25992. })(BABYLON || (BABYLON = {}));
  25993. //# sourceMappingURL=babylon.scene.js.map
  25994. "use strict";
  25995. var BABYLON;
  25996. (function (BABYLON) {
  25997. /**
  25998. * Set of assets to keep when moving a scene into an asset container.
  25999. */
  26000. var KeepAssets = /** @class */ (function () {
  26001. function KeepAssets() {
  26002. /**
  26003. * Cameras to keep.
  26004. */
  26005. this.cameras = new Array();
  26006. /**
  26007. * Lights to keep.
  26008. */
  26009. this.lights = new Array();
  26010. /**
  26011. * Meshes to keep.
  26012. */
  26013. this.meshes = new Array();
  26014. /**
  26015. * Skeletons to keep.
  26016. */
  26017. this.skeletons = new Array();
  26018. /**
  26019. * ParticleSystems to keep.
  26020. */
  26021. this.particleSystems = new Array();
  26022. /**
  26023. * Animations to keep.
  26024. */
  26025. this.animations = new Array();
  26026. /**
  26027. * AnimationGroups to keep.
  26028. */
  26029. this.animationGroups = new Array();
  26030. /**
  26031. * MultiMaterials to keep.
  26032. */
  26033. this.multiMaterials = new Array();
  26034. /**
  26035. * Materials to keep.
  26036. */
  26037. this.materials = new Array();
  26038. /**
  26039. * MorphTargetManagers to keep.
  26040. */
  26041. this.morphTargetManagers = new Array();
  26042. /**
  26043. * Geometries to keep.
  26044. */
  26045. this.geometries = new Array();
  26046. /**
  26047. * TransformNodes to keep.
  26048. */
  26049. this.transformNodes = new Array();
  26050. /**
  26051. * LensFlareSystems to keep.
  26052. */
  26053. this.lensFlareSystems = new Array();
  26054. /**
  26055. * ShadowGenerators to keep.
  26056. */
  26057. this.shadowGenerators = new Array();
  26058. /**
  26059. * ActionManagers to keep.
  26060. */
  26061. this.actionManagers = new Array();
  26062. /**
  26063. * Sounds to keep.
  26064. */
  26065. this.sounds = new Array();
  26066. /**
  26067. * Textures to keep.
  26068. */
  26069. this.textures = new Array();
  26070. }
  26071. return KeepAssets;
  26072. }());
  26073. BABYLON.KeepAssets = KeepAssets;
  26074. /**
  26075. * Container with a set of assets that can be added or removed from a scene.
  26076. */
  26077. var AssetContainer = /** @class */ (function () {
  26078. /**
  26079. * Instantiates an AssetContainer.
  26080. * @param scene The scene the AssetContainer belongs to.
  26081. */
  26082. function AssetContainer(scene) {
  26083. // Objects
  26084. /**
  26085. * Cameras populated in the container.
  26086. */
  26087. this.cameras = new Array();
  26088. /**
  26089. * Lights populated in the container.
  26090. */
  26091. this.lights = new Array();
  26092. /**
  26093. * Meshes populated in the container.
  26094. */
  26095. this.meshes = new Array();
  26096. /**
  26097. * Skeletons populated in the container.
  26098. */
  26099. this.skeletons = new Array();
  26100. /**
  26101. * ParticleSystems populated in the container.
  26102. */
  26103. this.particleSystems = new Array();
  26104. /**
  26105. * Animations populated in the container.
  26106. */
  26107. this.animations = new Array();
  26108. /**
  26109. * AnimationGroups populated in the container.
  26110. */
  26111. this.animationGroups = new Array();
  26112. /**
  26113. * MultiMaterials populated in the container.
  26114. */
  26115. this.multiMaterials = new Array();
  26116. /**
  26117. * Materials populated in the container.
  26118. */
  26119. this.materials = new Array();
  26120. /**
  26121. * MorphTargetManagers populated in the container.
  26122. */
  26123. this.morphTargetManagers = new Array();
  26124. /**
  26125. * Geometries populated in the container.
  26126. */
  26127. this.geometries = new Array();
  26128. /**
  26129. * TransformNodes populated in the container.
  26130. */
  26131. this.transformNodes = new Array();
  26132. /**
  26133. * LensFlareSystems populated in the container.
  26134. */
  26135. this.lensFlareSystems = new Array();
  26136. /**
  26137. * ShadowGenerators populated in the container.
  26138. */
  26139. this.shadowGenerators = new Array();
  26140. /**
  26141. * ActionManagers populated in the container.
  26142. */
  26143. this.actionManagers = new Array();
  26144. /**
  26145. * Sounds populated in the container.
  26146. */
  26147. this.sounds = new Array();
  26148. /**
  26149. * Textures populated in the container.
  26150. */
  26151. this.textures = new Array();
  26152. this.scene = scene;
  26153. }
  26154. /**
  26155. * Adds all the assets from the container to the scene.
  26156. */
  26157. AssetContainer.prototype.addAllToScene = function () {
  26158. var _this = this;
  26159. this.cameras.forEach(function (o) {
  26160. _this.scene.addCamera(o);
  26161. });
  26162. this.lights.forEach(function (o) {
  26163. _this.scene.addLight(o);
  26164. });
  26165. this.meshes.forEach(function (o) {
  26166. _this.scene.addMesh(o);
  26167. });
  26168. this.skeletons.forEach(function (o) {
  26169. _this.scene.addSkeleton(o);
  26170. });
  26171. this.particleSystems.forEach(function (o) {
  26172. _this.scene.addParticleSystem(o);
  26173. });
  26174. this.animations.forEach(function (o) {
  26175. _this.scene.addAnimation(o);
  26176. });
  26177. this.animationGroups.forEach(function (o) {
  26178. _this.scene.addAnimationGroup(o);
  26179. });
  26180. this.multiMaterials.forEach(function (o) {
  26181. _this.scene.addMultiMaterial(o);
  26182. });
  26183. this.materials.forEach(function (o) {
  26184. _this.scene.addMaterial(o);
  26185. });
  26186. this.morphTargetManagers.forEach(function (o) {
  26187. _this.scene.addMorphTargetManager(o);
  26188. });
  26189. this.geometries.forEach(function (o) {
  26190. _this.scene.addGeometry(o);
  26191. });
  26192. this.transformNodes.forEach(function (o) {
  26193. _this.scene.addTransformNode(o);
  26194. });
  26195. this.lensFlareSystems.forEach(function (o) {
  26196. _this.scene.addLensFlareSystem(o);
  26197. });
  26198. this.actionManagers.forEach(function (o) {
  26199. _this.scene.addActionManager(o);
  26200. });
  26201. this.sounds.forEach(function (o) {
  26202. o.play();
  26203. o.autoplay = true;
  26204. _this.scene.mainSoundTrack.AddSound(o);
  26205. });
  26206. this.textures.forEach(function (o) {
  26207. _this.scene.addTexture;
  26208. });
  26209. };
  26210. /**
  26211. * Removes all the assets in the container from the scene
  26212. */
  26213. AssetContainer.prototype.removeAllFromScene = function () {
  26214. var _this = this;
  26215. this.cameras.forEach(function (o) {
  26216. _this.scene.removeCamera(o);
  26217. });
  26218. this.lights.forEach(function (o) {
  26219. _this.scene.removeLight(o);
  26220. });
  26221. this.meshes.forEach(function (o) {
  26222. _this.scene.removeMesh(o);
  26223. });
  26224. this.skeletons.forEach(function (o) {
  26225. _this.scene.removeSkeleton(o);
  26226. });
  26227. this.particleSystems.forEach(function (o) {
  26228. _this.scene.removeParticleSystem(o);
  26229. });
  26230. this.animations.forEach(function (o) {
  26231. _this.scene.removeAnimation(o);
  26232. });
  26233. this.animationGroups.forEach(function (o) {
  26234. _this.scene.removeAnimationGroup(o);
  26235. });
  26236. this.multiMaterials.forEach(function (o) {
  26237. _this.scene.removeMultiMaterial(o);
  26238. });
  26239. this.materials.forEach(function (o) {
  26240. _this.scene.removeMaterial(o);
  26241. });
  26242. this.morphTargetManagers.forEach(function (o) {
  26243. _this.scene.removeMorphTargetManager(o);
  26244. });
  26245. this.geometries.forEach(function (o) {
  26246. _this.scene.removeGeometry(o);
  26247. });
  26248. this.transformNodes.forEach(function (o) {
  26249. _this.scene.removeTransformNode(o);
  26250. });
  26251. this.lensFlareSystems.forEach(function (o) {
  26252. _this.scene.removeLensFlareSystem(o);
  26253. });
  26254. this.actionManagers.forEach(function (o) {
  26255. _this.scene.removeActionManager(o);
  26256. });
  26257. this.sounds.forEach(function (o) {
  26258. o.stop();
  26259. o.autoplay = false;
  26260. _this.scene.mainSoundTrack.RemoveSound(o);
  26261. });
  26262. this.textures.forEach(function (o) {
  26263. _this.scene.removeTexture(o);
  26264. });
  26265. };
  26266. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  26267. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  26268. var asset = sourceAssets_1[_i];
  26269. var move = true;
  26270. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  26271. var keepAsset = keepAssets_1[_a];
  26272. if (asset === keepAsset) {
  26273. move = false;
  26274. break;
  26275. }
  26276. }
  26277. if (move) {
  26278. targetAssets.push(asset);
  26279. }
  26280. }
  26281. };
  26282. /**
  26283. * Removes all the assets contained in the scene and adds them to the container.
  26284. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  26285. */
  26286. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  26287. if (keepAssets === undefined) {
  26288. keepAssets = new KeepAssets();
  26289. }
  26290. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  26291. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  26292. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  26293. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  26294. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  26295. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  26296. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  26297. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  26298. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  26299. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  26300. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  26301. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  26302. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  26303. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  26304. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  26305. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  26306. this.removeAllFromScene();
  26307. };
  26308. return AssetContainer;
  26309. }());
  26310. BABYLON.AssetContainer = AssetContainer;
  26311. })(BABYLON || (BABYLON = {}));
  26312. //# sourceMappingURL=babylon.assetContainer.js.map
  26313. "use strict";
  26314. var BABYLON;
  26315. (function (BABYLON) {
  26316. var Buffer = /** @class */ (function () {
  26317. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  26318. if (instanced === void 0) { instanced = false; }
  26319. if (engine instanceof BABYLON.Mesh) {
  26320. this._engine = engine.getScene().getEngine();
  26321. }
  26322. else {
  26323. this._engine = engine;
  26324. }
  26325. this._updatable = updatable;
  26326. this._instanced = instanced;
  26327. this._data = data;
  26328. this._strideSize = stride;
  26329. if (!postponeInternalCreation) {
  26330. this.create();
  26331. }
  26332. }
  26333. /**
  26334. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  26335. * @param kind defines the vertex buffer kind (position, normal, etc.)
  26336. * @param offset defines offset in the buffer (0 by default)
  26337. * @param size defines the size in floats of attributes (position is 3 for instance)
  26338. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  26339. * @param instanced defines if the vertex buffer contains indexed data
  26340. * @returns the new vertex buffer
  26341. */
  26342. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  26343. // a lot of these parameters are ignored as they are overriden by the buffer
  26344. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  26345. };
  26346. // Properties
  26347. Buffer.prototype.isUpdatable = function () {
  26348. return this._updatable;
  26349. };
  26350. Buffer.prototype.getData = function () {
  26351. return this._data;
  26352. };
  26353. Buffer.prototype.getBuffer = function () {
  26354. return this._buffer;
  26355. };
  26356. Buffer.prototype.getStrideSize = function () {
  26357. return this._strideSize;
  26358. };
  26359. // public getIsInstanced(): boolean {
  26360. // return this._instanced;
  26361. // }
  26362. // public get instanceDivisor(): number {
  26363. // return this._instanceDivisor;
  26364. // }
  26365. // public set instanceDivisor(value: number) {
  26366. // this._instanceDivisor = value;
  26367. // if (value == 0) {
  26368. // this._instanced = false;
  26369. // } else {
  26370. // this._instanced = true;
  26371. // }
  26372. // }
  26373. // Methods
  26374. Buffer.prototype.create = function (data) {
  26375. if (data === void 0) { data = null; }
  26376. if (!data && this._buffer) {
  26377. return; // nothing to do
  26378. }
  26379. data = data || this._data;
  26380. if (!data) {
  26381. return;
  26382. }
  26383. if (!this._buffer) {
  26384. if (this._updatable) {
  26385. this._buffer = this._engine.createDynamicVertexBuffer(data);
  26386. this._data = data;
  26387. }
  26388. else {
  26389. this._buffer = this._engine.createVertexBuffer(data);
  26390. }
  26391. }
  26392. else if (this._updatable) {
  26393. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  26394. this._data = data;
  26395. }
  26396. };
  26397. Buffer.prototype._rebuild = function () {
  26398. this._buffer = null;
  26399. this.create(this._data);
  26400. };
  26401. Buffer.prototype.update = function (data) {
  26402. this.create(data);
  26403. };
  26404. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  26405. if (!this._buffer) {
  26406. return;
  26407. }
  26408. if (this._updatable) {
  26409. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  26410. this._data = null;
  26411. }
  26412. };
  26413. Buffer.prototype.dispose = function () {
  26414. if (!this._buffer) {
  26415. return;
  26416. }
  26417. if (this._engine._releaseBuffer(this._buffer)) {
  26418. this._buffer = null;
  26419. }
  26420. };
  26421. return Buffer;
  26422. }());
  26423. BABYLON.Buffer = Buffer;
  26424. })(BABYLON || (BABYLON = {}));
  26425. //# sourceMappingURL=babylon.buffer.js.map
  26426. "use strict";
  26427. var BABYLON;
  26428. (function (BABYLON) {
  26429. var VertexBuffer = /** @class */ (function () {
  26430. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  26431. if (data instanceof BABYLON.Buffer) {
  26432. if (!stride) {
  26433. stride = data.getStrideSize();
  26434. }
  26435. this._buffer = data;
  26436. this._ownsBuffer = false;
  26437. }
  26438. else {
  26439. if (!stride) {
  26440. stride = VertexBuffer.DeduceStride(kind);
  26441. }
  26442. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  26443. this._ownsBuffer = true;
  26444. }
  26445. this._stride = stride;
  26446. this._instanced = instanced !== undefined ? instanced : false;
  26447. this._instanceDivisor = instanced ? 1 : 0;
  26448. this._offset = offset ? offset : 0;
  26449. this._size = size ? size : stride;
  26450. this._kind = kind;
  26451. }
  26452. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  26453. /**
  26454. * Gets or sets the instance divisor when in instanced mode
  26455. */
  26456. get: function () {
  26457. return this._instanceDivisor;
  26458. },
  26459. set: function (value) {
  26460. this._instanceDivisor = value;
  26461. if (value == 0) {
  26462. this._instanced = false;
  26463. }
  26464. else {
  26465. this._instanced = true;
  26466. }
  26467. },
  26468. enumerable: true,
  26469. configurable: true
  26470. });
  26471. VertexBuffer.prototype._rebuild = function () {
  26472. if (!this._buffer) {
  26473. return;
  26474. }
  26475. this._buffer._rebuild();
  26476. };
  26477. /**
  26478. * Returns the kind of the VertexBuffer (string).
  26479. */
  26480. VertexBuffer.prototype.getKind = function () {
  26481. return this._kind;
  26482. };
  26483. // Properties
  26484. /**
  26485. * Boolean : is the VertexBuffer updatable ?
  26486. */
  26487. VertexBuffer.prototype.isUpdatable = function () {
  26488. return this._buffer.isUpdatable();
  26489. };
  26490. /**
  26491. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  26492. */
  26493. VertexBuffer.prototype.getData = function () {
  26494. return this._buffer.getData();
  26495. };
  26496. /**
  26497. * Returns the WebGLBuffer associated to the VertexBuffer.
  26498. */
  26499. VertexBuffer.prototype.getBuffer = function () {
  26500. return this._buffer.getBuffer();
  26501. };
  26502. /**
  26503. * Returns the stride of the VertexBuffer (integer).
  26504. */
  26505. VertexBuffer.prototype.getStrideSize = function () {
  26506. return this._stride;
  26507. };
  26508. /**
  26509. * Returns the offset (integer).
  26510. */
  26511. VertexBuffer.prototype.getOffset = function () {
  26512. return this._offset;
  26513. };
  26514. /**
  26515. * Returns the VertexBuffer total size (integer).
  26516. */
  26517. VertexBuffer.prototype.getSize = function () {
  26518. return this._size;
  26519. };
  26520. /**
  26521. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  26522. */
  26523. VertexBuffer.prototype.getIsInstanced = function () {
  26524. return this._instanced;
  26525. };
  26526. /**
  26527. * Returns the instancing divisor, zero for non-instanced (integer).
  26528. */
  26529. VertexBuffer.prototype.getInstanceDivisor = function () {
  26530. return this._instanceDivisor;
  26531. };
  26532. // Methods
  26533. /**
  26534. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  26535. * Returns the created WebGLBuffer.
  26536. */
  26537. VertexBuffer.prototype.create = function (data) {
  26538. return this._buffer.create(data);
  26539. };
  26540. /**
  26541. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26542. * This function will create a new buffer if the current one is not updatable
  26543. * Returns the updated WebGLBuffer.
  26544. */
  26545. VertexBuffer.prototype.update = function (data) {
  26546. return this._buffer.update(data);
  26547. };
  26548. /**
  26549. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26550. * Returns the directly updated WebGLBuffer.
  26551. */
  26552. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  26553. return this._buffer.updateDirectly(data, offset);
  26554. };
  26555. /**
  26556. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  26557. */
  26558. VertexBuffer.prototype.dispose = function () {
  26559. if (this._ownsBuffer) {
  26560. this._buffer.dispose();
  26561. }
  26562. };
  26563. Object.defineProperty(VertexBuffer, "PositionKind", {
  26564. get: function () {
  26565. return VertexBuffer._PositionKind;
  26566. },
  26567. enumerable: true,
  26568. configurable: true
  26569. });
  26570. Object.defineProperty(VertexBuffer, "NormalKind", {
  26571. get: function () {
  26572. return VertexBuffer._NormalKind;
  26573. },
  26574. enumerable: true,
  26575. configurable: true
  26576. });
  26577. Object.defineProperty(VertexBuffer, "TangentKind", {
  26578. get: function () {
  26579. return VertexBuffer._TangentKind;
  26580. },
  26581. enumerable: true,
  26582. configurable: true
  26583. });
  26584. Object.defineProperty(VertexBuffer, "UVKind", {
  26585. get: function () {
  26586. return VertexBuffer._UVKind;
  26587. },
  26588. enumerable: true,
  26589. configurable: true
  26590. });
  26591. Object.defineProperty(VertexBuffer, "UV2Kind", {
  26592. get: function () {
  26593. return VertexBuffer._UV2Kind;
  26594. },
  26595. enumerable: true,
  26596. configurable: true
  26597. });
  26598. Object.defineProperty(VertexBuffer, "UV3Kind", {
  26599. get: function () {
  26600. return VertexBuffer._UV3Kind;
  26601. },
  26602. enumerable: true,
  26603. configurable: true
  26604. });
  26605. Object.defineProperty(VertexBuffer, "UV4Kind", {
  26606. get: function () {
  26607. return VertexBuffer._UV4Kind;
  26608. },
  26609. enumerable: true,
  26610. configurable: true
  26611. });
  26612. Object.defineProperty(VertexBuffer, "UV5Kind", {
  26613. get: function () {
  26614. return VertexBuffer._UV5Kind;
  26615. },
  26616. enumerable: true,
  26617. configurable: true
  26618. });
  26619. Object.defineProperty(VertexBuffer, "UV6Kind", {
  26620. get: function () {
  26621. return VertexBuffer._UV6Kind;
  26622. },
  26623. enumerable: true,
  26624. configurable: true
  26625. });
  26626. Object.defineProperty(VertexBuffer, "ColorKind", {
  26627. get: function () {
  26628. return VertexBuffer._ColorKind;
  26629. },
  26630. enumerable: true,
  26631. configurable: true
  26632. });
  26633. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  26634. get: function () {
  26635. return VertexBuffer._MatricesIndicesKind;
  26636. },
  26637. enumerable: true,
  26638. configurable: true
  26639. });
  26640. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  26641. get: function () {
  26642. return VertexBuffer._MatricesWeightsKind;
  26643. },
  26644. enumerable: true,
  26645. configurable: true
  26646. });
  26647. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  26648. get: function () {
  26649. return VertexBuffer._MatricesIndicesExtraKind;
  26650. },
  26651. enumerable: true,
  26652. configurable: true
  26653. });
  26654. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  26655. get: function () {
  26656. return VertexBuffer._MatricesWeightsExtraKind;
  26657. },
  26658. enumerable: true,
  26659. configurable: true
  26660. });
  26661. /**
  26662. * Deduces the stride given a kind.
  26663. * @param kind The kind string to deduce
  26664. * @returns The deduced stride
  26665. */
  26666. VertexBuffer.DeduceStride = function (kind) {
  26667. switch (kind) {
  26668. case VertexBuffer.UVKind:
  26669. case VertexBuffer.UV2Kind:
  26670. case VertexBuffer.UV3Kind:
  26671. case VertexBuffer.UV4Kind:
  26672. case VertexBuffer.UV5Kind:
  26673. case VertexBuffer.UV6Kind:
  26674. return 2;
  26675. case VertexBuffer.NormalKind:
  26676. case VertexBuffer.PositionKind:
  26677. return 3;
  26678. case VertexBuffer.ColorKind:
  26679. case VertexBuffer.MatricesIndicesKind:
  26680. case VertexBuffer.MatricesIndicesExtraKind:
  26681. case VertexBuffer.MatricesWeightsKind:
  26682. case VertexBuffer.MatricesWeightsExtraKind:
  26683. case VertexBuffer.TangentKind:
  26684. return 4;
  26685. default:
  26686. throw new Error("Invalid kind '" + kind + "'");
  26687. }
  26688. };
  26689. // Enums
  26690. VertexBuffer._PositionKind = "position";
  26691. VertexBuffer._NormalKind = "normal";
  26692. VertexBuffer._TangentKind = "tangent";
  26693. VertexBuffer._UVKind = "uv";
  26694. VertexBuffer._UV2Kind = "uv2";
  26695. VertexBuffer._UV3Kind = "uv3";
  26696. VertexBuffer._UV4Kind = "uv4";
  26697. VertexBuffer._UV5Kind = "uv5";
  26698. VertexBuffer._UV6Kind = "uv6";
  26699. VertexBuffer._ColorKind = "color";
  26700. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  26701. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  26702. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  26703. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  26704. return VertexBuffer;
  26705. }());
  26706. BABYLON.VertexBuffer = VertexBuffer;
  26707. })(BABYLON || (BABYLON = {}));
  26708. //# sourceMappingURL=babylon.vertexBuffer.js.map
  26709. "use strict";
  26710. var BABYLON;
  26711. (function (BABYLON) {
  26712. /**
  26713. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  26714. */
  26715. var DummyInternalTextureTracker = /** @class */ (function () {
  26716. function DummyInternalTextureTracker() {
  26717. /**
  26718. * Gets or set the previous tracker in the list
  26719. */
  26720. this.previous = null;
  26721. /**
  26722. * Gets or set the next tracker in the list
  26723. */
  26724. this.next = null;
  26725. }
  26726. return DummyInternalTextureTracker;
  26727. }());
  26728. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  26729. })(BABYLON || (BABYLON = {}));
  26730. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  26731. "use strict";
  26732. var BABYLON;
  26733. (function (BABYLON) {
  26734. /**
  26735. * Class used to store data associated with WebGL texture data for the engine
  26736. * This class should not be used directly
  26737. */
  26738. var InternalTexture = /** @class */ (function () {
  26739. /**
  26740. * Creates a new InternalTexture
  26741. * @param engine defines the engine to use
  26742. * @param dataSource defines the type of data that will be used
  26743. */
  26744. function InternalTexture(engine, dataSource) {
  26745. /**
  26746. * Observable called when the texture is loaded
  26747. */
  26748. this.onLoadedObservable = new BABYLON.Observable();
  26749. /**
  26750. * Gets or set the previous tracker in the list
  26751. */
  26752. this.previous = null;
  26753. /**
  26754. * Gets or set the next tracker in the list
  26755. */
  26756. this.next = null;
  26757. // Private
  26758. /** @ignore */
  26759. this._initialSlot = -1;
  26760. /** @ignore */
  26761. this._designatedSlot = -1;
  26762. /** @ignore */
  26763. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  26764. /** @ignore */
  26765. this._comparisonFunction = 0;
  26766. /** @ignore */
  26767. this._references = 1;
  26768. this._engine = engine;
  26769. this._dataSource = dataSource;
  26770. this._webGLTexture = engine._createTexture();
  26771. }
  26772. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  26773. /**
  26774. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  26775. */
  26776. get: function () {
  26777. return this._dataSource;
  26778. },
  26779. enumerable: true,
  26780. configurable: true
  26781. });
  26782. /**
  26783. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  26784. */
  26785. InternalTexture.prototype.incrementReferences = function () {
  26786. this._references++;
  26787. };
  26788. /**
  26789. * Change the size of the texture (not the size of the content)
  26790. * @param width defines the new width
  26791. * @param height defines the new height
  26792. * @param depth defines the new depth (1 by default)
  26793. */
  26794. InternalTexture.prototype.updateSize = function (width, height, depth) {
  26795. if (depth === void 0) { depth = 1; }
  26796. this.width = width;
  26797. this.height = height;
  26798. this.depth = depth;
  26799. this.baseWidth = width;
  26800. this.baseHeight = height;
  26801. this.baseDepth = depth;
  26802. this._size = width * height * depth;
  26803. };
  26804. /** @ignore */
  26805. InternalTexture.prototype._rebuild = function () {
  26806. var _this = this;
  26807. var proxy;
  26808. this.isReady = false;
  26809. this._cachedCoordinatesMode = null;
  26810. this._cachedWrapU = null;
  26811. this._cachedWrapV = null;
  26812. this._cachedAnisotropicFilteringLevel = null;
  26813. switch (this._dataSource) {
  26814. case InternalTexture.DATASOURCE_TEMP:
  26815. return;
  26816. case InternalTexture.DATASOURCE_URL:
  26817. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  26818. _this.isReady = true;
  26819. }, null, this._buffer, undefined, this.format);
  26820. proxy._swapAndDie(this);
  26821. return;
  26822. case InternalTexture.DATASOURCE_RAW:
  26823. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26824. proxy._swapAndDie(this);
  26825. this.isReady = true;
  26826. return;
  26827. case InternalTexture.DATASOURCE_RAW3D:
  26828. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26829. proxy._swapAndDie(this);
  26830. this.isReady = true;
  26831. return;
  26832. case InternalTexture.DATASOURCE_DYNAMIC:
  26833. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  26834. proxy._swapAndDie(this);
  26835. // The engine will make sure to update content so no need to flag it as isReady = true
  26836. return;
  26837. case InternalTexture.DATASOURCE_RENDERTARGET:
  26838. var options = new BABYLON.RenderTargetCreationOptions();
  26839. options.generateDepthBuffer = this._generateDepthBuffer;
  26840. options.generateMipMaps = this.generateMipMaps;
  26841. options.generateStencilBuffer = this._generateStencilBuffer;
  26842. options.samplingMode = this.samplingMode;
  26843. options.type = this.type;
  26844. if (this.isCube) {
  26845. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  26846. }
  26847. else {
  26848. var size = {
  26849. width: this.width,
  26850. height: this.height
  26851. };
  26852. proxy = this._engine.createRenderTargetTexture(size, options);
  26853. }
  26854. proxy._swapAndDie(this);
  26855. this.isReady = true;
  26856. return;
  26857. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  26858. var depthTextureOptions = {
  26859. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  26860. comparisonFunction: this._comparisonFunction,
  26861. generateStencil: this._generateStencilBuffer,
  26862. isCube: this.isCube
  26863. };
  26864. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  26865. proxy._swapAndDie(this);
  26866. this.isReady = true;
  26867. return;
  26868. case InternalTexture.DATASOURCE_CUBE:
  26869. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  26870. _this.isReady = true;
  26871. }, null, this.format, this._extension);
  26872. proxy._swapAndDie(this);
  26873. return;
  26874. case InternalTexture.DATASOURCE_CUBERAW:
  26875. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26876. proxy._swapAndDie(this);
  26877. this.isReady = true;
  26878. return;
  26879. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  26880. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  26881. if (proxy) {
  26882. proxy._swapAndDie(_this);
  26883. }
  26884. _this.isReady = true;
  26885. }, null, this.format, this._extension);
  26886. return;
  26887. }
  26888. };
  26889. InternalTexture.prototype._swapAndDie = function (target) {
  26890. target._webGLTexture = this._webGLTexture;
  26891. if (this._framebuffer) {
  26892. target._framebuffer = this._framebuffer;
  26893. }
  26894. if (this._depthStencilBuffer) {
  26895. target._depthStencilBuffer = this._depthStencilBuffer;
  26896. }
  26897. if (this._lodTextureHigh) {
  26898. if (target._lodTextureHigh) {
  26899. target._lodTextureHigh.dispose();
  26900. }
  26901. target._lodTextureHigh = this._lodTextureHigh;
  26902. }
  26903. if (this._lodTextureMid) {
  26904. if (target._lodTextureMid) {
  26905. target._lodTextureMid.dispose();
  26906. }
  26907. target._lodTextureMid = this._lodTextureMid;
  26908. }
  26909. if (this._lodTextureLow) {
  26910. if (target._lodTextureLow) {
  26911. target._lodTextureLow.dispose();
  26912. }
  26913. target._lodTextureLow = this._lodTextureLow;
  26914. }
  26915. var cache = this._engine.getLoadedTexturesCache();
  26916. var index = cache.indexOf(this);
  26917. if (index !== -1) {
  26918. cache.splice(index, 1);
  26919. }
  26920. };
  26921. /**
  26922. * Dispose the current allocated resources
  26923. */
  26924. InternalTexture.prototype.dispose = function () {
  26925. if (!this._webGLTexture) {
  26926. return;
  26927. }
  26928. this._references--;
  26929. if (this._references === 0) {
  26930. this._engine._releaseTexture(this);
  26931. this._webGLTexture = null;
  26932. this.previous = null;
  26933. this.next = null;
  26934. }
  26935. };
  26936. /**
  26937. * The source of the texture data is unknown
  26938. */
  26939. InternalTexture.DATASOURCE_UNKNOWN = 0;
  26940. /**
  26941. * Texture data comes from an URL
  26942. */
  26943. InternalTexture.DATASOURCE_URL = 1;
  26944. /**
  26945. * Texture data is only used for temporary storage
  26946. */
  26947. InternalTexture.DATASOURCE_TEMP = 2;
  26948. /**
  26949. * Texture data comes from raw data (ArrayBuffer)
  26950. */
  26951. InternalTexture.DATASOURCE_RAW = 3;
  26952. /**
  26953. * Texture content is dynamic (video or dynamic texture)
  26954. */
  26955. InternalTexture.DATASOURCE_DYNAMIC = 4;
  26956. /**
  26957. * Texture content is generated by rendering to it
  26958. */
  26959. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  26960. /**
  26961. * Texture content is part of a multi render target process
  26962. */
  26963. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  26964. /**
  26965. * Texture data comes from a cube data file
  26966. */
  26967. InternalTexture.DATASOURCE_CUBE = 7;
  26968. /**
  26969. * Texture data comes from a raw cube data
  26970. */
  26971. InternalTexture.DATASOURCE_CUBERAW = 8;
  26972. /**
  26973. * Texture data come from a prefiltered cube data file
  26974. */
  26975. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  26976. /**
  26977. * Texture content is raw 3D data
  26978. */
  26979. InternalTexture.DATASOURCE_RAW3D = 10;
  26980. /**
  26981. * Texture content is a depth texture
  26982. */
  26983. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  26984. return InternalTexture;
  26985. }());
  26986. BABYLON.InternalTexture = InternalTexture;
  26987. })(BABYLON || (BABYLON = {}));
  26988. //# sourceMappingURL=babylon.internalTexture.js.map
  26989. "use strict";
  26990. var BABYLON;
  26991. (function (BABYLON) {
  26992. var BaseTexture = /** @class */ (function () {
  26993. function BaseTexture(scene) {
  26994. this._hasAlpha = false;
  26995. this.getAlphaFromRGB = false;
  26996. this.level = 1;
  26997. this.coordinatesIndex = 0;
  26998. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26999. /**
  27000. * | Value | Type | Description |
  27001. * | ----- | ------------------ | ----------- |
  27002. * | 0 | CLAMP_ADDRESSMODE | |
  27003. * | 1 | WRAP_ADDRESSMODE | |
  27004. * | 2 | MIRROR_ADDRESSMODE | |
  27005. */
  27006. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  27007. /**
  27008. * | Value | Type | Description |
  27009. * | ----- | ------------------ | ----------- |
  27010. * | 0 | CLAMP_ADDRESSMODE | |
  27011. * | 1 | WRAP_ADDRESSMODE | |
  27012. * | 2 | MIRROR_ADDRESSMODE | |
  27013. */
  27014. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  27015. /**
  27016. * | Value | Type | Description |
  27017. * | ----- | ------------------ | ----------- |
  27018. * | 0 | CLAMP_ADDRESSMODE | |
  27019. * | 1 | WRAP_ADDRESSMODE | |
  27020. * | 2 | MIRROR_ADDRESSMODE | |
  27021. */
  27022. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  27023. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  27024. this.isCube = false;
  27025. this.is3D = false;
  27026. this.gammaSpace = true;
  27027. this.invertZ = false;
  27028. this.lodLevelInAlpha = false;
  27029. this.lodGenerationOffset = 0.0;
  27030. this.lodGenerationScale = 0.8;
  27031. this.isRenderTarget = false;
  27032. this.animations = new Array();
  27033. /**
  27034. * An event triggered when the texture is disposed.
  27035. */
  27036. this.onDisposeObservable = new BABYLON.Observable();
  27037. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27038. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  27039. if (this._scene) {
  27040. this._scene.textures.push(this);
  27041. }
  27042. this._uid = null;
  27043. }
  27044. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  27045. get: function () {
  27046. return this._hasAlpha;
  27047. },
  27048. set: function (value) {
  27049. if (this._hasAlpha === value) {
  27050. return;
  27051. }
  27052. this._hasAlpha = value;
  27053. if (this._scene) {
  27054. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  27055. }
  27056. },
  27057. enumerable: true,
  27058. configurable: true
  27059. });
  27060. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  27061. get: function () {
  27062. return this._coordinatesMode;
  27063. },
  27064. /**
  27065. * How a texture is mapped.
  27066. *
  27067. * | Value | Type | Description |
  27068. * | ----- | ----------------------------------- | ----------- |
  27069. * | 0 | EXPLICIT_MODE | |
  27070. * | 1 | SPHERICAL_MODE | |
  27071. * | 2 | PLANAR_MODE | |
  27072. * | 3 | CUBIC_MODE | |
  27073. * | 4 | PROJECTION_MODE | |
  27074. * | 5 | SKYBOX_MODE | |
  27075. * | 6 | INVCUBIC_MODE | |
  27076. * | 7 | EQUIRECTANGULAR_MODE | |
  27077. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  27078. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  27079. */
  27080. set: function (value) {
  27081. if (this._coordinatesMode === value) {
  27082. return;
  27083. }
  27084. this._coordinatesMode = value;
  27085. if (this._scene) {
  27086. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27087. }
  27088. },
  27089. enumerable: true,
  27090. configurable: true
  27091. });
  27092. Object.defineProperty(BaseTexture.prototype, "uid", {
  27093. get: function () {
  27094. if (!this._uid) {
  27095. this._uid = BABYLON.Tools.RandomId();
  27096. }
  27097. return this._uid;
  27098. },
  27099. enumerable: true,
  27100. configurable: true
  27101. });
  27102. BaseTexture.prototype.toString = function () {
  27103. return this.name;
  27104. };
  27105. BaseTexture.prototype.getClassName = function () {
  27106. return "BaseTexture";
  27107. };
  27108. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  27109. set: function (callback) {
  27110. if (this._onDisposeObserver) {
  27111. this.onDisposeObservable.remove(this._onDisposeObserver);
  27112. }
  27113. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27114. },
  27115. enumerable: true,
  27116. configurable: true
  27117. });
  27118. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  27119. get: function () {
  27120. return true;
  27121. },
  27122. enumerable: true,
  27123. configurable: true
  27124. });
  27125. BaseTexture.prototype.getScene = function () {
  27126. return this._scene;
  27127. };
  27128. BaseTexture.prototype.getTextureMatrix = function () {
  27129. return BABYLON.Matrix.IdentityReadOnly;
  27130. };
  27131. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  27132. return BABYLON.Matrix.IdentityReadOnly;
  27133. };
  27134. BaseTexture.prototype.getInternalTexture = function () {
  27135. return this._texture;
  27136. };
  27137. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  27138. return !this.isBlocking || this.isReady();
  27139. };
  27140. BaseTexture.prototype.isReady = function () {
  27141. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27142. this.delayLoad();
  27143. return false;
  27144. }
  27145. if (this._texture) {
  27146. return this._texture.isReady;
  27147. }
  27148. return false;
  27149. };
  27150. BaseTexture.prototype.getSize = function () {
  27151. if (this._texture && this._texture.width) {
  27152. return new BABYLON.Size(this._texture.width, this._texture.height);
  27153. }
  27154. if (this._texture && this._texture._size) {
  27155. return new BABYLON.Size(this._texture._size, this._texture._size);
  27156. }
  27157. return BABYLON.Size.Zero();
  27158. };
  27159. BaseTexture.prototype.getBaseSize = function () {
  27160. if (!this.isReady() || !this._texture)
  27161. return BABYLON.Size.Zero();
  27162. if (this._texture._size) {
  27163. return new BABYLON.Size(this._texture._size, this._texture._size);
  27164. }
  27165. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  27166. };
  27167. BaseTexture.prototype.scale = function (ratio) {
  27168. };
  27169. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  27170. get: function () {
  27171. return false;
  27172. },
  27173. enumerable: true,
  27174. configurable: true
  27175. });
  27176. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  27177. if (!this._scene) {
  27178. return null;
  27179. }
  27180. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  27181. for (var index = 0; index < texturesCache.length; index++) {
  27182. var texturesCacheEntry = texturesCache[index];
  27183. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  27184. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  27185. texturesCacheEntry.incrementReferences();
  27186. return texturesCacheEntry;
  27187. }
  27188. }
  27189. }
  27190. return null;
  27191. };
  27192. BaseTexture.prototype._rebuild = function () {
  27193. };
  27194. BaseTexture.prototype.delayLoad = function () {
  27195. };
  27196. BaseTexture.prototype.clone = function () {
  27197. return null;
  27198. };
  27199. Object.defineProperty(BaseTexture.prototype, "textureType", {
  27200. get: function () {
  27201. if (!this._texture) {
  27202. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  27203. }
  27204. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  27205. },
  27206. enumerable: true,
  27207. configurable: true
  27208. });
  27209. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  27210. get: function () {
  27211. if (!this._texture) {
  27212. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  27213. }
  27214. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  27215. },
  27216. enumerable: true,
  27217. configurable: true
  27218. });
  27219. BaseTexture.prototype.readPixels = function (faceIndex) {
  27220. if (faceIndex === void 0) { faceIndex = 0; }
  27221. if (!this._texture) {
  27222. return null;
  27223. }
  27224. var size = this.getSize();
  27225. var scene = this.getScene();
  27226. if (!scene) {
  27227. return null;
  27228. }
  27229. var engine = scene.getEngine();
  27230. if (this._texture.isCube) {
  27231. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  27232. }
  27233. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  27234. };
  27235. BaseTexture.prototype.releaseInternalTexture = function () {
  27236. if (this._texture) {
  27237. this._texture.dispose();
  27238. this._texture = null;
  27239. }
  27240. };
  27241. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  27242. get: function () {
  27243. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  27244. return null;
  27245. }
  27246. if (!this._texture._sphericalPolynomial) {
  27247. this._texture._sphericalPolynomial =
  27248. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  27249. }
  27250. return this._texture._sphericalPolynomial;
  27251. },
  27252. set: function (value) {
  27253. if (this._texture) {
  27254. this._texture._sphericalPolynomial = value;
  27255. }
  27256. },
  27257. enumerable: true,
  27258. configurable: true
  27259. });
  27260. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  27261. get: function () {
  27262. if (this._texture) {
  27263. return this._texture._lodTextureHigh;
  27264. }
  27265. return null;
  27266. },
  27267. enumerable: true,
  27268. configurable: true
  27269. });
  27270. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  27271. get: function () {
  27272. if (this._texture) {
  27273. return this._texture._lodTextureMid;
  27274. }
  27275. return null;
  27276. },
  27277. enumerable: true,
  27278. configurable: true
  27279. });
  27280. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  27281. get: function () {
  27282. if (this._texture) {
  27283. return this._texture._lodTextureLow;
  27284. }
  27285. return null;
  27286. },
  27287. enumerable: true,
  27288. configurable: true
  27289. });
  27290. BaseTexture.prototype.dispose = function () {
  27291. if (!this._scene) {
  27292. return;
  27293. }
  27294. // Animations
  27295. this._scene.stopAnimation(this);
  27296. // Remove from scene
  27297. this._scene._removePendingData(this);
  27298. var index = this._scene.textures.indexOf(this);
  27299. if (index >= 0) {
  27300. this._scene.textures.splice(index, 1);
  27301. }
  27302. if (this._texture === undefined) {
  27303. return;
  27304. }
  27305. // Release
  27306. this.releaseInternalTexture();
  27307. // Callback
  27308. this.onDisposeObservable.notifyObservers(this);
  27309. this.onDisposeObservable.clear();
  27310. };
  27311. BaseTexture.prototype.serialize = function () {
  27312. if (!this.name) {
  27313. return null;
  27314. }
  27315. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  27316. // Animations
  27317. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27318. return serializationObject;
  27319. };
  27320. BaseTexture.WhenAllReady = function (textures, callback) {
  27321. var numRemaining = textures.length;
  27322. if (numRemaining === 0) {
  27323. callback();
  27324. return;
  27325. }
  27326. var _loop_1 = function () {
  27327. texture = textures[i];
  27328. if (texture.isReady()) {
  27329. if (--numRemaining === 0) {
  27330. callback();
  27331. }
  27332. }
  27333. else {
  27334. onLoadObservable = texture.onLoadObservable;
  27335. var onLoadCallback_1 = function () {
  27336. onLoadObservable.removeCallback(onLoadCallback_1);
  27337. if (--numRemaining === 0) {
  27338. callback();
  27339. }
  27340. };
  27341. onLoadObservable.add(onLoadCallback_1);
  27342. }
  27343. };
  27344. var texture, onLoadObservable;
  27345. for (var i = 0; i < textures.length; i++) {
  27346. _loop_1();
  27347. }
  27348. };
  27349. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  27350. __decorate([
  27351. BABYLON.serialize()
  27352. ], BaseTexture.prototype, "name", void 0);
  27353. __decorate([
  27354. BABYLON.serialize("hasAlpha")
  27355. ], BaseTexture.prototype, "_hasAlpha", void 0);
  27356. __decorate([
  27357. BABYLON.serialize()
  27358. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  27359. __decorate([
  27360. BABYLON.serialize()
  27361. ], BaseTexture.prototype, "level", void 0);
  27362. __decorate([
  27363. BABYLON.serialize()
  27364. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  27365. __decorate([
  27366. BABYLON.serialize("coordinatesMode")
  27367. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  27368. __decorate([
  27369. BABYLON.serialize()
  27370. ], BaseTexture.prototype, "wrapU", void 0);
  27371. __decorate([
  27372. BABYLON.serialize()
  27373. ], BaseTexture.prototype, "wrapV", void 0);
  27374. __decorate([
  27375. BABYLON.serialize()
  27376. ], BaseTexture.prototype, "wrapR", void 0);
  27377. __decorate([
  27378. BABYLON.serialize()
  27379. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  27380. __decorate([
  27381. BABYLON.serialize()
  27382. ], BaseTexture.prototype, "isCube", void 0);
  27383. __decorate([
  27384. BABYLON.serialize()
  27385. ], BaseTexture.prototype, "is3D", void 0);
  27386. __decorate([
  27387. BABYLON.serialize()
  27388. ], BaseTexture.prototype, "gammaSpace", void 0);
  27389. __decorate([
  27390. BABYLON.serialize()
  27391. ], BaseTexture.prototype, "invertZ", void 0);
  27392. __decorate([
  27393. BABYLON.serialize()
  27394. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  27395. __decorate([
  27396. BABYLON.serialize()
  27397. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  27398. __decorate([
  27399. BABYLON.serialize()
  27400. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  27401. __decorate([
  27402. BABYLON.serialize()
  27403. ], BaseTexture.prototype, "isRenderTarget", void 0);
  27404. return BaseTexture;
  27405. }());
  27406. BABYLON.BaseTexture = BaseTexture;
  27407. })(BABYLON || (BABYLON = {}));
  27408. //# sourceMappingURL=babylon.baseTexture.js.map
  27409. "use strict";
  27410. var BABYLON;
  27411. (function (BABYLON) {
  27412. var Texture = /** @class */ (function (_super) {
  27413. __extends(Texture, _super);
  27414. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  27415. if (noMipmap === void 0) { noMipmap = false; }
  27416. if (invertY === void 0) { invertY = true; }
  27417. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27418. if (onLoad === void 0) { onLoad = null; }
  27419. if (onError === void 0) { onError = null; }
  27420. if (buffer === void 0) { buffer = null; }
  27421. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27422. var _this = _super.call(this, scene) || this;
  27423. _this.uOffset = 0;
  27424. _this.vOffset = 0;
  27425. _this.uScale = 1.0;
  27426. _this.vScale = 1.0;
  27427. _this.uAng = 0;
  27428. _this.vAng = 0;
  27429. _this.wAng = 0;
  27430. _this._isBlocking = true;
  27431. _this.name = url || "";
  27432. _this.url = url;
  27433. _this._noMipmap = noMipmap;
  27434. _this._invertY = invertY;
  27435. _this._samplingMode = samplingMode;
  27436. _this._buffer = buffer;
  27437. _this._deleteBuffer = deleteBuffer;
  27438. if (format) {
  27439. _this._format = format;
  27440. }
  27441. scene = _this.getScene();
  27442. if (!scene) {
  27443. return _this;
  27444. }
  27445. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  27446. var load = function () {
  27447. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  27448. _this.onLoadObservable.notifyObservers(_this);
  27449. }
  27450. if (onLoad) {
  27451. onLoad();
  27452. }
  27453. if (!_this.isBlocking && scene) {
  27454. scene.resetCachedMaterial();
  27455. }
  27456. };
  27457. if (!_this.url) {
  27458. _this._delayedOnLoad = load;
  27459. _this._delayedOnError = onError;
  27460. return _this;
  27461. }
  27462. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  27463. if (!_this._texture) {
  27464. if (!scene.useDelayedTextureLoading) {
  27465. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  27466. if (deleteBuffer) {
  27467. delete _this._buffer;
  27468. }
  27469. }
  27470. else {
  27471. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27472. _this._delayedOnLoad = load;
  27473. _this._delayedOnError = onError;
  27474. }
  27475. }
  27476. else {
  27477. if (_this._texture.isReady) {
  27478. BABYLON.Tools.SetImmediate(function () { return load(); });
  27479. }
  27480. else {
  27481. _this._texture.onLoadedObservable.add(load);
  27482. }
  27483. }
  27484. return _this;
  27485. }
  27486. Object.defineProperty(Texture.prototype, "noMipmap", {
  27487. get: function () {
  27488. return this._noMipmap;
  27489. },
  27490. enumerable: true,
  27491. configurable: true
  27492. });
  27493. Object.defineProperty(Texture.prototype, "isBlocking", {
  27494. get: function () {
  27495. return this._isBlocking;
  27496. },
  27497. set: function (value) {
  27498. this._isBlocking = value;
  27499. },
  27500. enumerable: true,
  27501. configurable: true
  27502. });
  27503. Object.defineProperty(Texture.prototype, "samplingMode", {
  27504. get: function () {
  27505. return this._samplingMode;
  27506. },
  27507. enumerable: true,
  27508. configurable: true
  27509. });
  27510. Texture.prototype.updateURL = function (url) {
  27511. this.url = url;
  27512. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27513. this.delayLoad();
  27514. };
  27515. Texture.prototype.delayLoad = function () {
  27516. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27517. return;
  27518. }
  27519. var scene = this.getScene();
  27520. if (!scene) {
  27521. return;
  27522. }
  27523. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27524. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  27525. if (!this._texture) {
  27526. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  27527. if (this._deleteBuffer) {
  27528. delete this._buffer;
  27529. }
  27530. }
  27531. else {
  27532. if (this._delayedOnLoad) {
  27533. if (this._texture.isReady) {
  27534. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  27535. }
  27536. else {
  27537. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  27538. }
  27539. }
  27540. }
  27541. this._delayedOnLoad = null;
  27542. this._delayedOnError = null;
  27543. };
  27544. Texture.prototype.updateSamplingMode = function (samplingMode) {
  27545. if (!this._texture) {
  27546. return;
  27547. }
  27548. var scene = this.getScene();
  27549. if (!scene) {
  27550. return;
  27551. }
  27552. this._samplingMode = samplingMode;
  27553. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  27554. };
  27555. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  27556. x *= this.uScale;
  27557. y *= this.vScale;
  27558. x -= 0.5 * this.uScale;
  27559. y -= 0.5 * this.vScale;
  27560. z -= 0.5;
  27561. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  27562. t.x += 0.5 * this.uScale + this.uOffset;
  27563. t.y += 0.5 * this.vScale + this.vOffset;
  27564. t.z += 0.5;
  27565. };
  27566. Texture.prototype.getTextureMatrix = function () {
  27567. var _this = this;
  27568. if (this.uOffset === this._cachedUOffset &&
  27569. this.vOffset === this._cachedVOffset &&
  27570. this.uScale === this._cachedUScale &&
  27571. this.vScale === this._cachedVScale &&
  27572. this.uAng === this._cachedUAng &&
  27573. this.vAng === this._cachedVAng &&
  27574. this.wAng === this._cachedWAng) {
  27575. return this._cachedTextureMatrix;
  27576. }
  27577. this._cachedUOffset = this.uOffset;
  27578. this._cachedVOffset = this.vOffset;
  27579. this._cachedUScale = this.uScale;
  27580. this._cachedVScale = this.vScale;
  27581. this._cachedUAng = this.uAng;
  27582. this._cachedVAng = this.vAng;
  27583. this._cachedWAng = this.wAng;
  27584. if (!this._cachedTextureMatrix) {
  27585. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27586. this._rowGenerationMatrix = new BABYLON.Matrix();
  27587. this._t0 = BABYLON.Vector3.Zero();
  27588. this._t1 = BABYLON.Vector3.Zero();
  27589. this._t2 = BABYLON.Vector3.Zero();
  27590. }
  27591. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  27592. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  27593. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  27594. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  27595. this._t1.subtractInPlace(this._t0);
  27596. this._t2.subtractInPlace(this._t0);
  27597. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27598. this._cachedTextureMatrix.m[0] = this._t1.x;
  27599. this._cachedTextureMatrix.m[1] = this._t1.y;
  27600. this._cachedTextureMatrix.m[2] = this._t1.z;
  27601. this._cachedTextureMatrix.m[4] = this._t2.x;
  27602. this._cachedTextureMatrix.m[5] = this._t2.y;
  27603. this._cachedTextureMatrix.m[6] = this._t2.z;
  27604. this._cachedTextureMatrix.m[8] = this._t0.x;
  27605. this._cachedTextureMatrix.m[9] = this._t0.y;
  27606. this._cachedTextureMatrix.m[10] = this._t0.z;
  27607. var scene = this.getScene();
  27608. if (!scene) {
  27609. return this._cachedTextureMatrix;
  27610. }
  27611. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27612. return mat.hasTexture(_this);
  27613. });
  27614. return this._cachedTextureMatrix;
  27615. };
  27616. Texture.prototype.getReflectionTextureMatrix = function () {
  27617. var _this = this;
  27618. var scene = this.getScene();
  27619. if (!scene) {
  27620. return this._cachedTextureMatrix;
  27621. }
  27622. if (this.uOffset === this._cachedUOffset &&
  27623. this.vOffset === this._cachedVOffset &&
  27624. this.uScale === this._cachedUScale &&
  27625. this.vScale === this._cachedVScale &&
  27626. this.coordinatesMode === this._cachedCoordinatesMode) {
  27627. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  27628. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  27629. return this._cachedTextureMatrix;
  27630. }
  27631. }
  27632. else {
  27633. return this._cachedTextureMatrix;
  27634. }
  27635. }
  27636. if (!this._cachedTextureMatrix) {
  27637. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27638. }
  27639. if (!this._projectionModeMatrix) {
  27640. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  27641. }
  27642. this._cachedUOffset = this.uOffset;
  27643. this._cachedVOffset = this.vOffset;
  27644. this._cachedUScale = this.uScale;
  27645. this._cachedVScale = this.vScale;
  27646. this._cachedCoordinatesMode = this.coordinatesMode;
  27647. switch (this.coordinatesMode) {
  27648. case Texture.PLANAR_MODE:
  27649. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27650. this._cachedTextureMatrix[0] = this.uScale;
  27651. this._cachedTextureMatrix[5] = this.vScale;
  27652. this._cachedTextureMatrix[12] = this.uOffset;
  27653. this._cachedTextureMatrix[13] = this.vOffset;
  27654. break;
  27655. case Texture.PROJECTION_MODE:
  27656. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  27657. this._projectionModeMatrix.m[0] = 0.5;
  27658. this._projectionModeMatrix.m[5] = -0.5;
  27659. this._projectionModeMatrix.m[10] = 0.0;
  27660. this._projectionModeMatrix.m[12] = 0.5;
  27661. this._projectionModeMatrix.m[13] = 0.5;
  27662. this._projectionModeMatrix.m[14] = 1.0;
  27663. this._projectionModeMatrix.m[15] = 1.0;
  27664. var projectionMatrix = scene.getProjectionMatrix();
  27665. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  27666. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  27667. break;
  27668. default:
  27669. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27670. break;
  27671. }
  27672. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27673. return (mat.getActiveTextures().indexOf(_this) !== -1);
  27674. });
  27675. return this._cachedTextureMatrix;
  27676. };
  27677. Texture.prototype.clone = function () {
  27678. var _this = this;
  27679. return BABYLON.SerializationHelper.Clone(function () {
  27680. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  27681. }, this);
  27682. };
  27683. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  27684. get: function () {
  27685. if (!this._onLoadObservable) {
  27686. this._onLoadObservable = new BABYLON.Observable();
  27687. }
  27688. return this._onLoadObservable;
  27689. },
  27690. enumerable: true,
  27691. configurable: true
  27692. });
  27693. Texture.prototype.serialize = function () {
  27694. var serializationObject = _super.prototype.serialize.call(this);
  27695. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  27696. serializationObject.base64String = this._buffer;
  27697. serializationObject.name = serializationObject.name.replace("data:", "");
  27698. }
  27699. return serializationObject;
  27700. };
  27701. Texture.prototype.getClassName = function () {
  27702. return "Texture";
  27703. };
  27704. Texture.prototype.dispose = function () {
  27705. _super.prototype.dispose.call(this);
  27706. if (this.onLoadObservable) {
  27707. this.onLoadObservable.clear();
  27708. this._onLoadObservable = null;
  27709. }
  27710. this._delayedOnLoad = null;
  27711. this._delayedOnError = null;
  27712. };
  27713. // Statics
  27714. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27715. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27716. if (onLoad === void 0) { onLoad = null; }
  27717. if (onError === void 0) { onError = null; }
  27718. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27719. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27720. };
  27721. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27722. if (parsedTexture.customType) {
  27723. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27724. // Update Sampling Mode
  27725. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  27726. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  27727. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  27728. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  27729. }
  27730. }
  27731. return parsedCustomTexture;
  27732. }
  27733. if (parsedTexture.isCube) {
  27734. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27735. }
  27736. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27737. return null;
  27738. }
  27739. var texture = BABYLON.SerializationHelper.Parse(function () {
  27740. var generateMipMaps = true;
  27741. if (parsedTexture.noMipmap) {
  27742. generateMipMaps = false;
  27743. }
  27744. if (parsedTexture.mirrorPlane) {
  27745. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27746. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27747. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27748. return mirrorTexture;
  27749. }
  27750. else if (parsedTexture.isRenderTarget) {
  27751. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27752. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27753. return renderTargetTexture;
  27754. }
  27755. else {
  27756. var texture;
  27757. if (parsedTexture.base64String) {
  27758. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  27759. }
  27760. else {
  27761. var url = rootUrl + parsedTexture.name;
  27762. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  27763. url = parsedTexture.url;
  27764. }
  27765. texture = new Texture(url, scene, !generateMipMaps);
  27766. }
  27767. return texture;
  27768. }
  27769. }, parsedTexture, scene);
  27770. // Update Sampling Mode
  27771. if (parsedTexture.samplingMode) {
  27772. var sampling = parsedTexture.samplingMode;
  27773. if (texture._samplingMode !== sampling) {
  27774. texture.updateSamplingMode(sampling);
  27775. }
  27776. }
  27777. // Animations
  27778. if (parsedTexture.animations) {
  27779. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27780. var parsedAnimation = parsedTexture.animations[animationIndex];
  27781. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27782. }
  27783. }
  27784. return texture;
  27785. };
  27786. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27787. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27788. if (noMipmap === void 0) { noMipmap = false; }
  27789. if (invertY === void 0) { invertY = true; }
  27790. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27791. if (onLoad === void 0) { onLoad = null; }
  27792. if (onError === void 0) { onError = null; }
  27793. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27794. if (name.substr(0, 5) !== "data:") {
  27795. name = "data:" + name;
  27796. }
  27797. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27798. };
  27799. // Constants
  27800. Texture.NEAREST_SAMPLINGMODE = 1;
  27801. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  27802. Texture.BILINEAR_SAMPLINGMODE = 2;
  27803. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  27804. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27805. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  27806. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  27807. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  27808. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  27809. Texture.NEAREST_LINEAR = 7;
  27810. Texture.NEAREST_NEAREST = 8;
  27811. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  27812. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  27813. Texture.LINEAR_LINEAR = 11;
  27814. Texture.LINEAR_NEAREST = 12;
  27815. Texture.EXPLICIT_MODE = 0;
  27816. Texture.SPHERICAL_MODE = 1;
  27817. Texture.PLANAR_MODE = 2;
  27818. Texture.CUBIC_MODE = 3;
  27819. Texture.PROJECTION_MODE = 4;
  27820. Texture.SKYBOX_MODE = 5;
  27821. Texture.INVCUBIC_MODE = 6;
  27822. Texture.EQUIRECTANGULAR_MODE = 7;
  27823. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27824. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27825. Texture.CLAMP_ADDRESSMODE = 0;
  27826. Texture.WRAP_ADDRESSMODE = 1;
  27827. Texture.MIRROR_ADDRESSMODE = 2;
  27828. /**
  27829. * 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
  27830. */
  27831. Texture.UseSerializedUrlIfAny = false;
  27832. __decorate([
  27833. BABYLON.serialize()
  27834. ], Texture.prototype, "url", void 0);
  27835. __decorate([
  27836. BABYLON.serialize()
  27837. ], Texture.prototype, "uOffset", void 0);
  27838. __decorate([
  27839. BABYLON.serialize()
  27840. ], Texture.prototype, "vOffset", void 0);
  27841. __decorate([
  27842. BABYLON.serialize()
  27843. ], Texture.prototype, "uScale", void 0);
  27844. __decorate([
  27845. BABYLON.serialize()
  27846. ], Texture.prototype, "vScale", void 0);
  27847. __decorate([
  27848. BABYLON.serialize()
  27849. ], Texture.prototype, "uAng", void 0);
  27850. __decorate([
  27851. BABYLON.serialize()
  27852. ], Texture.prototype, "vAng", void 0);
  27853. __decorate([
  27854. BABYLON.serialize()
  27855. ], Texture.prototype, "wAng", void 0);
  27856. __decorate([
  27857. BABYLON.serialize()
  27858. ], Texture.prototype, "isBlocking", null);
  27859. return Texture;
  27860. }(BABYLON.BaseTexture));
  27861. BABYLON.Texture = Texture;
  27862. })(BABYLON || (BABYLON = {}));
  27863. //# sourceMappingURL=babylon.texture.js.map
  27864. "use strict";
  27865. var BABYLON;
  27866. (function (BABYLON) {
  27867. var _InstancesBatch = /** @class */ (function () {
  27868. function _InstancesBatch() {
  27869. this.mustReturn = false;
  27870. this.visibleInstances = new Array();
  27871. this.renderSelf = new Array();
  27872. }
  27873. return _InstancesBatch;
  27874. }());
  27875. BABYLON._InstancesBatch = _InstancesBatch;
  27876. var Mesh = /** @class */ (function (_super) {
  27877. __extends(Mesh, _super);
  27878. /**
  27879. * @constructor
  27880. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  27881. * @param {Scene} scene The scene to add this mesh to.
  27882. * @param {Node} parent The parent of this mesh, if it has one
  27883. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  27884. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  27885. * When false, achieved by calling a clone(), also passing False.
  27886. * This will make creation of children, recursive.
  27887. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  27888. */
  27889. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  27890. if (scene === void 0) { scene = null; }
  27891. if (parent === void 0) { parent = null; }
  27892. if (source === void 0) { source = null; }
  27893. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27894. var _this = _super.call(this, name, scene) || this;
  27895. // Events
  27896. /**
  27897. * An event triggered before rendering the mesh
  27898. */
  27899. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27900. /**
  27901. * An event triggered after rendering the mesh
  27902. */
  27903. _this.onAfterRenderObservable = new BABYLON.Observable();
  27904. /**
  27905. * An event triggered before drawing the mesh
  27906. */
  27907. _this.onBeforeDrawObservable = new BABYLON.Observable();
  27908. // Members
  27909. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27910. _this.instances = new Array();
  27911. _this._LODLevels = new Array();
  27912. _this._visibleInstances = {};
  27913. _this._renderIdForInstances = new Array();
  27914. _this._batchCache = new _InstancesBatch();
  27915. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  27916. // Use by builder only to know what orientation were the mesh build in.
  27917. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  27918. _this.overrideMaterialSideOrientation = null;
  27919. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  27920. // Will be used to save a source mesh reference, If any
  27921. _this._source = null;
  27922. scene = _this.getScene();
  27923. if (source) {
  27924. // Source mesh
  27925. _this._source = source;
  27926. // Geometry
  27927. if (source._geometry) {
  27928. source._geometry.applyToMesh(_this);
  27929. }
  27930. // Deep copy
  27931. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  27932. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix", "_source"]);
  27933. // Metadata
  27934. if (source.metadata && source.metadata.clone) {
  27935. _this.metadata = source.metadata.clone();
  27936. }
  27937. else {
  27938. _this.metadata = source.metadata;
  27939. }
  27940. // Tags
  27941. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  27942. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  27943. }
  27944. // Parent
  27945. _this.parent = source.parent;
  27946. // Pivot
  27947. _this.setPivotMatrix(source.getPivotMatrix());
  27948. _this.id = name + "." + source.id;
  27949. // Material
  27950. _this.material = source.material;
  27951. var index;
  27952. if (!doNotCloneChildren) {
  27953. // Children
  27954. var directDescendants = source.getDescendants(true);
  27955. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  27956. var child = directDescendants[index_1];
  27957. if (child.clone) {
  27958. child.clone(name + "." + child.name, _this);
  27959. }
  27960. }
  27961. }
  27962. // Physics clone
  27963. var physicsEngine = _this.getScene().getPhysicsEngine();
  27964. if (clonePhysicsImpostor && physicsEngine) {
  27965. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  27966. if (impostor) {
  27967. _this.physicsImpostor = impostor.clone(_this);
  27968. }
  27969. }
  27970. // Particles
  27971. for (index = 0; index < scene.particleSystems.length; index++) {
  27972. var system = scene.particleSystems[index];
  27973. if (system.emitter === source) {
  27974. system.clone(system.name, _this);
  27975. }
  27976. }
  27977. _this.computeWorldMatrix(true);
  27978. }
  27979. // Parent
  27980. if (parent !== null) {
  27981. _this.parent = parent;
  27982. }
  27983. return _this;
  27984. }
  27985. Object.defineProperty(Mesh, "FRONTSIDE", {
  27986. /**
  27987. * Mesh side orientation : usually the external or front surface
  27988. */
  27989. get: function () {
  27990. return Mesh._FRONTSIDE;
  27991. },
  27992. enumerable: true,
  27993. configurable: true
  27994. });
  27995. Object.defineProperty(Mesh, "BACKSIDE", {
  27996. /**
  27997. * Mesh side orientation : usually the internal or back surface
  27998. */
  27999. get: function () {
  28000. return Mesh._BACKSIDE;
  28001. },
  28002. enumerable: true,
  28003. configurable: true
  28004. });
  28005. Object.defineProperty(Mesh, "DOUBLESIDE", {
  28006. /**
  28007. * Mesh side orientation : both internal and external or front and back surfaces
  28008. */
  28009. get: function () {
  28010. return Mesh._DOUBLESIDE;
  28011. },
  28012. enumerable: true,
  28013. configurable: true
  28014. });
  28015. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  28016. /**
  28017. * Mesh side orientation : by default, `FRONTSIDE`
  28018. */
  28019. get: function () {
  28020. return Mesh._DEFAULTSIDE;
  28021. },
  28022. enumerable: true,
  28023. configurable: true
  28024. });
  28025. Object.defineProperty(Mesh, "NO_CAP", {
  28026. /**
  28027. * Mesh cap setting : no cap
  28028. */
  28029. get: function () {
  28030. return Mesh._NO_CAP;
  28031. },
  28032. enumerable: true,
  28033. configurable: true
  28034. });
  28035. Object.defineProperty(Mesh, "CAP_START", {
  28036. /**
  28037. * Mesh cap setting : one cap at the beginning of the mesh
  28038. */
  28039. get: function () {
  28040. return Mesh._CAP_START;
  28041. },
  28042. enumerable: true,
  28043. configurable: true
  28044. });
  28045. Object.defineProperty(Mesh, "CAP_END", {
  28046. /**
  28047. * Mesh cap setting : one cap at the end of the mesh
  28048. */
  28049. get: function () {
  28050. return Mesh._CAP_END;
  28051. },
  28052. enumerable: true,
  28053. configurable: true
  28054. });
  28055. Object.defineProperty(Mesh, "CAP_ALL", {
  28056. /**
  28057. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  28058. */
  28059. get: function () {
  28060. return Mesh._CAP_ALL;
  28061. },
  28062. enumerable: true,
  28063. configurable: true
  28064. });
  28065. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  28066. set: function (callback) {
  28067. if (this._onBeforeDrawObserver) {
  28068. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  28069. }
  28070. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  28071. },
  28072. enumerable: true,
  28073. configurable: true
  28074. });
  28075. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  28076. get: function () {
  28077. return this._morphTargetManager;
  28078. },
  28079. set: function (value) {
  28080. if (this._morphTargetManager === value) {
  28081. return;
  28082. }
  28083. this._morphTargetManager = value;
  28084. this._syncGeometryWithMorphTargetManager();
  28085. },
  28086. enumerable: true,
  28087. configurable: true
  28088. });
  28089. Object.defineProperty(Mesh.prototype, "source", {
  28090. get: function () {
  28091. return this._source;
  28092. },
  28093. enumerable: true,
  28094. configurable: true
  28095. });
  28096. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  28097. get: function () {
  28098. return this._unIndexed;
  28099. },
  28100. set: function (value) {
  28101. if (this._unIndexed !== value) {
  28102. this._unIndexed = value;
  28103. this._markSubMeshesAsAttributesDirty();
  28104. }
  28105. },
  28106. enumerable: true,
  28107. configurable: true
  28108. });
  28109. // Methods
  28110. /**
  28111. * Returns the string "Mesh".
  28112. */
  28113. Mesh.prototype.getClassName = function () {
  28114. return "Mesh";
  28115. };
  28116. /**
  28117. * Returns a string.
  28118. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28119. */
  28120. Mesh.prototype.toString = function (fullDetails) {
  28121. var ret = _super.prototype.toString.call(this, fullDetails);
  28122. ret += ", n vertices: " + this.getTotalVertices();
  28123. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  28124. if (this.animations) {
  28125. for (var i = 0; i < this.animations.length; i++) {
  28126. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  28127. }
  28128. }
  28129. if (fullDetails) {
  28130. if (this._geometry) {
  28131. var ib = this.getIndices();
  28132. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28133. if (vb && ib) {
  28134. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  28135. }
  28136. }
  28137. else {
  28138. ret += ", flat shading: UNKNOWN";
  28139. }
  28140. }
  28141. return ret;
  28142. };
  28143. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  28144. /**
  28145. * True if the mesh has some Levels Of Details (LOD).
  28146. * Returns a boolean.
  28147. */
  28148. get: function () {
  28149. return this._LODLevels.length > 0;
  28150. },
  28151. enumerable: true,
  28152. configurable: true
  28153. });
  28154. /**
  28155. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  28156. * @returns an array of {BABYLON.MeshLODLevel}
  28157. */
  28158. Mesh.prototype.getLODLevels = function () {
  28159. return this._LODLevels;
  28160. };
  28161. Mesh.prototype._sortLODLevels = function () {
  28162. this._LODLevels.sort(function (a, b) {
  28163. if (a.distance < b.distance) {
  28164. return 1;
  28165. }
  28166. if (a.distance > b.distance) {
  28167. return -1;
  28168. }
  28169. return 0;
  28170. });
  28171. };
  28172. /**
  28173. * Add a mesh as LOD level triggered at the given distance.
  28174. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28175. * @param {number} distance The distance from the center of the object to show this level
  28176. * @param {Mesh} mesh The mesh to be added as LOD level
  28177. * @return {Mesh} This mesh (for chaining)
  28178. */
  28179. Mesh.prototype.addLODLevel = function (distance, mesh) {
  28180. if (mesh && mesh._masterMesh) {
  28181. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  28182. return this;
  28183. }
  28184. var level = new BABYLON.MeshLODLevel(distance, mesh);
  28185. this._LODLevels.push(level);
  28186. if (mesh) {
  28187. mesh._masterMesh = this;
  28188. }
  28189. this._sortLODLevels();
  28190. return this;
  28191. };
  28192. /**
  28193. * Returns the LOD level mesh at the passed distance or null if not found.
  28194. * It is related to the method `addLODLevel(distance, mesh)`.
  28195. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28196. * Returns an object Mesh or `null`.
  28197. */
  28198. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  28199. for (var index = 0; index < this._LODLevels.length; index++) {
  28200. var level = this._LODLevels[index];
  28201. if (level.distance === distance) {
  28202. return level.mesh;
  28203. }
  28204. }
  28205. return null;
  28206. };
  28207. /**
  28208. * Remove a mesh from the LOD array
  28209. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28210. * @param {Mesh} mesh The mesh to be removed.
  28211. * @return {Mesh} This mesh (for chaining)
  28212. */
  28213. Mesh.prototype.removeLODLevel = function (mesh) {
  28214. for (var index = 0; index < this._LODLevels.length; index++) {
  28215. if (this._LODLevels[index].mesh === mesh) {
  28216. this._LODLevels.splice(index, 1);
  28217. if (mesh) {
  28218. mesh._masterMesh = null;
  28219. }
  28220. }
  28221. }
  28222. this._sortLODLevels();
  28223. return this;
  28224. };
  28225. /**
  28226. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  28227. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28228. */
  28229. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  28230. if (!this._LODLevels || this._LODLevels.length === 0) {
  28231. return this;
  28232. }
  28233. var bSphere;
  28234. if (boundingSphere) {
  28235. bSphere = boundingSphere;
  28236. }
  28237. else {
  28238. var boundingInfo = this.getBoundingInfo();
  28239. bSphere = boundingInfo.boundingSphere;
  28240. }
  28241. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  28242. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  28243. if (this.onLODLevelSelection) {
  28244. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  28245. }
  28246. return this;
  28247. }
  28248. for (var index = 0; index < this._LODLevels.length; index++) {
  28249. var level = this._LODLevels[index];
  28250. if (level.distance < distanceToCamera) {
  28251. if (level.mesh) {
  28252. level.mesh._preActivate();
  28253. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  28254. }
  28255. if (this.onLODLevelSelection) {
  28256. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  28257. }
  28258. return level.mesh;
  28259. }
  28260. }
  28261. if (this.onLODLevelSelection) {
  28262. this.onLODLevelSelection(distanceToCamera, this, this);
  28263. }
  28264. return this;
  28265. };
  28266. Object.defineProperty(Mesh.prototype, "geometry", {
  28267. /**
  28268. * Returns the mesh internal Geometry object.
  28269. */
  28270. get: function () {
  28271. return this._geometry;
  28272. },
  28273. enumerable: true,
  28274. configurable: true
  28275. });
  28276. /**
  28277. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  28278. */
  28279. Mesh.prototype.getTotalVertices = function () {
  28280. if (this._geometry === null || this._geometry === undefined) {
  28281. return 0;
  28282. }
  28283. return this._geometry.getTotalVertices();
  28284. };
  28285. /**
  28286. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  28287. * 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.
  28288. * You can force the copy with forceCopy === true
  28289. * Returns null if the mesh has no geometry or no vertex buffer.
  28290. * Possible `kind` values :
  28291. * - BABYLON.VertexBuffer.PositionKind
  28292. * - BABYLON.VertexBuffer.UVKind
  28293. * - BABYLON.VertexBuffer.UV2Kind
  28294. * - BABYLON.VertexBuffer.UV3Kind
  28295. * - BABYLON.VertexBuffer.UV4Kind
  28296. * - BABYLON.VertexBuffer.UV5Kind
  28297. * - BABYLON.VertexBuffer.UV6Kind
  28298. * - BABYLON.VertexBuffer.ColorKind
  28299. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28300. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28301. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28302. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28303. */
  28304. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  28305. if (!this._geometry) {
  28306. return null;
  28307. }
  28308. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  28309. };
  28310. /**
  28311. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  28312. * Returns `null` if the mesh has no geometry.
  28313. * Possible `kind` values :
  28314. * - BABYLON.VertexBuffer.PositionKind
  28315. * - BABYLON.VertexBuffer.UVKind
  28316. * - BABYLON.VertexBuffer.UV2Kind
  28317. * - BABYLON.VertexBuffer.UV3Kind
  28318. * - BABYLON.VertexBuffer.UV4Kind
  28319. * - BABYLON.VertexBuffer.UV5Kind
  28320. * - BABYLON.VertexBuffer.UV6Kind
  28321. * - BABYLON.VertexBuffer.ColorKind
  28322. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28323. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28324. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28325. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28326. */
  28327. Mesh.prototype.getVertexBuffer = function (kind) {
  28328. if (!this._geometry) {
  28329. return null;
  28330. }
  28331. return this._geometry.getVertexBuffer(kind);
  28332. };
  28333. /**
  28334. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  28335. * Possible `kind` values :
  28336. * - BABYLON.VertexBuffer.PositionKind
  28337. * - BABYLON.VertexBuffer.UVKind
  28338. * - BABYLON.VertexBuffer.UV2Kind
  28339. * - BABYLON.VertexBuffer.UV3Kind
  28340. * - BABYLON.VertexBuffer.UV4Kind
  28341. * - BABYLON.VertexBuffer.UV5Kind
  28342. * - BABYLON.VertexBuffer.UV6Kind
  28343. * - BABYLON.VertexBuffer.ColorKind
  28344. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28345. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28346. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28347. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28348. */
  28349. Mesh.prototype.isVerticesDataPresent = function (kind) {
  28350. if (!this._geometry) {
  28351. if (this._delayInfo) {
  28352. return this._delayInfo.indexOf(kind) !== -1;
  28353. }
  28354. return false;
  28355. }
  28356. return this._geometry.isVerticesDataPresent(kind);
  28357. };
  28358. /**
  28359. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  28360. * Possible `kind` values :
  28361. * - BABYLON.VertexBuffer.PositionKind
  28362. * - BABYLON.VertexBuffer.UVKind
  28363. * - BABYLON.VertexBuffer.UV2Kind
  28364. * - BABYLON.VertexBuffer.UV3Kind
  28365. * - BABYLON.VertexBuffer.UV4Kind
  28366. * - BABYLON.VertexBuffer.UV5Kind
  28367. * - BABYLON.VertexBuffer.UV6Kind
  28368. * - BABYLON.VertexBuffer.ColorKind
  28369. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28370. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28371. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28372. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28373. */
  28374. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  28375. if (!this._geometry) {
  28376. if (this._delayInfo) {
  28377. return this._delayInfo.indexOf(kind) !== -1;
  28378. }
  28379. return false;
  28380. }
  28381. return this._geometry.isVertexBufferUpdatable(kind);
  28382. };
  28383. /**
  28384. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  28385. * Possible `kind` values :
  28386. * - BABYLON.VertexBuffer.PositionKind
  28387. * - BABYLON.VertexBuffer.UVKind
  28388. * - BABYLON.VertexBuffer.UV2Kind
  28389. * - BABYLON.VertexBuffer.UV3Kind
  28390. * - BABYLON.VertexBuffer.UV4Kind
  28391. * - BABYLON.VertexBuffer.UV5Kind
  28392. * - BABYLON.VertexBuffer.UV6Kind
  28393. * - BABYLON.VertexBuffer.ColorKind
  28394. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28395. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28396. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28397. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28398. */
  28399. Mesh.prototype.getVerticesDataKinds = function () {
  28400. if (!this._geometry) {
  28401. var result = new Array();
  28402. if (this._delayInfo) {
  28403. this._delayInfo.forEach(function (kind, index, array) {
  28404. result.push(kind);
  28405. });
  28406. }
  28407. return result;
  28408. }
  28409. return this._geometry.getVerticesDataKinds();
  28410. };
  28411. /**
  28412. * Returns a positive integer : the total number of indices in this mesh geometry.
  28413. * Returns zero if the mesh has no geometry.
  28414. */
  28415. Mesh.prototype.getTotalIndices = function () {
  28416. if (!this._geometry) {
  28417. return 0;
  28418. }
  28419. return this._geometry.getTotalIndices();
  28420. };
  28421. /**
  28422. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  28423. * 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.
  28424. * Returns an empty array if the mesh has no geometry.
  28425. */
  28426. Mesh.prototype.getIndices = function (copyWhenShared) {
  28427. if (!this._geometry) {
  28428. return [];
  28429. }
  28430. return this._geometry.getIndices(copyWhenShared);
  28431. };
  28432. Object.defineProperty(Mesh.prototype, "isBlocked", {
  28433. get: function () {
  28434. return this._masterMesh !== null && this._masterMesh !== undefined;
  28435. },
  28436. enumerable: true,
  28437. configurable: true
  28438. });
  28439. /**
  28440. * Determine if the current mesh is ready to be rendered
  28441. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  28442. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  28443. * @returns true if all associated assets are ready (material, textures, shaders)
  28444. */
  28445. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  28446. if (completeCheck === void 0) { completeCheck = false; }
  28447. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  28448. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28449. return false;
  28450. }
  28451. if (!_super.prototype.isReady.call(this, completeCheck)) {
  28452. return false;
  28453. }
  28454. if (!this.subMeshes || this.subMeshes.length === 0) {
  28455. return true;
  28456. }
  28457. if (!completeCheck) {
  28458. return true;
  28459. }
  28460. var engine = this.getEngine();
  28461. var scene = this.getScene();
  28462. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  28463. this.computeWorldMatrix();
  28464. var mat = this.material || scene.defaultMaterial;
  28465. if (mat) {
  28466. if (mat.storeEffectOnSubMeshes) {
  28467. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28468. var subMesh = _a[_i];
  28469. var effectiveMaterial = subMesh.getMaterial();
  28470. if (effectiveMaterial) {
  28471. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28472. return false;
  28473. }
  28474. }
  28475. }
  28476. }
  28477. else {
  28478. if (!mat.isReady(this, hardwareInstancedRendering)) {
  28479. return false;
  28480. }
  28481. }
  28482. }
  28483. // Shadows
  28484. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  28485. var light = _c[_b];
  28486. var generator = light.getShadowGenerator();
  28487. if (generator) {
  28488. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  28489. var subMesh = _e[_d];
  28490. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  28491. return false;
  28492. }
  28493. }
  28494. }
  28495. }
  28496. // LOD
  28497. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  28498. var lod = _g[_f];
  28499. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  28500. return false;
  28501. }
  28502. }
  28503. return true;
  28504. };
  28505. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  28506. /**
  28507. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  28508. * This property is pertinent only for updatable parametric shapes.
  28509. */
  28510. get: function () {
  28511. return this._areNormalsFrozen;
  28512. },
  28513. enumerable: true,
  28514. configurable: true
  28515. });
  28516. /**
  28517. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28518. * It has no effect at all on other shapes.
  28519. * It prevents the mesh normals from being recomputed on next `positions` array update.
  28520. * Returns the Mesh.
  28521. */
  28522. Mesh.prototype.freezeNormals = function () {
  28523. this._areNormalsFrozen = true;
  28524. return this;
  28525. };
  28526. /**
  28527. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28528. * It has no effect at all on other shapes.
  28529. * It reactivates the mesh normals computation if it was previously frozen.
  28530. * Returns the Mesh.
  28531. */
  28532. Mesh.prototype.unfreezeNormals = function () {
  28533. this._areNormalsFrozen = false;
  28534. return this;
  28535. };
  28536. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  28537. /**
  28538. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  28539. */
  28540. set: function (count) {
  28541. this._overridenInstanceCount = count;
  28542. },
  28543. enumerable: true,
  28544. configurable: true
  28545. });
  28546. // Methods
  28547. Mesh.prototype._preActivate = function () {
  28548. var sceneRenderId = this.getScene().getRenderId();
  28549. if (this._preActivateId === sceneRenderId) {
  28550. return this;
  28551. }
  28552. this._preActivateId = sceneRenderId;
  28553. this._visibleInstances = null;
  28554. return this;
  28555. };
  28556. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  28557. if (this._visibleInstances) {
  28558. this._visibleInstances.intermediateDefaultRenderId = renderId;
  28559. }
  28560. return this;
  28561. };
  28562. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  28563. if (!this._visibleInstances) {
  28564. this._visibleInstances = {};
  28565. this._visibleInstances.defaultRenderId = renderId;
  28566. this._visibleInstances.selfDefaultRenderId = this._renderId;
  28567. }
  28568. if (!this._visibleInstances[renderId]) {
  28569. this._visibleInstances[renderId] = new Array();
  28570. }
  28571. this._visibleInstances[renderId].push(instance);
  28572. return this;
  28573. };
  28574. /**
  28575. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  28576. * This means the mesh underlying bounding box and sphere are recomputed.
  28577. * Returns the Mesh.
  28578. */
  28579. Mesh.prototype.refreshBoundingInfo = function () {
  28580. return this._refreshBoundingInfo(false);
  28581. };
  28582. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  28583. if (this._boundingInfo && this._boundingInfo.isLocked) {
  28584. return this;
  28585. }
  28586. var data = this._getPositionData(applySkeleton);
  28587. if (data) {
  28588. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  28589. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28590. }
  28591. if (this.subMeshes) {
  28592. for (var index = 0; index < this.subMeshes.length; index++) {
  28593. this.subMeshes[index].refreshBoundingInfo();
  28594. }
  28595. }
  28596. this._updateBoundingInfo();
  28597. return this;
  28598. };
  28599. Mesh.prototype._getPositionData = function (applySkeleton) {
  28600. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28601. if (data && applySkeleton && this.skeleton) {
  28602. data = BABYLON.Tools.Slice(data);
  28603. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28604. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28605. if (matricesWeightsData && matricesIndicesData) {
  28606. var needExtras = this.numBoneInfluencers > 4;
  28607. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  28608. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  28609. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  28610. var tempVector = BABYLON.Tmp.Vector3[0];
  28611. var finalMatrix = BABYLON.Tmp.Matrix[0];
  28612. var tempMatrix = BABYLON.Tmp.Matrix[1];
  28613. var matWeightIdx = 0;
  28614. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  28615. finalMatrix.reset();
  28616. var inf;
  28617. var weight;
  28618. for (inf = 0; inf < 4; inf++) {
  28619. weight = matricesWeightsData[matWeightIdx + inf];
  28620. if (weight <= 0)
  28621. break;
  28622. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28623. finalMatrix.addToSelf(tempMatrix);
  28624. }
  28625. if (needExtras) {
  28626. for (inf = 0; inf < 4; inf++) {
  28627. weight = matricesWeightsExtraData[matWeightIdx + inf];
  28628. if (weight <= 0)
  28629. break;
  28630. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28631. finalMatrix.addToSelf(tempMatrix);
  28632. }
  28633. }
  28634. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  28635. tempVector.toArray(data, index);
  28636. }
  28637. }
  28638. }
  28639. return data;
  28640. };
  28641. Mesh.prototype._createGlobalSubMesh = function (force) {
  28642. var totalVertices = this.getTotalVertices();
  28643. if (!totalVertices || !this.getIndices()) {
  28644. return null;
  28645. }
  28646. // Check if we need to recreate the submeshes
  28647. if (this.subMeshes && this.subMeshes.length > 0) {
  28648. var ib = this.getIndices();
  28649. if (!ib) {
  28650. return null;
  28651. }
  28652. var totalIndices = ib.length;
  28653. var needToRecreate = false;
  28654. if (force) {
  28655. needToRecreate = true;
  28656. }
  28657. else {
  28658. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28659. var submesh = _a[_i];
  28660. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  28661. needToRecreate = true;
  28662. break;
  28663. }
  28664. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  28665. needToRecreate = true;
  28666. break;
  28667. }
  28668. }
  28669. }
  28670. if (!needToRecreate) {
  28671. return this.subMeshes[0];
  28672. }
  28673. }
  28674. this.releaseSubMeshes();
  28675. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  28676. };
  28677. Mesh.prototype.subdivide = function (count) {
  28678. if (count < 1) {
  28679. return;
  28680. }
  28681. var totalIndices = this.getTotalIndices();
  28682. var subdivisionSize = (totalIndices / count) | 0;
  28683. var offset = 0;
  28684. // Ensure that subdivisionSize is a multiple of 3
  28685. while (subdivisionSize % 3 !== 0) {
  28686. subdivisionSize++;
  28687. }
  28688. this.releaseSubMeshes();
  28689. for (var index = 0; index < count; index++) {
  28690. if (offset >= totalIndices) {
  28691. break;
  28692. }
  28693. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  28694. offset += subdivisionSize;
  28695. }
  28696. this.synchronizeInstances();
  28697. };
  28698. /**
  28699. * Sets the vertex data of the mesh geometry for the requested `kind`.
  28700. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  28701. * The `data` are either a numeric array either a Float32Array.
  28702. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  28703. * 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).
  28704. * Note that a new underlying VertexBuffer object is created each call.
  28705. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  28706. *
  28707. * Possible `kind` values :
  28708. * - BABYLON.VertexBuffer.PositionKind
  28709. * - BABYLON.VertexBuffer.UVKind
  28710. * - BABYLON.VertexBuffer.UV2Kind
  28711. * - BABYLON.VertexBuffer.UV3Kind
  28712. * - BABYLON.VertexBuffer.UV4Kind
  28713. * - BABYLON.VertexBuffer.UV5Kind
  28714. * - BABYLON.VertexBuffer.UV6Kind
  28715. * - BABYLON.VertexBuffer.ColorKind
  28716. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28717. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28718. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28719. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28720. *
  28721. * Returns the Mesh.
  28722. */
  28723. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28724. if (updatable === void 0) { updatable = false; }
  28725. if (!this._geometry) {
  28726. var vertexData = new BABYLON.VertexData();
  28727. vertexData.set(data, kind);
  28728. var scene = this.getScene();
  28729. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28730. }
  28731. else {
  28732. this._geometry.setVerticesData(kind, data, updatable, stride);
  28733. }
  28734. return this;
  28735. };
  28736. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  28737. if (updatable === void 0) { updatable = true; }
  28738. var vb = this.getVertexBuffer(kind);
  28739. if (!vb || vb.isUpdatable() === updatable) {
  28740. return;
  28741. }
  28742. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  28743. };
  28744. /**
  28745. * Sets the mesh VertexBuffer.
  28746. * Returns the Mesh.
  28747. */
  28748. Mesh.prototype.setVerticesBuffer = function (buffer) {
  28749. if (!this._geometry) {
  28750. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  28751. }
  28752. this._geometry.setVerticesBuffer(buffer);
  28753. return this;
  28754. };
  28755. /**
  28756. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  28757. * If the mesh has no geometry, it is simply returned as it is.
  28758. * The `data` are either a numeric array either a Float32Array.
  28759. * No new underlying VertexBuffer object is created.
  28760. * 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.
  28761. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  28762. *
  28763. * Possible `kind` values :
  28764. * - BABYLON.VertexBuffer.PositionKind
  28765. * - BABYLON.VertexBuffer.UVKind
  28766. * - BABYLON.VertexBuffer.UV2Kind
  28767. * - BABYLON.VertexBuffer.UV3Kind
  28768. * - BABYLON.VertexBuffer.UV4Kind
  28769. * - BABYLON.VertexBuffer.UV5Kind
  28770. * - BABYLON.VertexBuffer.UV6Kind
  28771. * - BABYLON.VertexBuffer.ColorKind
  28772. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28773. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28774. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28775. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28776. *
  28777. * Returns the Mesh.
  28778. */
  28779. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  28780. if (!this._geometry) {
  28781. return this;
  28782. }
  28783. if (!makeItUnique) {
  28784. this._geometry.updateVerticesData(kind, data, updateExtends);
  28785. }
  28786. else {
  28787. this.makeGeometryUnique();
  28788. this.updateVerticesData(kind, data, updateExtends, false);
  28789. }
  28790. return this;
  28791. };
  28792. /**
  28793. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  28794. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  28795. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  28796. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  28797. * Returns the Mesh.
  28798. */
  28799. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  28800. if (computeNormals === void 0) { computeNormals = true; }
  28801. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28802. if (!positions) {
  28803. return this;
  28804. }
  28805. positionFunction(positions);
  28806. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28807. if (computeNormals) {
  28808. var indices = this.getIndices();
  28809. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28810. if (!normals) {
  28811. return this;
  28812. }
  28813. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  28814. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28815. }
  28816. return this;
  28817. };
  28818. /**
  28819. * Creates a un-shared specific occurence of the geometry for the mesh.
  28820. * Returns the Mesh.
  28821. */
  28822. Mesh.prototype.makeGeometryUnique = function () {
  28823. if (!this._geometry) {
  28824. return this;
  28825. }
  28826. var oldGeometry = this._geometry;
  28827. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  28828. oldGeometry.releaseForMesh(this, true);
  28829. geometry.applyToMesh(this);
  28830. return this;
  28831. };
  28832. /**
  28833. * Sets the mesh indices.
  28834. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  28835. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  28836. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  28837. * This method creates a new index buffer each call.
  28838. * Returns the Mesh.
  28839. */
  28840. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  28841. if (totalVertices === void 0) { totalVertices = null; }
  28842. if (updatable === void 0) { updatable = false; }
  28843. if (!this._geometry) {
  28844. var vertexData = new BABYLON.VertexData();
  28845. vertexData.indices = indices;
  28846. var scene = this.getScene();
  28847. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28848. }
  28849. else {
  28850. this._geometry.setIndices(indices, totalVertices, updatable);
  28851. }
  28852. return this;
  28853. };
  28854. /**
  28855. * Update the current index buffer
  28856. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  28857. * Returns the Mesh.
  28858. */
  28859. Mesh.prototype.updateIndices = function (indices, offset) {
  28860. if (!this._geometry) {
  28861. return this;
  28862. }
  28863. this._geometry.updateIndices(indices, offset);
  28864. return this;
  28865. };
  28866. /**
  28867. * Invert the geometry to move from a right handed system to a left handed one.
  28868. * Returns the Mesh.
  28869. */
  28870. Mesh.prototype.toLeftHanded = function () {
  28871. if (!this._geometry) {
  28872. return this;
  28873. }
  28874. this._geometry.toLeftHanded();
  28875. return this;
  28876. };
  28877. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  28878. if (!this._geometry) {
  28879. return this;
  28880. }
  28881. var engine = this.getScene().getEngine();
  28882. // Wireframe
  28883. var indexToBind;
  28884. if (this._unIndexed) {
  28885. indexToBind = null;
  28886. }
  28887. else {
  28888. switch (fillMode) {
  28889. case BABYLON.Material.PointFillMode:
  28890. indexToBind = null;
  28891. break;
  28892. case BABYLON.Material.WireFrameFillMode:
  28893. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  28894. break;
  28895. default:
  28896. case BABYLON.Material.TriangleFillMode:
  28897. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  28898. break;
  28899. }
  28900. }
  28901. // VBOs
  28902. this._geometry._bind(effect, indexToBind);
  28903. return this;
  28904. };
  28905. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  28906. if (alternate === void 0) { alternate = false; }
  28907. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28908. return this;
  28909. }
  28910. this.onBeforeDrawObservable.notifyObservers(this);
  28911. var scene = this.getScene();
  28912. var engine = scene.getEngine();
  28913. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  28914. // or triangles as points
  28915. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  28916. }
  28917. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  28918. // Triangles as wireframe
  28919. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  28920. }
  28921. else {
  28922. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  28923. }
  28924. if (scene._isAlternateRenderingEnabled && !alternate) {
  28925. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  28926. if (!effect || !scene.activeCamera) {
  28927. return this;
  28928. }
  28929. scene._switchToAlternateCameraConfiguration(true);
  28930. this._effectiveMaterial.bindView(effect);
  28931. this._effectiveMaterial.bindViewProjection(effect);
  28932. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  28933. this._draw(subMesh, fillMode, instancesCount, true);
  28934. engine.setViewport(scene.activeCamera.viewport);
  28935. scene._switchToAlternateCameraConfiguration(false);
  28936. this._effectiveMaterial.bindView(effect);
  28937. this._effectiveMaterial.bindViewProjection(effect);
  28938. }
  28939. return this;
  28940. };
  28941. /**
  28942. * Registers for this mesh a javascript function called just before the rendering process.
  28943. * This function is passed the current mesh.
  28944. * Return the Mesh.
  28945. */
  28946. Mesh.prototype.registerBeforeRender = function (func) {
  28947. this.onBeforeRenderObservable.add(func);
  28948. return this;
  28949. };
  28950. /**
  28951. * Disposes a previously registered javascript function called before the rendering.
  28952. * This function is passed the current mesh.
  28953. * Returns the Mesh.
  28954. */
  28955. Mesh.prototype.unregisterBeforeRender = function (func) {
  28956. this.onBeforeRenderObservable.removeCallback(func);
  28957. return this;
  28958. };
  28959. /**
  28960. * Registers for this mesh a javascript function called just after the rendering is complete.
  28961. * This function is passed the current mesh.
  28962. * Returns the Mesh.
  28963. */
  28964. Mesh.prototype.registerAfterRender = function (func) {
  28965. this.onAfterRenderObservable.add(func);
  28966. return this;
  28967. };
  28968. /**
  28969. * Disposes a previously registered javascript function called after the rendering.
  28970. * This function is passed the current mesh.
  28971. * Return the Mesh.
  28972. */
  28973. Mesh.prototype.unregisterAfterRender = function (func) {
  28974. this.onAfterRenderObservable.removeCallback(func);
  28975. return this;
  28976. };
  28977. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  28978. var scene = this.getScene();
  28979. this._batchCache.mustReturn = false;
  28980. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  28981. this._batchCache.visibleInstances[subMeshId] = null;
  28982. if (this._visibleInstances) {
  28983. var currentRenderId = scene.getRenderId();
  28984. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  28985. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  28986. var selfRenderId = this._renderId;
  28987. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  28988. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  28989. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  28990. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  28991. }
  28992. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  28993. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  28994. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  28995. this._batchCache.mustReturn = true;
  28996. return this._batchCache;
  28997. }
  28998. if (currentRenderId !== selfRenderId) {
  28999. this._batchCache.renderSelf[subMeshId] = false;
  29000. }
  29001. }
  29002. this._renderIdForInstances[subMeshId] = currentRenderId;
  29003. }
  29004. return this._batchCache;
  29005. };
  29006. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  29007. var visibleInstances = batch.visibleInstances[subMesh._id];
  29008. if (!visibleInstances) {
  29009. return this;
  29010. }
  29011. var matricesCount = visibleInstances.length + 1;
  29012. var bufferSize = matricesCount * 16 * 4;
  29013. var currentInstancesBufferSize = this._instancesBufferSize;
  29014. var instancesBuffer = this._instancesBuffer;
  29015. while (this._instancesBufferSize < bufferSize) {
  29016. this._instancesBufferSize *= 2;
  29017. }
  29018. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  29019. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  29020. }
  29021. var offset = 0;
  29022. var instancesCount = 0;
  29023. var world = this.getWorldMatrix();
  29024. if (batch.renderSelf[subMesh._id]) {
  29025. world.copyToArray(this._instancesData, offset);
  29026. offset += 16;
  29027. instancesCount++;
  29028. }
  29029. if (visibleInstances) {
  29030. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  29031. var instance = visibleInstances[instanceIndex];
  29032. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  29033. offset += 16;
  29034. instancesCount++;
  29035. }
  29036. }
  29037. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  29038. if (instancesBuffer) {
  29039. instancesBuffer.dispose();
  29040. }
  29041. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  29042. this._instancesBuffer = instancesBuffer;
  29043. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  29044. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  29045. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  29046. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  29047. }
  29048. else {
  29049. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  29050. }
  29051. this._bind(subMesh, effect, fillMode);
  29052. this._draw(subMesh, fillMode, instancesCount);
  29053. engine.unbindInstanceAttributes();
  29054. return this;
  29055. };
  29056. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  29057. var scene = this.getScene();
  29058. var engine = scene.getEngine();
  29059. if (hardwareInstancedRendering) {
  29060. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  29061. }
  29062. else {
  29063. if (batch.renderSelf[subMesh._id]) {
  29064. // Draw
  29065. if (onBeforeDraw) {
  29066. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  29067. }
  29068. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  29069. }
  29070. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  29071. if (visibleInstancesForSubMesh) {
  29072. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  29073. var instance = visibleInstancesForSubMesh[instanceIndex];
  29074. // World
  29075. var world = instance.getWorldMatrix();
  29076. if (onBeforeDraw) {
  29077. onBeforeDraw(true, world, effectiveMaterial);
  29078. }
  29079. // Draw
  29080. this._draw(subMesh, fillMode);
  29081. }
  29082. }
  29083. }
  29084. return this;
  29085. };
  29086. /**
  29087. * Triggers the draw call for the mesh.
  29088. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  29089. * Returns the Mesh.
  29090. */
  29091. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  29092. this.checkOcclusionQuery();
  29093. if (this._isOccluded) {
  29094. return this;
  29095. }
  29096. var scene = this.getScene();
  29097. // Managing instances
  29098. var batch = this._getInstancesRenderList(subMesh._id);
  29099. if (batch.mustReturn) {
  29100. return this;
  29101. }
  29102. // Checking geometry state
  29103. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  29104. return this;
  29105. }
  29106. this.onBeforeRenderObservable.notifyObservers(this);
  29107. var engine = scene.getEngine();
  29108. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  29109. // Material
  29110. var material = subMesh.getMaterial();
  29111. if (!material) {
  29112. return this;
  29113. }
  29114. this._effectiveMaterial = material;
  29115. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  29116. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  29117. return this;
  29118. }
  29119. }
  29120. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  29121. return this;
  29122. }
  29123. // Alpha mode
  29124. if (enableAlphaMode) {
  29125. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  29126. }
  29127. // Outline - step 1
  29128. var savedDepthWrite = engine.getDepthWrite();
  29129. if (this.renderOutline) {
  29130. engine.setDepthWrite(false);
  29131. scene.getOutlineRenderer().render(subMesh, batch);
  29132. engine.setDepthWrite(savedDepthWrite);
  29133. }
  29134. var effect;
  29135. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  29136. effect = subMesh.effect;
  29137. }
  29138. else {
  29139. effect = this._effectiveMaterial.getEffect();
  29140. }
  29141. if (!effect) {
  29142. return this;
  29143. }
  29144. var sideOrientation = this.overrideMaterialSideOrientation;
  29145. if (sideOrientation == null) {
  29146. sideOrientation = this._effectiveMaterial.sideOrientation;
  29147. if (this._getWorldMatrixDeterminant() < 0) {
  29148. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  29149. }
  29150. }
  29151. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  29152. if (this._effectiveMaterial.forceDepthWrite) {
  29153. engine.setDepthWrite(true);
  29154. }
  29155. // Bind
  29156. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  29157. if (!hardwareInstancedRendering) {
  29158. this._bind(subMesh, effect, fillMode);
  29159. }
  29160. var world = this.getWorldMatrix();
  29161. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  29162. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  29163. }
  29164. else {
  29165. this._effectiveMaterial.bind(world, this);
  29166. }
  29167. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  29168. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  29169. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  29170. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  29171. }
  29172. // Draw
  29173. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  29174. // Unbind
  29175. this._effectiveMaterial.unbind();
  29176. // Outline - step 2
  29177. if (this.renderOutline && savedDepthWrite) {
  29178. engine.setDepthWrite(true);
  29179. engine.setColorWrite(false);
  29180. scene.getOutlineRenderer().render(subMesh, batch);
  29181. engine.setColorWrite(true);
  29182. }
  29183. // Overlay
  29184. if (this.renderOverlay) {
  29185. var currentMode = engine.getAlphaMode();
  29186. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  29187. scene.getOutlineRenderer().render(subMesh, batch, true);
  29188. engine.setAlphaMode(currentMode);
  29189. }
  29190. this.onAfterRenderObservable.notifyObservers(this);
  29191. return this;
  29192. };
  29193. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  29194. if (isInstance && effectiveMaterial) {
  29195. effectiveMaterial.bindOnlyWorldMatrix(world);
  29196. }
  29197. };
  29198. /**
  29199. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  29200. */
  29201. Mesh.prototype.getEmittedParticleSystems = function () {
  29202. var results = new Array();
  29203. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  29204. var particleSystem = this.getScene().particleSystems[index];
  29205. if (particleSystem.emitter === this) {
  29206. results.push(particleSystem);
  29207. }
  29208. }
  29209. return results;
  29210. };
  29211. /**
  29212. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  29213. */
  29214. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  29215. var results = new Array();
  29216. var descendants = this.getDescendants();
  29217. descendants.push(this);
  29218. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  29219. var particleSystem = this.getScene().particleSystems[index];
  29220. var emitter = particleSystem.emitter;
  29221. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  29222. results.push(particleSystem);
  29223. }
  29224. }
  29225. return results;
  29226. };
  29227. Mesh.prototype._checkDelayState = function () {
  29228. var scene = this.getScene();
  29229. if (this._geometry) {
  29230. this._geometry.load(scene);
  29231. }
  29232. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29233. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  29234. this._queueLoad(scene);
  29235. }
  29236. return this;
  29237. };
  29238. Mesh.prototype._queueLoad = function (scene) {
  29239. var _this = this;
  29240. scene._addPendingData(this);
  29241. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  29242. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  29243. if (data instanceof ArrayBuffer) {
  29244. _this._delayLoadingFunction(data, _this);
  29245. }
  29246. else {
  29247. _this._delayLoadingFunction(JSON.parse(data), _this);
  29248. }
  29249. _this.instances.forEach(function (instance) {
  29250. instance._syncSubMeshes();
  29251. });
  29252. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  29253. scene._removePendingData(_this);
  29254. }, function () { }, scene.database, getBinaryData);
  29255. return this;
  29256. };
  29257. /**
  29258. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  29259. */
  29260. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  29261. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  29262. return false;
  29263. }
  29264. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  29265. return false;
  29266. }
  29267. this._checkDelayState();
  29268. return true;
  29269. };
  29270. /**
  29271. * Sets the mesh material by the material or multiMaterial `id` property.
  29272. * The material `id` is a string identifying the material or the multiMaterial.
  29273. * This method returns the Mesh.
  29274. */
  29275. Mesh.prototype.setMaterialByID = function (id) {
  29276. var materials = this.getScene().materials;
  29277. var index;
  29278. for (index = materials.length - 1; index > -1; index--) {
  29279. if (materials[index].id === id) {
  29280. this.material = materials[index];
  29281. return this;
  29282. }
  29283. }
  29284. // Multi
  29285. var multiMaterials = this.getScene().multiMaterials;
  29286. for (index = multiMaterials.length - 1; index > -1; index--) {
  29287. if (multiMaterials[index].id === id) {
  29288. this.material = multiMaterials[index];
  29289. return this;
  29290. }
  29291. }
  29292. return this;
  29293. };
  29294. /**
  29295. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  29296. */
  29297. Mesh.prototype.getAnimatables = function () {
  29298. var results = new Array();
  29299. if (this.material) {
  29300. results.push(this.material);
  29301. }
  29302. if (this.skeleton) {
  29303. results.push(this.skeleton);
  29304. }
  29305. return results;
  29306. };
  29307. /**
  29308. * Modifies the mesh geometry according to the passed transformation matrix.
  29309. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  29310. * The mesh normals are modified accordingly the same transformation.
  29311. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  29312. * Note that, under the hood, this method sets a new VertexBuffer each call.
  29313. * Returns the Mesh.
  29314. */
  29315. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  29316. // Position
  29317. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29318. return this;
  29319. }
  29320. var submeshes = this.subMeshes.splice(0);
  29321. this._resetPointsArrayCache();
  29322. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29323. var temp = new Array();
  29324. var index;
  29325. for (index = 0; index < data.length; index += 3) {
  29326. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  29327. }
  29328. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  29329. // Normals
  29330. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29331. return this;
  29332. }
  29333. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29334. temp = [];
  29335. for (index = 0; index < data.length; index += 3) {
  29336. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  29337. }
  29338. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  29339. // flip faces?
  29340. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  29341. this.flipFaces();
  29342. }
  29343. // Restore submeshes
  29344. this.releaseSubMeshes();
  29345. this.subMeshes = submeshes;
  29346. return this;
  29347. };
  29348. /**
  29349. * Modifies the mesh geometry according to its own current World Matrix.
  29350. * The mesh World Matrix is then reset.
  29351. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  29352. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  29353. * Note that, under the hood, this method sets a new VertexBuffer each call.
  29354. * Returns the Mesh.
  29355. */
  29356. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  29357. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  29358. this.scaling.copyFromFloats(1, 1, 1);
  29359. this.position.copyFromFloats(0, 0, 0);
  29360. this.rotation.copyFromFloats(0, 0, 0);
  29361. //only if quaternion is already set
  29362. if (this.rotationQuaternion) {
  29363. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  29364. }
  29365. this._worldMatrix = BABYLON.Matrix.Identity();
  29366. return this;
  29367. };
  29368. Object.defineProperty(Mesh.prototype, "_positions", {
  29369. // Cache
  29370. get: function () {
  29371. if (this._geometry) {
  29372. return this._geometry._positions;
  29373. }
  29374. return null;
  29375. },
  29376. enumerable: true,
  29377. configurable: true
  29378. });
  29379. Mesh.prototype._resetPointsArrayCache = function () {
  29380. if (this._geometry) {
  29381. this._geometry._resetPointsArrayCache();
  29382. }
  29383. return this;
  29384. };
  29385. Mesh.prototype._generatePointsArray = function () {
  29386. if (this._geometry) {
  29387. return this._geometry._generatePointsArray();
  29388. }
  29389. return false;
  29390. };
  29391. /**
  29392. * Returns a new Mesh object generated from the current mesh properties.
  29393. * This method must not get confused with createInstance().
  29394. * The parameter `name` is a string, the name given to the new mesh.
  29395. * The optional parameter `newParent` can be any Node object (default `null`).
  29396. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  29397. * 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.
  29398. */
  29399. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  29400. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  29401. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  29402. };
  29403. /**
  29404. * Releases resources associated with this mesh.
  29405. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  29406. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  29407. */
  29408. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  29409. var _this = this;
  29410. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  29411. this.morphTargetManager = null;
  29412. if (this._geometry) {
  29413. this._geometry.releaseForMesh(this, true);
  29414. }
  29415. // Sources
  29416. var meshes = this.getScene().meshes;
  29417. meshes.forEach(function (abstractMesh) {
  29418. var mesh = abstractMesh;
  29419. if (mesh._source && mesh._source === _this) {
  29420. mesh._source = null;
  29421. }
  29422. });
  29423. this._source = null;
  29424. // Instances
  29425. if (this._instancesBuffer) {
  29426. this._instancesBuffer.dispose();
  29427. this._instancesBuffer = null;
  29428. }
  29429. while (this.instances.length) {
  29430. this.instances[0].dispose();
  29431. }
  29432. // Effect layers.
  29433. var effectLayers = this.getScene().effectLayers;
  29434. for (var i = 0; i < effectLayers.length; i++) {
  29435. var effectLayer = effectLayers[i];
  29436. if (effectLayer) {
  29437. effectLayer._disposeMesh(this);
  29438. }
  29439. }
  29440. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  29441. };
  29442. /**
  29443. * Modifies the mesh geometry according to a displacement map.
  29444. * 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.
  29445. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  29446. * This method returns nothing.
  29447. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  29448. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  29449. * 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.
  29450. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  29451. * The parameter `uvScale` is an optional vector2 used to scale UV.
  29452. *
  29453. * Returns the Mesh.
  29454. */
  29455. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  29456. var _this = this;
  29457. var scene = this.getScene();
  29458. var onload = function (img) {
  29459. // Getting height map data
  29460. var canvas = document.createElement("canvas");
  29461. var context = canvas.getContext("2d");
  29462. var heightMapWidth = img.width;
  29463. var heightMapHeight = img.height;
  29464. canvas.width = heightMapWidth;
  29465. canvas.height = heightMapHeight;
  29466. context.drawImage(img, 0, 0);
  29467. // Create VertexData from map data
  29468. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  29469. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  29470. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  29471. //execute success callback, if set
  29472. if (onSuccess) {
  29473. onSuccess(_this);
  29474. }
  29475. };
  29476. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  29477. return this;
  29478. };
  29479. /**
  29480. * Modifies the mesh geometry according to a displacementMap buffer.
  29481. * 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.
  29482. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  29483. * This method returns nothing.
  29484. * 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.
  29485. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  29486. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  29487. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  29488. * The parameter `uvScale` is an optional vector2 used to scale UV.
  29489. *
  29490. * Returns the Mesh.
  29491. */
  29492. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  29493. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  29494. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  29495. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29496. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  29497. return this;
  29498. }
  29499. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29500. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29501. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29502. var position = BABYLON.Vector3.Zero();
  29503. var normal = BABYLON.Vector3.Zero();
  29504. var uv = BABYLON.Vector2.Zero();
  29505. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  29506. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  29507. for (var index = 0; index < positions.length; index += 3) {
  29508. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  29509. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  29510. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  29511. // Compute height
  29512. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  29513. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  29514. var pos = (u + v * heightMapWidth) * 4;
  29515. var r = buffer[pos] / 255.0;
  29516. var g = buffer[pos + 1] / 255.0;
  29517. var b = buffer[pos + 2] / 255.0;
  29518. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  29519. normal.normalize();
  29520. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  29521. position = position.add(normal);
  29522. position.toArray(positions, index);
  29523. }
  29524. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  29525. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  29526. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  29527. return this;
  29528. };
  29529. /**
  29530. * Modify the mesh to get a flat shading rendering.
  29531. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  29532. * This method returns the Mesh.
  29533. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  29534. */
  29535. Mesh.prototype.convertToFlatShadedMesh = function () {
  29536. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  29537. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29538. var kinds = this.getVerticesDataKinds();
  29539. var vbs = {};
  29540. var data = {};
  29541. var newdata = {};
  29542. var updatableNormals = false;
  29543. var kindIndex;
  29544. var kind;
  29545. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29546. kind = kinds[kindIndex];
  29547. var vertexBuffer = this.getVertexBuffer(kind);
  29548. if (kind === BABYLON.VertexBuffer.NormalKind) {
  29549. updatableNormals = vertexBuffer.isUpdatable();
  29550. kinds.splice(kindIndex, 1);
  29551. kindIndex--;
  29552. continue;
  29553. }
  29554. vbs[kind] = vertexBuffer;
  29555. data[kind] = vbs[kind].getData();
  29556. newdata[kind] = [];
  29557. }
  29558. // Save previous submeshes
  29559. var previousSubmeshes = this.subMeshes.slice(0);
  29560. var indices = this.getIndices();
  29561. var totalIndices = this.getTotalIndices();
  29562. // Generating unique vertices per face
  29563. var index;
  29564. for (index = 0; index < totalIndices; index++) {
  29565. var vertexIndex = indices[index];
  29566. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29567. kind = kinds[kindIndex];
  29568. var stride = vbs[kind].getStrideSize();
  29569. for (var offset = 0; offset < stride; offset++) {
  29570. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29571. }
  29572. }
  29573. }
  29574. // Updating faces & normal
  29575. var normals = [];
  29576. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  29577. for (index = 0; index < totalIndices; index += 3) {
  29578. indices[index] = index;
  29579. indices[index + 1] = index + 1;
  29580. indices[index + 2] = index + 2;
  29581. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  29582. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  29583. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  29584. var p1p2 = p1.subtract(p2);
  29585. var p3p2 = p3.subtract(p2);
  29586. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  29587. // Store same normals for every vertex
  29588. for (var localIndex = 0; localIndex < 3; localIndex++) {
  29589. normals.push(normal.x);
  29590. normals.push(normal.y);
  29591. normals.push(normal.z);
  29592. }
  29593. }
  29594. this.setIndices(indices);
  29595. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  29596. // Updating vertex buffers
  29597. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29598. kind = kinds[kindIndex];
  29599. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29600. }
  29601. // Updating submeshes
  29602. this.releaseSubMeshes();
  29603. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29604. var previousOne = previousSubmeshes[submeshIndex];
  29605. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29606. }
  29607. this.synchronizeInstances();
  29608. return this;
  29609. };
  29610. /**
  29611. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  29612. * In other words, more vertices, no more indices and a single bigger VBO.
  29613. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  29614. * Returns the Mesh.
  29615. */
  29616. Mesh.prototype.convertToUnIndexedMesh = function () {
  29617. /// <summary>Remove indices by unfolding faces into buffers</summary>
  29618. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29619. var kinds = this.getVerticesDataKinds();
  29620. var vbs = {};
  29621. var data = {};
  29622. var newdata = {};
  29623. var kindIndex;
  29624. var kind;
  29625. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29626. kind = kinds[kindIndex];
  29627. var vertexBuffer = this.getVertexBuffer(kind);
  29628. vbs[kind] = vertexBuffer;
  29629. data[kind] = vbs[kind].getData();
  29630. newdata[kind] = [];
  29631. }
  29632. // Save previous submeshes
  29633. var previousSubmeshes = this.subMeshes.slice(0);
  29634. var indices = this.getIndices();
  29635. var totalIndices = this.getTotalIndices();
  29636. // Generating unique vertices per face
  29637. var index;
  29638. for (index = 0; index < totalIndices; index++) {
  29639. var vertexIndex = indices[index];
  29640. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29641. kind = kinds[kindIndex];
  29642. var stride = vbs[kind].getStrideSize();
  29643. for (var offset = 0; offset < stride; offset++) {
  29644. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29645. }
  29646. }
  29647. }
  29648. // Updating indices
  29649. for (index = 0; index < totalIndices; index += 3) {
  29650. indices[index] = index;
  29651. indices[index + 1] = index + 1;
  29652. indices[index + 2] = index + 2;
  29653. }
  29654. this.setIndices(indices);
  29655. // Updating vertex buffers
  29656. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29657. kind = kinds[kindIndex];
  29658. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29659. }
  29660. // Updating submeshes
  29661. this.releaseSubMeshes();
  29662. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29663. var previousOne = previousSubmeshes[submeshIndex];
  29664. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29665. }
  29666. this._unIndexed = true;
  29667. this.synchronizeInstances();
  29668. return this;
  29669. };
  29670. /**
  29671. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  29672. * This method returns the Mesh.
  29673. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  29674. */
  29675. Mesh.prototype.flipFaces = function (flipNormals) {
  29676. if (flipNormals === void 0) { flipNormals = false; }
  29677. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  29678. var i;
  29679. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  29680. for (i = 0; i < vertex_data.normals.length; i++) {
  29681. vertex_data.normals[i] *= -1;
  29682. }
  29683. }
  29684. if (vertex_data.indices) {
  29685. var temp;
  29686. for (i = 0; i < vertex_data.indices.length; i += 3) {
  29687. // reassign indices
  29688. temp = vertex_data.indices[i + 1];
  29689. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  29690. vertex_data.indices[i + 2] = temp;
  29691. }
  29692. }
  29693. vertex_data.applyToMesh(this);
  29694. return this;
  29695. };
  29696. // Instances
  29697. /**
  29698. * Creates a new InstancedMesh object from the mesh model.
  29699. * An instance shares the same properties and the same material than its model.
  29700. * Only these properties of each instance can then be set individually :
  29701. * - position
  29702. * - rotation
  29703. * - rotationQuaternion
  29704. * - setPivotMatrix
  29705. * - scaling
  29706. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  29707. * Warning : this method is not supported for Line mesh and LineSystem
  29708. */
  29709. Mesh.prototype.createInstance = function (name) {
  29710. return new BABYLON.InstancedMesh(name, this);
  29711. };
  29712. /**
  29713. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  29714. * After this call, all the mesh instances have the same submeshes than the current mesh.
  29715. * This method returns the Mesh.
  29716. */
  29717. Mesh.prototype.synchronizeInstances = function () {
  29718. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  29719. var instance = this.instances[instanceIndex];
  29720. instance._syncSubMeshes();
  29721. }
  29722. return this;
  29723. };
  29724. /**
  29725. * Simplify the mesh according to the given array of settings.
  29726. * Function will return immediately and will simplify async. It returns the Mesh.
  29727. * @param settings a collection of simplification settings.
  29728. * @param parallelProcessing should all levels calculate parallel or one after the other.
  29729. * @param type the type of simplification to run.
  29730. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  29731. */
  29732. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  29733. if (parallelProcessing === void 0) { parallelProcessing = true; }
  29734. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  29735. this.getScene().simplificationQueue.addTask({
  29736. settings: settings,
  29737. parallelProcessing: parallelProcessing,
  29738. mesh: this,
  29739. simplificationType: simplificationType,
  29740. successCallback: successCallback
  29741. });
  29742. return this;
  29743. };
  29744. /**
  29745. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  29746. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  29747. * This should be used together with the simplification to avoid disappearing triangles.
  29748. * Returns the Mesh.
  29749. * @param successCallback an optional success callback to be called after the optimization finished.
  29750. */
  29751. Mesh.prototype.optimizeIndices = function (successCallback) {
  29752. var _this = this;
  29753. var indices = this.getIndices();
  29754. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29755. if (!positions || !indices) {
  29756. return this;
  29757. }
  29758. var vectorPositions = new Array();
  29759. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  29760. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  29761. }
  29762. var dupes = new Array();
  29763. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  29764. var realPos = vectorPositions.length - 1 - iteration;
  29765. var testedPosition = vectorPositions[realPos];
  29766. for (var j = 0; j < realPos; ++j) {
  29767. var againstPosition = vectorPositions[j];
  29768. if (testedPosition.equals(againstPosition)) {
  29769. dupes[realPos] = j;
  29770. break;
  29771. }
  29772. }
  29773. }, function () {
  29774. for (var i = 0; i < indices.length; ++i) {
  29775. indices[i] = dupes[indices[i]] || indices[i];
  29776. }
  29777. //indices are now reordered
  29778. var originalSubMeshes = _this.subMeshes.slice(0);
  29779. _this.setIndices(indices);
  29780. _this.subMeshes = originalSubMeshes;
  29781. if (successCallback) {
  29782. successCallback(_this);
  29783. }
  29784. });
  29785. return this;
  29786. };
  29787. Mesh.prototype.serialize = function (serializationObject) {
  29788. serializationObject.name = this.name;
  29789. serializationObject.id = this.id;
  29790. serializationObject.type = this.getClassName();
  29791. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29792. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29793. }
  29794. serializationObject.position = this.position.asArray();
  29795. if (this.rotationQuaternion) {
  29796. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  29797. }
  29798. else if (this.rotation) {
  29799. serializationObject.rotation = this.rotation.asArray();
  29800. }
  29801. serializationObject.scaling = this.scaling.asArray();
  29802. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  29803. serializationObject.isEnabled = this.isEnabled(false);
  29804. serializationObject.isVisible = this.isVisible;
  29805. serializationObject.infiniteDistance = this.infiniteDistance;
  29806. serializationObject.pickable = this.isPickable;
  29807. serializationObject.receiveShadows = this.receiveShadows;
  29808. serializationObject.billboardMode = this.billboardMode;
  29809. serializationObject.visibility = this.visibility;
  29810. serializationObject.checkCollisions = this.checkCollisions;
  29811. serializationObject.isBlocker = this.isBlocker;
  29812. // Parent
  29813. if (this.parent) {
  29814. serializationObject.parentId = this.parent.id;
  29815. }
  29816. // Geometry
  29817. serializationObject.isUnIndexed = this.isUnIndexed;
  29818. var geometry = this._geometry;
  29819. if (geometry) {
  29820. var geometryId = geometry.id;
  29821. serializationObject.geometryId = geometryId;
  29822. // SubMeshes
  29823. serializationObject.subMeshes = [];
  29824. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  29825. var subMesh = this.subMeshes[subIndex];
  29826. serializationObject.subMeshes.push({
  29827. materialIndex: subMesh.materialIndex,
  29828. verticesStart: subMesh.verticesStart,
  29829. verticesCount: subMesh.verticesCount,
  29830. indexStart: subMesh.indexStart,
  29831. indexCount: subMesh.indexCount
  29832. });
  29833. }
  29834. }
  29835. // Material
  29836. if (this.material) {
  29837. serializationObject.materialId = this.material.id;
  29838. }
  29839. else {
  29840. this.material = null;
  29841. }
  29842. // Morph targets
  29843. if (this.morphTargetManager) {
  29844. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  29845. }
  29846. // Skeleton
  29847. if (this.skeleton) {
  29848. serializationObject.skeletonId = this.skeleton.id;
  29849. }
  29850. // Physics
  29851. //TODO implement correct serialization for physics impostors.
  29852. var impostor = this.getPhysicsImpostor();
  29853. if (impostor) {
  29854. serializationObject.physicsMass = impostor.getParam("mass");
  29855. serializationObject.physicsFriction = impostor.getParam("friction");
  29856. serializationObject.physicsRestitution = impostor.getParam("mass");
  29857. serializationObject.physicsImpostor = impostor.type;
  29858. }
  29859. // Metadata
  29860. if (this.metadata) {
  29861. serializationObject.metadata = this.metadata;
  29862. }
  29863. // Instances
  29864. serializationObject.instances = [];
  29865. for (var index = 0; index < this.instances.length; index++) {
  29866. var instance = this.instances[index];
  29867. var serializationInstance = {
  29868. name: instance.name,
  29869. id: instance.id,
  29870. position: instance.position.asArray(),
  29871. scaling: instance.scaling.asArray()
  29872. };
  29873. if (instance.rotationQuaternion) {
  29874. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  29875. }
  29876. else if (instance.rotation) {
  29877. serializationInstance.rotation = instance.rotation.asArray();
  29878. }
  29879. serializationObject.instances.push(serializationInstance);
  29880. // Animations
  29881. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  29882. serializationInstance.ranges = instance.serializeAnimationRanges();
  29883. }
  29884. //
  29885. // Animations
  29886. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29887. serializationObject.ranges = this.serializeAnimationRanges();
  29888. // Layer mask
  29889. serializationObject.layerMask = this.layerMask;
  29890. // Alpha
  29891. serializationObject.alphaIndex = this.alphaIndex;
  29892. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  29893. // Overlay
  29894. serializationObject.overlayAlpha = this.overlayAlpha;
  29895. serializationObject.overlayColor = this.overlayColor.asArray();
  29896. serializationObject.renderOverlay = this.renderOverlay;
  29897. // Fog
  29898. serializationObject.applyFog = this.applyFog;
  29899. // Action Manager
  29900. if (this.actionManager) {
  29901. serializationObject.actions = this.actionManager.serialize(this.name);
  29902. }
  29903. };
  29904. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  29905. if (!this.geometry) {
  29906. return;
  29907. }
  29908. this._markSubMeshesAsAttributesDirty();
  29909. var morphTargetManager = this._morphTargetManager;
  29910. if (morphTargetManager && morphTargetManager.vertexCount) {
  29911. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  29912. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  29913. this.morphTargetManager = null;
  29914. return;
  29915. }
  29916. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  29917. var morphTarget = morphTargetManager.getActiveTarget(index);
  29918. var positions = morphTarget.getPositions();
  29919. if (!positions) {
  29920. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  29921. return;
  29922. }
  29923. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  29924. var normals = morphTarget.getNormals();
  29925. if (normals) {
  29926. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  29927. }
  29928. var tangents = morphTarget.getTangents();
  29929. if (tangents) {
  29930. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  29931. }
  29932. }
  29933. }
  29934. else {
  29935. var index = 0;
  29936. // Positions
  29937. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  29938. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  29939. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  29940. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  29941. }
  29942. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  29943. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  29944. }
  29945. index++;
  29946. }
  29947. }
  29948. };
  29949. // Statics
  29950. /**
  29951. * Returns a new Mesh object parsed from the source provided.
  29952. * The parameter `parsedMesh` is the source.
  29953. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  29954. */
  29955. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  29956. var mesh;
  29957. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  29958. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  29959. }
  29960. else {
  29961. mesh = new Mesh(parsedMesh.name, scene);
  29962. }
  29963. mesh.id = parsedMesh.id;
  29964. if (BABYLON.Tags) {
  29965. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  29966. }
  29967. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  29968. if (parsedMesh.metadata !== undefined) {
  29969. mesh.metadata = parsedMesh.metadata;
  29970. }
  29971. if (parsedMesh.rotationQuaternion) {
  29972. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  29973. }
  29974. else if (parsedMesh.rotation) {
  29975. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  29976. }
  29977. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  29978. if (parsedMesh.localMatrix) {
  29979. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  29980. }
  29981. else if (parsedMesh.pivotMatrix) {
  29982. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  29983. }
  29984. mesh.setEnabled(parsedMesh.isEnabled);
  29985. mesh.isVisible = parsedMesh.isVisible;
  29986. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  29987. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  29988. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  29989. if (parsedMesh.applyFog !== undefined) {
  29990. mesh.applyFog = parsedMesh.applyFog;
  29991. }
  29992. if (parsedMesh.pickable !== undefined) {
  29993. mesh.isPickable = parsedMesh.pickable;
  29994. }
  29995. if (parsedMesh.alphaIndex !== undefined) {
  29996. mesh.alphaIndex = parsedMesh.alphaIndex;
  29997. }
  29998. mesh.receiveShadows = parsedMesh.receiveShadows;
  29999. mesh.billboardMode = parsedMesh.billboardMode;
  30000. if (parsedMesh.visibility !== undefined) {
  30001. mesh.visibility = parsedMesh.visibility;
  30002. }
  30003. mesh.checkCollisions = parsedMesh.checkCollisions;
  30004. if (parsedMesh.isBlocker !== undefined) {
  30005. mesh.isBlocker = parsedMesh.isBlocker;
  30006. }
  30007. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  30008. // freezeWorldMatrix
  30009. if (parsedMesh.freezeWorldMatrix) {
  30010. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  30011. }
  30012. // Parent
  30013. if (parsedMesh.parentId) {
  30014. mesh._waitingParentId = parsedMesh.parentId;
  30015. }
  30016. // Actions
  30017. if (parsedMesh.actions !== undefined) {
  30018. mesh._waitingActions = parsedMesh.actions;
  30019. }
  30020. // Overlay
  30021. if (parsedMesh.overlayAlpha !== undefined) {
  30022. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  30023. }
  30024. if (parsedMesh.overlayColor !== undefined) {
  30025. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  30026. }
  30027. if (parsedMesh.renderOverlay !== undefined) {
  30028. mesh.renderOverlay = parsedMesh.renderOverlay;
  30029. }
  30030. // Geometry
  30031. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  30032. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  30033. if (parsedMesh.delayLoadingFile) {
  30034. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30035. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  30036. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  30037. if (parsedMesh._binaryInfo) {
  30038. mesh._binaryInfo = parsedMesh._binaryInfo;
  30039. }
  30040. mesh._delayInfo = [];
  30041. if (parsedMesh.hasUVs) {
  30042. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  30043. }
  30044. if (parsedMesh.hasUVs2) {
  30045. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  30046. }
  30047. if (parsedMesh.hasUVs3) {
  30048. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  30049. }
  30050. if (parsedMesh.hasUVs4) {
  30051. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  30052. }
  30053. if (parsedMesh.hasUVs5) {
  30054. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  30055. }
  30056. if (parsedMesh.hasUVs6) {
  30057. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  30058. }
  30059. if (parsedMesh.hasColors) {
  30060. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  30061. }
  30062. if (parsedMesh.hasMatricesIndices) {
  30063. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  30064. }
  30065. if (parsedMesh.hasMatricesWeights) {
  30066. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  30067. }
  30068. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  30069. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  30070. mesh._checkDelayState();
  30071. }
  30072. }
  30073. else {
  30074. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  30075. }
  30076. // Material
  30077. if (parsedMesh.materialId) {
  30078. mesh.setMaterialByID(parsedMesh.materialId);
  30079. }
  30080. else {
  30081. mesh.material = null;
  30082. }
  30083. // Morph targets
  30084. if (parsedMesh.morphTargetManagerId > -1) {
  30085. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  30086. }
  30087. // Skeleton
  30088. if (parsedMesh.skeletonId > -1) {
  30089. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  30090. if (parsedMesh.numBoneInfluencers) {
  30091. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  30092. }
  30093. }
  30094. // Animations
  30095. if (parsedMesh.animations) {
  30096. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  30097. var parsedAnimation = parsedMesh.animations[animationIndex];
  30098. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30099. }
  30100. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  30101. }
  30102. if (parsedMesh.autoAnimate) {
  30103. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  30104. }
  30105. // Layer Mask
  30106. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  30107. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  30108. }
  30109. else {
  30110. mesh.layerMask = 0x0FFFFFFF;
  30111. }
  30112. // Physics
  30113. if (parsedMesh.physicsImpostor) {
  30114. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  30115. mass: parsedMesh.physicsMass,
  30116. friction: parsedMesh.physicsFriction,
  30117. restitution: parsedMesh.physicsRestitution
  30118. }, scene);
  30119. }
  30120. // Instances
  30121. if (parsedMesh.instances) {
  30122. for (var index = 0; index < parsedMesh.instances.length; index++) {
  30123. var parsedInstance = parsedMesh.instances[index];
  30124. var instance = mesh.createInstance(parsedInstance.name);
  30125. if (parsedInstance.id) {
  30126. instance.id = parsedInstance.id;
  30127. }
  30128. if (BABYLON.Tags) {
  30129. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  30130. }
  30131. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  30132. if (parsedInstance.parentId) {
  30133. instance._waitingParentId = parsedInstance.parentId;
  30134. }
  30135. if (parsedInstance.rotationQuaternion) {
  30136. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  30137. }
  30138. else if (parsedInstance.rotation) {
  30139. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  30140. }
  30141. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  30142. instance.checkCollisions = mesh.checkCollisions;
  30143. if (parsedMesh.animations) {
  30144. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  30145. parsedAnimation = parsedMesh.animations[animationIndex];
  30146. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30147. }
  30148. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  30149. }
  30150. }
  30151. }
  30152. return mesh;
  30153. };
  30154. /**
  30155. * Creates a ribbon mesh.
  30156. * Please consider using the same method from the MeshBuilder class instead.
  30157. * 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.
  30158. *
  30159. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  30160. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  30161. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  30162. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  30163. * 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.
  30164. * 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.
  30165. * 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
  30166. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30167. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30168. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30169. */
  30170. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  30171. if (closeArray === void 0) { closeArray = false; }
  30172. if (updatable === void 0) { updatable = false; }
  30173. return BABYLON.MeshBuilder.CreateRibbon(name, {
  30174. pathArray: pathArray,
  30175. closeArray: closeArray,
  30176. closePath: closePath,
  30177. offset: offset,
  30178. updatable: updatable,
  30179. sideOrientation: sideOrientation,
  30180. instance: instance
  30181. }, scene);
  30182. };
  30183. /**
  30184. * Creates a plane polygonal mesh. By default, this is a disc.
  30185. * Please consider using the same method from the MeshBuilder class instead.
  30186. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  30187. * 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.
  30188. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30189. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30190. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30191. */
  30192. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  30193. if (scene === void 0) { scene = null; }
  30194. var options = {
  30195. radius: radius,
  30196. tessellation: tessellation,
  30197. sideOrientation: sideOrientation,
  30198. updatable: updatable
  30199. };
  30200. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  30201. };
  30202. /**
  30203. * Creates a box mesh.
  30204. * Please consider using the same method from the MeshBuilder class instead.
  30205. * The parameter `size` sets the size (float) of each box side (default 1).
  30206. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30207. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30208. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30209. */
  30210. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  30211. if (scene === void 0) { scene = null; }
  30212. var options = {
  30213. size: size,
  30214. sideOrientation: sideOrientation,
  30215. updatable: updatable
  30216. };
  30217. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  30218. };
  30219. /**
  30220. * Creates a sphere mesh.
  30221. * Please consider using the same method from the MeshBuilder class instead.
  30222. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  30223. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  30224. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30225. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30226. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30227. */
  30228. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  30229. var options = {
  30230. segments: segments,
  30231. diameterX: diameter,
  30232. diameterY: diameter,
  30233. diameterZ: diameter,
  30234. sideOrientation: sideOrientation,
  30235. updatable: updatable
  30236. };
  30237. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  30238. };
  30239. /**
  30240. * Creates a cylinder or a cone mesh.
  30241. * Please consider using the same method from the MeshBuilder class instead.
  30242. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  30243. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  30244. * 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.
  30245. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  30246. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  30247. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30248. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30249. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30250. */
  30251. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  30252. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  30253. if (scene !== undefined) {
  30254. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  30255. updatable = scene;
  30256. }
  30257. scene = subdivisions;
  30258. subdivisions = 1;
  30259. }
  30260. var options = {
  30261. height: height,
  30262. diameterTop: diameterTop,
  30263. diameterBottom: diameterBottom,
  30264. tessellation: tessellation,
  30265. subdivisions: subdivisions,
  30266. sideOrientation: sideOrientation,
  30267. updatable: updatable
  30268. };
  30269. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  30270. };
  30271. // Torus (Code from SharpDX.org)
  30272. /**
  30273. * Creates a torus mesh.
  30274. * Please consider using the same method from the MeshBuilder class instead.
  30275. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  30276. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  30277. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  30278. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30279. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30280. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30281. */
  30282. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  30283. var options = {
  30284. diameter: diameter,
  30285. thickness: thickness,
  30286. tessellation: tessellation,
  30287. sideOrientation: sideOrientation,
  30288. updatable: updatable
  30289. };
  30290. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  30291. };
  30292. /**
  30293. * Creates a torus knot mesh.
  30294. * Please consider using the same method from the MeshBuilder class instead.
  30295. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  30296. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  30297. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  30298. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  30299. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30300. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30301. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30302. */
  30303. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  30304. var options = {
  30305. radius: radius,
  30306. tube: tube,
  30307. radialSegments: radialSegments,
  30308. tubularSegments: tubularSegments,
  30309. p: p,
  30310. q: q,
  30311. sideOrientation: sideOrientation,
  30312. updatable: updatable
  30313. };
  30314. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  30315. };
  30316. /**
  30317. * Creates a line mesh.
  30318. * Please consider using the same method from the MeshBuilder class instead.
  30319. * 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.
  30320. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  30321. * The parameter `points` is an array successive Vector3.
  30322. * 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
  30323. * When updating an instance, remember that only point positions can change, not the number of points.
  30324. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30325. */
  30326. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  30327. if (scene === void 0) { scene = null; }
  30328. if (updatable === void 0) { updatable = false; }
  30329. if (instance === void 0) { instance = null; }
  30330. var options = {
  30331. points: points,
  30332. updatable: updatable,
  30333. instance: instance
  30334. };
  30335. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  30336. };
  30337. /**
  30338. * Creates a dashed line mesh.
  30339. * Please consider using the same method from the MeshBuilder class instead.
  30340. * 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.
  30341. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  30342. * The parameter `points` is an array successive Vector3.
  30343. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  30344. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  30345. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  30346. * 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
  30347. * When updating an instance, remember that only point positions can change, not the number of points.
  30348. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30349. */
  30350. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  30351. if (scene === void 0) { scene = null; }
  30352. var options = {
  30353. points: points,
  30354. dashSize: dashSize,
  30355. gapSize: gapSize,
  30356. dashNb: dashNb,
  30357. updatable: updatable,
  30358. instance: instance
  30359. };
  30360. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  30361. };
  30362. /**
  30363. * Creates a polygon mesh.
  30364. * Please consider using the same method from the MeshBuilder class instead.
  30365. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  30366. * 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.
  30367. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30368. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30369. * Remember you can only change the shape positions, not their number when updating a polygon.
  30370. */
  30371. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  30372. var options = {
  30373. shape: shape,
  30374. holes: holes,
  30375. updatable: updatable,
  30376. sideOrientation: sideOrientation
  30377. };
  30378. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  30379. };
  30380. /**
  30381. * Creates an extruded polygon mesh, with depth in the Y direction.
  30382. * Please consider using the same method from the MeshBuilder class instead.
  30383. */
  30384. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  30385. var options = {
  30386. shape: shape,
  30387. holes: holes,
  30388. depth: depth,
  30389. updatable: updatable,
  30390. sideOrientation: sideOrientation
  30391. };
  30392. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  30393. };
  30394. /**
  30395. * Creates an extruded shape mesh.
  30396. * 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.
  30397. * Please consider using the same method from the MeshBuilder class instead.
  30398. *
  30399. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  30400. * 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
  30401. * extruded along the Z axis.
  30402. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  30403. * 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.
  30404. * The parameter `scale` (float, default 1) is the value to scale the shape.
  30405. * 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
  30406. * 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
  30407. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  30408. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30409. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30410. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30411. */
  30412. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  30413. if (scene === void 0) { scene = null; }
  30414. var options = {
  30415. shape: shape,
  30416. path: path,
  30417. scale: scale,
  30418. rotation: rotation,
  30419. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  30420. sideOrientation: sideOrientation,
  30421. instance: instance,
  30422. updatable: updatable
  30423. };
  30424. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  30425. };
  30426. /**
  30427. * Creates an custom extruded shape mesh.
  30428. * 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.
  30429. * Please consider using the same method from the MeshBuilder class instead.
  30430. *
  30431. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  30432. * 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
  30433. * extruded along the Z axis.
  30434. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  30435. * 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
  30436. * and the distance of this point from the begining of the path :
  30437. * ```javascript
  30438. * var rotationFunction = function(i, distance) {
  30439. * // do things
  30440. * return rotationValue; }
  30441. * ```
  30442. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  30443. * 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
  30444. * and the distance of this point from the begining of the path :
  30445. * ```javascript
  30446. * var scaleFunction = function(i, distance) {
  30447. * // do things
  30448. * return scaleValue;}
  30449. * ```
  30450. * It must returns a float value that will be the scale value applied to the shape on each path point.
  30451. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  30452. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  30453. * 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
  30454. * 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
  30455. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  30456. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30457. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30458. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30459. */
  30460. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  30461. var options = {
  30462. shape: shape,
  30463. path: path,
  30464. scaleFunction: scaleFunction,
  30465. rotationFunction: rotationFunction,
  30466. ribbonCloseArray: ribbonCloseArray,
  30467. ribbonClosePath: ribbonClosePath,
  30468. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  30469. sideOrientation: sideOrientation,
  30470. instance: instance,
  30471. updatable: updatable
  30472. };
  30473. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  30474. };
  30475. /**
  30476. * Creates lathe mesh.
  30477. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  30478. * Please consider using the same method from the MeshBuilder class instead.
  30479. * 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
  30480. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  30481. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  30482. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  30483. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30484. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30485. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30486. */
  30487. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  30488. var options = {
  30489. shape: shape,
  30490. radius: radius,
  30491. tessellation: tessellation,
  30492. sideOrientation: sideOrientation,
  30493. updatable: updatable
  30494. };
  30495. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  30496. };
  30497. /**
  30498. * Creates a plane mesh.
  30499. * Please consider using the same method from the MeshBuilder class instead.
  30500. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  30501. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30502. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30503. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30504. */
  30505. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  30506. var options = {
  30507. size: size,
  30508. width: size,
  30509. height: size,
  30510. sideOrientation: sideOrientation,
  30511. updatable: updatable
  30512. };
  30513. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  30514. };
  30515. /**
  30516. * Creates a ground mesh.
  30517. * Please consider using the same method from the MeshBuilder class instead.
  30518. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  30519. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  30520. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30521. */
  30522. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  30523. var options = {
  30524. width: width,
  30525. height: height,
  30526. subdivisions: subdivisions,
  30527. updatable: updatable
  30528. };
  30529. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  30530. };
  30531. /**
  30532. * Creates a tiled ground mesh.
  30533. * Please consider using the same method from the MeshBuilder class instead.
  30534. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  30535. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  30536. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  30537. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  30538. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  30539. * numbers of subdivisions on the ground width and height of each tile.
  30540. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30541. */
  30542. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  30543. var options = {
  30544. xmin: xmin,
  30545. zmin: zmin,
  30546. xmax: xmax,
  30547. zmax: zmax,
  30548. subdivisions: subdivisions,
  30549. precision: precision,
  30550. updatable: updatable
  30551. };
  30552. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  30553. };
  30554. /**
  30555. * Creates a ground mesh from a height map.
  30556. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  30557. * Please consider using the same method from the MeshBuilder class instead.
  30558. * The parameter `url` sets the URL of the height map image resource.
  30559. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  30560. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  30561. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  30562. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  30563. * 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).
  30564. * This function is passed the newly built mesh :
  30565. * ```javascript
  30566. * function(mesh) { // do things
  30567. * return; }
  30568. * ```
  30569. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30570. */
  30571. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  30572. var options = {
  30573. width: width,
  30574. height: height,
  30575. subdivisions: subdivisions,
  30576. minHeight: minHeight,
  30577. maxHeight: maxHeight,
  30578. updatable: updatable,
  30579. onReady: onReady
  30580. };
  30581. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  30582. };
  30583. /**
  30584. * Creates a tube mesh.
  30585. * 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.
  30586. * Please consider using the same method from the MeshBuilder class instead.
  30587. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  30588. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  30589. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  30590. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  30591. * 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.
  30592. * It must return a radius value (positive float) :
  30593. * ```javascript
  30594. * var radiusFunction = function(i, distance) {
  30595. * // do things
  30596. * return radius; }
  30597. * ```
  30598. * 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
  30599. * 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
  30600. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30601. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30602. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30603. */
  30604. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  30605. var options = {
  30606. path: path,
  30607. radius: radius,
  30608. tessellation: tessellation,
  30609. radiusFunction: radiusFunction,
  30610. arc: 1,
  30611. cap: cap,
  30612. updatable: updatable,
  30613. sideOrientation: sideOrientation,
  30614. instance: instance
  30615. };
  30616. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  30617. };
  30618. /**
  30619. * Creates a polyhedron mesh.
  30620. * Please consider using the same method from the MeshBuilder class instead.
  30621. * 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
  30622. * to choose the wanted type.
  30623. * The parameter `size` (positive float, default 1) sets the polygon size.
  30624. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  30625. * 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`.
  30626. * 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
  30627. * 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)`).
  30628. * 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
  30629. * 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.
  30630. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30631. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30632. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30633. */
  30634. Mesh.CreatePolyhedron = function (name, options, scene) {
  30635. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  30636. };
  30637. /**
  30638. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  30639. * Please consider using the same method from the MeshBuilder class instead.
  30640. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  30641. * 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`).
  30642. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  30643. * 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.
  30644. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30645. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30646. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30647. */
  30648. Mesh.CreateIcoSphere = function (name, options, scene) {
  30649. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  30650. };
  30651. /**
  30652. * Creates a decal mesh.
  30653. * Please consider using the same method from the MeshBuilder class instead.
  30654. * 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.
  30655. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  30656. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  30657. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  30658. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  30659. */
  30660. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  30661. var options = {
  30662. position: position,
  30663. normal: normal,
  30664. size: size,
  30665. angle: angle
  30666. };
  30667. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  30668. };
  30669. // Skeletons
  30670. /**
  30671. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30672. */
  30673. Mesh.prototype.setPositionsForCPUSkinning = function () {
  30674. if (!this._sourcePositions) {
  30675. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30676. if (!source) {
  30677. return this._sourcePositions;
  30678. }
  30679. this._sourcePositions = new Float32Array(source);
  30680. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30681. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  30682. }
  30683. }
  30684. return this._sourcePositions;
  30685. };
  30686. /**
  30687. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30688. */
  30689. Mesh.prototype.setNormalsForCPUSkinning = function () {
  30690. if (!this._sourceNormals) {
  30691. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30692. if (!source) {
  30693. return this._sourceNormals;
  30694. }
  30695. this._sourceNormals = new Float32Array(source);
  30696. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30697. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  30698. }
  30699. }
  30700. return this._sourceNormals;
  30701. };
  30702. /**
  30703. * Updates the vertex buffer by applying transformation from the bones.
  30704. * Returns the Mesh.
  30705. *
  30706. * @param {skeleton} skeleton to apply
  30707. */
  30708. Mesh.prototype.applySkeleton = function (skeleton) {
  30709. if (!this.geometry) {
  30710. return this;
  30711. }
  30712. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  30713. return this;
  30714. }
  30715. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  30716. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30717. return this;
  30718. }
  30719. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30720. return this;
  30721. }
  30722. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30723. return this;
  30724. }
  30725. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30726. return this;
  30727. }
  30728. if (!this._sourcePositions) {
  30729. var submeshes = this.subMeshes.slice();
  30730. this.setPositionsForCPUSkinning();
  30731. this.subMeshes = submeshes;
  30732. }
  30733. if (!this._sourceNormals) {
  30734. this.setNormalsForCPUSkinning();
  30735. }
  30736. // positionsData checks for not being Float32Array will only pass at most once
  30737. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30738. if (!positionsData) {
  30739. return this;
  30740. }
  30741. if (!(positionsData instanceof Float32Array)) {
  30742. positionsData = new Float32Array(positionsData);
  30743. }
  30744. // normalsData checks for not being Float32Array will only pass at most once
  30745. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30746. if (!normalsData) {
  30747. return this;
  30748. }
  30749. if (!(normalsData instanceof Float32Array)) {
  30750. normalsData = new Float32Array(normalsData);
  30751. }
  30752. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30753. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30754. if (!matricesWeightsData || !matricesIndicesData) {
  30755. return this;
  30756. }
  30757. var needExtras = this.numBoneInfluencers > 4;
  30758. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30759. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30760. var skeletonMatrices = skeleton.getTransformMatrices(this);
  30761. var tempVector3 = BABYLON.Vector3.Zero();
  30762. var finalMatrix = new BABYLON.Matrix();
  30763. var tempMatrix = new BABYLON.Matrix();
  30764. var matWeightIdx = 0;
  30765. var inf;
  30766. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  30767. var weight;
  30768. for (inf = 0; inf < 4; inf++) {
  30769. weight = matricesWeightsData[matWeightIdx + inf];
  30770. if (weight > 0) {
  30771. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30772. finalMatrix.addToSelf(tempMatrix);
  30773. }
  30774. else
  30775. break;
  30776. }
  30777. if (needExtras) {
  30778. for (inf = 0; inf < 4; inf++) {
  30779. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30780. if (weight > 0) {
  30781. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30782. finalMatrix.addToSelf(tempMatrix);
  30783. }
  30784. else
  30785. break;
  30786. }
  30787. }
  30788. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  30789. tempVector3.toArray(positionsData, index);
  30790. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  30791. tempVector3.toArray(normalsData, index);
  30792. finalMatrix.reset();
  30793. }
  30794. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  30795. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  30796. return this;
  30797. };
  30798. // Tools
  30799. /**
  30800. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  30801. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  30802. */
  30803. Mesh.MinMax = function (meshes) {
  30804. var minVector = null;
  30805. var maxVector = null;
  30806. meshes.forEach(function (mesh, index, array) {
  30807. var boundingInfo = mesh.getBoundingInfo();
  30808. var boundingBox = boundingInfo.boundingBox;
  30809. if (!minVector || !maxVector) {
  30810. minVector = boundingBox.minimumWorld;
  30811. maxVector = boundingBox.maximumWorld;
  30812. }
  30813. else {
  30814. minVector.minimizeInPlace(boundingBox.minimumWorld);
  30815. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  30816. }
  30817. });
  30818. if (!minVector || !maxVector) {
  30819. return {
  30820. min: BABYLON.Vector3.Zero(),
  30821. max: BABYLON.Vector3.Zero()
  30822. };
  30823. }
  30824. return {
  30825. min: minVector,
  30826. max: maxVector
  30827. };
  30828. };
  30829. /**
  30830. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  30831. */
  30832. Mesh.Center = function (meshesOrMinMaxVector) {
  30833. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  30834. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  30835. };
  30836. /**
  30837. * Merge the array of meshes into a single mesh for performance reasons.
  30838. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  30839. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  30840. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  30841. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  30842. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  30843. */
  30844. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  30845. if (disposeSource === void 0) { disposeSource = true; }
  30846. var index;
  30847. if (!allow32BitsIndices) {
  30848. var totalVertices = 0;
  30849. // Counting vertices
  30850. for (index = 0; index < meshes.length; index++) {
  30851. if (meshes[index]) {
  30852. totalVertices += meshes[index].getTotalVertices();
  30853. if (totalVertices > 65536) {
  30854. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  30855. return null;
  30856. }
  30857. }
  30858. }
  30859. }
  30860. // Merge
  30861. var vertexData = null;
  30862. var otherVertexData;
  30863. var indiceArray = new Array();
  30864. var source = null;
  30865. for (index = 0; index < meshes.length; index++) {
  30866. if (meshes[index]) {
  30867. meshes[index].computeWorldMatrix(true);
  30868. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  30869. otherVertexData.transform(meshes[index].getWorldMatrix());
  30870. if (vertexData) {
  30871. vertexData.merge(otherVertexData);
  30872. }
  30873. else {
  30874. vertexData = otherVertexData;
  30875. source = meshes[index];
  30876. }
  30877. if (subdivideWithSubMeshes) {
  30878. indiceArray.push(meshes[index].getTotalIndices());
  30879. }
  30880. }
  30881. }
  30882. source = source;
  30883. if (!meshSubclass) {
  30884. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  30885. }
  30886. vertexData.applyToMesh(meshSubclass);
  30887. // Setting properties
  30888. meshSubclass.material = source.material;
  30889. meshSubclass.checkCollisions = source.checkCollisions;
  30890. // Cleaning
  30891. if (disposeSource) {
  30892. for (index = 0; index < meshes.length; index++) {
  30893. if (meshes[index]) {
  30894. meshes[index].dispose();
  30895. }
  30896. }
  30897. }
  30898. // Subdivide
  30899. if (subdivideWithSubMeshes) {
  30900. //-- Suppresions du submesh global
  30901. meshSubclass.releaseSubMeshes();
  30902. index = 0;
  30903. var offset = 0;
  30904. //-- aplique la subdivision en fonction du tableau d'indices
  30905. while (index < indiceArray.length) {
  30906. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  30907. offset += indiceArray[index];
  30908. index++;
  30909. }
  30910. }
  30911. return meshSubclass;
  30912. };
  30913. // Consts
  30914. Mesh._FRONTSIDE = 0;
  30915. Mesh._BACKSIDE = 1;
  30916. Mesh._DOUBLESIDE = 2;
  30917. Mesh._DEFAULTSIDE = 0;
  30918. Mesh._NO_CAP = 0;
  30919. Mesh._CAP_START = 1;
  30920. Mesh._CAP_END = 2;
  30921. Mesh._CAP_ALL = 3;
  30922. return Mesh;
  30923. }(BABYLON.AbstractMesh));
  30924. BABYLON.Mesh = Mesh;
  30925. })(BABYLON || (BABYLON = {}));
  30926. //# sourceMappingURL=babylon.mesh.js.map
  30927. "use strict";
  30928. var BABYLON;
  30929. (function (BABYLON) {
  30930. var BaseSubMesh = /** @class */ (function () {
  30931. function BaseSubMesh() {
  30932. }
  30933. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  30934. get: function () {
  30935. return this._materialEffect;
  30936. },
  30937. enumerable: true,
  30938. configurable: true
  30939. });
  30940. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  30941. if (defines === void 0) { defines = null; }
  30942. if (this._materialEffect === effect) {
  30943. if (!effect) {
  30944. this._materialDefines = null;
  30945. }
  30946. return;
  30947. }
  30948. this._materialDefines = defines;
  30949. this._materialEffect = effect;
  30950. };
  30951. return BaseSubMesh;
  30952. }());
  30953. BABYLON.BaseSubMesh = BaseSubMesh;
  30954. var SubMesh = /** @class */ (function (_super) {
  30955. __extends(SubMesh, _super);
  30956. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30957. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30958. var _this = _super.call(this) || this;
  30959. _this.materialIndex = materialIndex;
  30960. _this.verticesStart = verticesStart;
  30961. _this.verticesCount = verticesCount;
  30962. _this.indexStart = indexStart;
  30963. _this.indexCount = indexCount;
  30964. _this._renderId = 0;
  30965. _this._mesh = mesh;
  30966. _this._renderingMesh = renderingMesh || mesh;
  30967. mesh.subMeshes.push(_this);
  30968. _this._trianglePlanes = [];
  30969. _this._id = mesh.subMeshes.length - 1;
  30970. if (createBoundingBox) {
  30971. _this.refreshBoundingInfo();
  30972. mesh.computeWorldMatrix(true);
  30973. }
  30974. return _this;
  30975. }
  30976. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30977. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30978. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  30979. };
  30980. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  30981. get: function () {
  30982. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  30983. },
  30984. enumerable: true,
  30985. configurable: true
  30986. });
  30987. /**
  30988. * Returns the submesh BoudingInfo object.
  30989. */
  30990. SubMesh.prototype.getBoundingInfo = function () {
  30991. if (this.IsGlobal) {
  30992. return this._mesh.getBoundingInfo();
  30993. }
  30994. return this._boundingInfo;
  30995. };
  30996. /**
  30997. * Sets the submesh BoundingInfo.
  30998. * Return the SubMesh.
  30999. */
  31000. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  31001. this._boundingInfo = boundingInfo;
  31002. return this;
  31003. };
  31004. /**
  31005. * Returns the mesh of the current submesh.
  31006. */
  31007. SubMesh.prototype.getMesh = function () {
  31008. return this._mesh;
  31009. };
  31010. /**
  31011. * Returns the rendering mesh of the submesh.
  31012. */
  31013. SubMesh.prototype.getRenderingMesh = function () {
  31014. return this._renderingMesh;
  31015. };
  31016. /**
  31017. * Returns the submesh material.
  31018. */
  31019. SubMesh.prototype.getMaterial = function () {
  31020. var rootMaterial = this._renderingMesh.material;
  31021. if (rootMaterial === null || rootMaterial === undefined) {
  31022. return this._mesh.getScene().defaultMaterial;
  31023. }
  31024. else if (rootMaterial.getSubMaterial) {
  31025. var multiMaterial = rootMaterial;
  31026. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  31027. if (this._currentMaterial !== effectiveMaterial) {
  31028. this._currentMaterial = effectiveMaterial;
  31029. this._materialDefines = null;
  31030. }
  31031. return effectiveMaterial;
  31032. }
  31033. return rootMaterial;
  31034. };
  31035. // Methods
  31036. /**
  31037. * Sets a new updated BoundingInfo object to the submesh.
  31038. * Returns the SubMesh.
  31039. */
  31040. SubMesh.prototype.refreshBoundingInfo = function () {
  31041. this._lastColliderWorldVertices = null;
  31042. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  31043. return this;
  31044. }
  31045. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31046. if (!data) {
  31047. this._boundingInfo = this._mesh.getBoundingInfo();
  31048. return this;
  31049. }
  31050. var indices = this._renderingMesh.getIndices();
  31051. var extend;
  31052. //is this the only submesh?
  31053. if (this.indexStart === 0 && this.indexCount === indices.length) {
  31054. var boundingInfo = this._renderingMesh.getBoundingInfo();
  31055. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  31056. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  31057. }
  31058. else {
  31059. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  31060. }
  31061. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31062. return this;
  31063. };
  31064. SubMesh.prototype._checkCollision = function (collider) {
  31065. var boundingInfo = this.getBoundingInfo();
  31066. return boundingInfo._checkCollision(collider);
  31067. };
  31068. /**
  31069. * Updates the submesh BoundingInfo.
  31070. * Returns the Submesh.
  31071. */
  31072. SubMesh.prototype.updateBoundingInfo = function (world) {
  31073. var boundingInfo = this.getBoundingInfo();
  31074. if (!boundingInfo) {
  31075. this.refreshBoundingInfo();
  31076. boundingInfo = this.getBoundingInfo();
  31077. }
  31078. boundingInfo.update(world);
  31079. return this;
  31080. };
  31081. /**
  31082. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  31083. * Boolean returned.
  31084. */
  31085. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  31086. var boundingInfo = this.getBoundingInfo();
  31087. if (!boundingInfo) {
  31088. return false;
  31089. }
  31090. return boundingInfo.isInFrustum(frustumPlanes);
  31091. };
  31092. /**
  31093. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  31094. * Boolean returned.
  31095. */
  31096. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  31097. var boundingInfo = this.getBoundingInfo();
  31098. if (!boundingInfo) {
  31099. return false;
  31100. }
  31101. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  31102. };
  31103. /**
  31104. * Renders the submesh.
  31105. * Returns it.
  31106. */
  31107. SubMesh.prototype.render = function (enableAlphaMode) {
  31108. this._renderingMesh.render(this, enableAlphaMode);
  31109. return this;
  31110. };
  31111. /**
  31112. * Returns a new Index Buffer.
  31113. * Type returned : WebGLBuffer.
  31114. */
  31115. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  31116. if (!this._linesIndexBuffer) {
  31117. var linesIndices = [];
  31118. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  31119. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  31120. }
  31121. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  31122. this.linesIndexCount = linesIndices.length;
  31123. }
  31124. return this._linesIndexBuffer;
  31125. };
  31126. /**
  31127. * True is the passed Ray intersects the submesh bounding box.
  31128. * Boolean returned.
  31129. */
  31130. SubMesh.prototype.canIntersects = function (ray) {
  31131. var boundingInfo = this.getBoundingInfo();
  31132. if (!boundingInfo) {
  31133. return false;
  31134. }
  31135. return ray.intersectsBox(boundingInfo.boundingBox);
  31136. };
  31137. /**
  31138. * Returns an object IntersectionInfo.
  31139. */
  31140. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  31141. var intersectInfo = null;
  31142. var material = this.getMaterial();
  31143. if (!material) {
  31144. return null;
  31145. }
  31146. switch (material.fillMode) {
  31147. case BABYLON.Material.PointListDrawMode:
  31148. case BABYLON.Material.LineListDrawMode:
  31149. case BABYLON.Material.LineLoopDrawMode:
  31150. case BABYLON.Material.LineStripDrawMode:
  31151. case BABYLON.Material.TriangleFanDrawMode:
  31152. case BABYLON.Material.TriangleStripDrawMode:
  31153. return null;
  31154. }
  31155. // LineMesh first as it's also a Mesh...
  31156. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  31157. var lineMesh = this._mesh;
  31158. // Line test
  31159. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  31160. var p0 = positions[indices[index]];
  31161. var p1 = positions[indices[index + 1]];
  31162. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  31163. if (length < 0) {
  31164. continue;
  31165. }
  31166. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  31167. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  31168. if (fastCheck) {
  31169. break;
  31170. }
  31171. }
  31172. }
  31173. }
  31174. else {
  31175. // Triangles test
  31176. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  31177. var p0 = positions[indices[index]];
  31178. var p1 = positions[indices[index + 1]];
  31179. var p2 = positions[indices[index + 2]];
  31180. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  31181. if (currentIntersectInfo) {
  31182. if (currentIntersectInfo.distance < 0) {
  31183. continue;
  31184. }
  31185. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  31186. intersectInfo = currentIntersectInfo;
  31187. intersectInfo.faceId = index / 3;
  31188. if (fastCheck) {
  31189. break;
  31190. }
  31191. }
  31192. }
  31193. }
  31194. }
  31195. return intersectInfo;
  31196. };
  31197. SubMesh.prototype._rebuild = function () {
  31198. if (this._linesIndexBuffer) {
  31199. this._linesIndexBuffer = null;
  31200. }
  31201. };
  31202. // Clone
  31203. /**
  31204. * Creates a new Submesh from the passed Mesh.
  31205. */
  31206. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  31207. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  31208. if (!this.IsGlobal) {
  31209. var boundingInfo = this.getBoundingInfo();
  31210. if (!boundingInfo) {
  31211. return result;
  31212. }
  31213. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  31214. }
  31215. return result;
  31216. };
  31217. // Dispose
  31218. /**
  31219. * Disposes the Submesh.
  31220. * Returns nothing.
  31221. */
  31222. SubMesh.prototype.dispose = function () {
  31223. if (this._linesIndexBuffer) {
  31224. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  31225. this._linesIndexBuffer = null;
  31226. }
  31227. // Remove from mesh
  31228. var index = this._mesh.subMeshes.indexOf(this);
  31229. this._mesh.subMeshes.splice(index, 1);
  31230. };
  31231. // Statics
  31232. /**
  31233. * Creates a new Submesh from the passed parameters :
  31234. * - materialIndex (integer) : the index of the main mesh material.
  31235. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  31236. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  31237. * - mesh (Mesh) : the main mesh to create the submesh from.
  31238. * - renderingMesh (optional Mesh) : rendering mesh.
  31239. */
  31240. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  31241. var minVertexIndex = Number.MAX_VALUE;
  31242. var maxVertexIndex = -Number.MAX_VALUE;
  31243. renderingMesh = (renderingMesh || mesh);
  31244. var indices = renderingMesh.getIndices();
  31245. for (var index = startIndex; index < startIndex + indexCount; index++) {
  31246. var vertexIndex = indices[index];
  31247. if (vertexIndex < minVertexIndex)
  31248. minVertexIndex = vertexIndex;
  31249. if (vertexIndex > maxVertexIndex)
  31250. maxVertexIndex = vertexIndex;
  31251. }
  31252. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  31253. };
  31254. return SubMesh;
  31255. }(BaseSubMesh));
  31256. BABYLON.SubMesh = SubMesh;
  31257. })(BABYLON || (BABYLON = {}));
  31258. //# sourceMappingURL=babylon.subMesh.js.map
  31259. "use strict";
  31260. var __assign = (this && this.__assign) || Object.assign || function(t) {
  31261. for (var s, i = 1, n = arguments.length; i < n; i++) {
  31262. s = arguments[i];
  31263. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  31264. t[p] = s[p];
  31265. }
  31266. return t;
  31267. };
  31268. var BABYLON;
  31269. (function (BABYLON) {
  31270. /**
  31271. * Manages the defines for the Material.
  31272. */
  31273. var MaterialDefines = /** @class */ (function () {
  31274. function MaterialDefines() {
  31275. this._isDirty = true;
  31276. this._areLightsDirty = true;
  31277. this._areAttributesDirty = true;
  31278. this._areTexturesDirty = true;
  31279. this._areFresnelDirty = true;
  31280. this._areMiscDirty = true;
  31281. this._areImageProcessingDirty = true;
  31282. this._normals = false;
  31283. this._uvs = false;
  31284. this._needNormals = false;
  31285. this._needUVs = false;
  31286. }
  31287. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  31288. /**
  31289. * Specifies if the material needs to be re-calculated.
  31290. */
  31291. get: function () {
  31292. return this._isDirty;
  31293. },
  31294. enumerable: true,
  31295. configurable: true
  31296. });
  31297. /**
  31298. * Marks the material to indicate that it has been re-calculated.
  31299. */
  31300. MaterialDefines.prototype.markAsProcessed = function () {
  31301. this._isDirty = false;
  31302. this._areAttributesDirty = false;
  31303. this._areTexturesDirty = false;
  31304. this._areFresnelDirty = false;
  31305. this._areLightsDirty = false;
  31306. this._areMiscDirty = false;
  31307. this._areImageProcessingDirty = false;
  31308. };
  31309. /**
  31310. * Marks the material to indicate that it needs to be re-calculated.
  31311. */
  31312. MaterialDefines.prototype.markAsUnprocessed = function () {
  31313. this._isDirty = true;
  31314. };
  31315. /**
  31316. * Marks the material to indicate all of its defines need to be re-calculated.
  31317. */
  31318. MaterialDefines.prototype.markAllAsDirty = function () {
  31319. this._areTexturesDirty = true;
  31320. this._areAttributesDirty = true;
  31321. this._areLightsDirty = true;
  31322. this._areFresnelDirty = true;
  31323. this._areMiscDirty = true;
  31324. this._areImageProcessingDirty = true;
  31325. this._isDirty = true;
  31326. };
  31327. /**
  31328. * Marks the material to indicate that image processing needs to be re-calculated.
  31329. */
  31330. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  31331. this._areImageProcessingDirty = true;
  31332. this._isDirty = true;
  31333. };
  31334. /**
  31335. * Marks the material to indicate the lights need to be re-calculated.
  31336. */
  31337. MaterialDefines.prototype.markAsLightDirty = function () {
  31338. this._areLightsDirty = true;
  31339. this._isDirty = true;
  31340. };
  31341. /**
  31342. * Marks the attribute state as changed.
  31343. */
  31344. MaterialDefines.prototype.markAsAttributesDirty = function () {
  31345. this._areAttributesDirty = true;
  31346. this._isDirty = true;
  31347. };
  31348. /**
  31349. * Marks the texture state as changed.
  31350. */
  31351. MaterialDefines.prototype.markAsTexturesDirty = function () {
  31352. this._areTexturesDirty = true;
  31353. this._isDirty = true;
  31354. };
  31355. /**
  31356. * Marks the fresnel state as changed.
  31357. */
  31358. MaterialDefines.prototype.markAsFresnelDirty = function () {
  31359. this._areFresnelDirty = true;
  31360. this._isDirty = true;
  31361. };
  31362. /**
  31363. * Marks the misc state as changed.
  31364. */
  31365. MaterialDefines.prototype.markAsMiscDirty = function () {
  31366. this._areMiscDirty = true;
  31367. this._isDirty = true;
  31368. };
  31369. /**
  31370. * Rebuilds the material defines.
  31371. */
  31372. MaterialDefines.prototype.rebuild = function () {
  31373. if (this._keys) {
  31374. delete this._keys;
  31375. }
  31376. this._keys = [];
  31377. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  31378. var key = _a[_i];
  31379. if (key[0] === "_") {
  31380. continue;
  31381. }
  31382. this._keys.push(key);
  31383. }
  31384. };
  31385. /**
  31386. * Specifies if two material defines are equal.
  31387. * @param other - A material define instance to compare to.
  31388. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  31389. */
  31390. MaterialDefines.prototype.isEqual = function (other) {
  31391. if (this._keys.length !== other._keys.length) {
  31392. return false;
  31393. }
  31394. for (var index = 0; index < this._keys.length; index++) {
  31395. var prop = this._keys[index];
  31396. if (this[prop] !== other[prop]) {
  31397. return false;
  31398. }
  31399. }
  31400. return true;
  31401. };
  31402. /**
  31403. * Clones this instance's defines to another instance.
  31404. * @param other - material defines to clone values to.
  31405. */
  31406. MaterialDefines.prototype.cloneTo = function (other) {
  31407. if (this._keys.length !== other._keys.length) {
  31408. other._keys = this._keys.slice(0);
  31409. }
  31410. for (var index = 0; index < this._keys.length; index++) {
  31411. var prop = this._keys[index];
  31412. other[prop] = this[prop];
  31413. }
  31414. };
  31415. /**
  31416. * Resets the material define values.
  31417. */
  31418. MaterialDefines.prototype.reset = function () {
  31419. for (var index = 0; index < this._keys.length; index++) {
  31420. var prop = this._keys[index];
  31421. var type = typeof this[prop];
  31422. switch (type) {
  31423. case "number":
  31424. this[prop] = 0;
  31425. break;
  31426. case "string":
  31427. this[prop] = "";
  31428. break;
  31429. default:
  31430. this[prop] = false;
  31431. break;
  31432. }
  31433. }
  31434. };
  31435. /**
  31436. * Converts the material define values to a string.
  31437. * @returns - String of material define information.
  31438. */
  31439. MaterialDefines.prototype.toString = function () {
  31440. var result = "";
  31441. for (var index = 0; index < this._keys.length; index++) {
  31442. var prop = this._keys[index];
  31443. var value = this[prop];
  31444. var type = typeof value;
  31445. switch (type) {
  31446. case "number":
  31447. case "string":
  31448. result += "#define " + prop + " " + value + "\n";
  31449. break;
  31450. default:
  31451. if (value) {
  31452. result += "#define " + prop + "\n";
  31453. }
  31454. break;
  31455. }
  31456. }
  31457. return result;
  31458. };
  31459. return MaterialDefines;
  31460. }());
  31461. BABYLON.MaterialDefines = MaterialDefines;
  31462. /**
  31463. * This offers the main features of a material in BJS.
  31464. */
  31465. var Material = /** @class */ (function () {
  31466. /**
  31467. * Creates a material instance.
  31468. * @param name - The name of the material.
  31469. * @param scene - The BJS scene to reference.
  31470. * @param doNotAdd - Specifies if the material should be added to the scene.
  31471. */
  31472. function Material(name, scene, doNotAdd) {
  31473. /**
  31474. * Specifies if the ready state should be checked on each call.
  31475. */
  31476. this.checkReadyOnEveryCall = false;
  31477. /**
  31478. * Specifies if the ready state should be checked once.
  31479. */
  31480. this.checkReadyOnlyOnce = false;
  31481. /**
  31482. * The state of the material.
  31483. */
  31484. this.state = "";
  31485. /**
  31486. * The alpha value of the material.
  31487. */
  31488. this._alpha = 1.0;
  31489. /**
  31490. * Specifies if back face culling is enabled.
  31491. */
  31492. this._backFaceCulling = true;
  31493. /**
  31494. * Specifies if the material should be serialized.
  31495. */
  31496. this.doNotSerialize = false;
  31497. /**
  31498. * Specifies if the effect should be stored on sub meshes.
  31499. */
  31500. this.storeEffectOnSubMeshes = false;
  31501. /**
  31502. * An event triggered when the material is disposed.
  31503. */
  31504. this.onDisposeObservable = new BABYLON.Observable();
  31505. /**
  31506. * An event triggered when the material is bound.
  31507. */
  31508. this.onBindObservable = new BABYLON.Observable();
  31509. /**
  31510. * An event triggered when the material is unbound.
  31511. */
  31512. this.onUnBindObservable = new BABYLON.Observable();
  31513. /**
  31514. * Stores the value of the alpha mode.
  31515. */
  31516. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  31517. /**
  31518. * Stores the state of the need depth pre-pass value.
  31519. */
  31520. this._needDepthPrePass = false;
  31521. /**
  31522. * Specifies if depth writing should be disabled.
  31523. */
  31524. this.disableDepthWrite = false;
  31525. /**
  31526. * Specifies if depth writing should be forced.
  31527. */
  31528. this.forceDepthWrite = false;
  31529. /**
  31530. * Specifies if there should be a separate pass for culling.
  31531. */
  31532. this.separateCullingPass = false;
  31533. /**
  31534. * Stores the state specifing if fog should be enabled.
  31535. */
  31536. this._fogEnabled = true;
  31537. /**
  31538. * Stores the size of points.
  31539. */
  31540. this.pointSize = 1.0;
  31541. /**
  31542. * Stores the z offset value.
  31543. */
  31544. this.zOffset = 0;
  31545. /**
  31546. * Specifies if the material was previously ready.
  31547. */
  31548. this._wasPreviouslyReady = false;
  31549. /**
  31550. * Stores the fill mode state.
  31551. */
  31552. this._fillMode = Material.TriangleFillMode;
  31553. this.name = name;
  31554. this.id = name || BABYLON.Tools.RandomId();
  31555. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  31556. if (this._scene.useRightHandedSystem) {
  31557. this.sideOrientation = Material.ClockWiseSideOrientation;
  31558. }
  31559. else {
  31560. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  31561. }
  31562. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  31563. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  31564. if (!doNotAdd) {
  31565. this._scene.materials.push(this);
  31566. }
  31567. }
  31568. Object.defineProperty(Material, "TriangleFillMode", {
  31569. /**
  31570. * Returns the triangle fill mode.
  31571. */
  31572. get: function () {
  31573. return Material._TriangleFillMode;
  31574. },
  31575. enumerable: true,
  31576. configurable: true
  31577. });
  31578. Object.defineProperty(Material, "WireFrameFillMode", {
  31579. /**
  31580. * Returns the wireframe mode.
  31581. */
  31582. get: function () {
  31583. return Material._WireFrameFillMode;
  31584. },
  31585. enumerable: true,
  31586. configurable: true
  31587. });
  31588. Object.defineProperty(Material, "PointFillMode", {
  31589. /**
  31590. * Returns the point fill mode.
  31591. */
  31592. get: function () {
  31593. return Material._PointFillMode;
  31594. },
  31595. enumerable: true,
  31596. configurable: true
  31597. });
  31598. Object.defineProperty(Material, "PointListDrawMode", {
  31599. /**
  31600. * Returns the point list draw mode.
  31601. */
  31602. get: function () {
  31603. return Material._PointListDrawMode;
  31604. },
  31605. enumerable: true,
  31606. configurable: true
  31607. });
  31608. Object.defineProperty(Material, "LineListDrawMode", {
  31609. /**
  31610. * Returns the line list draw mode.
  31611. */
  31612. get: function () {
  31613. return Material._LineListDrawMode;
  31614. },
  31615. enumerable: true,
  31616. configurable: true
  31617. });
  31618. Object.defineProperty(Material, "LineLoopDrawMode", {
  31619. /**
  31620. * Returns the line loop draw mode.
  31621. */
  31622. get: function () {
  31623. return Material._LineLoopDrawMode;
  31624. },
  31625. enumerable: true,
  31626. configurable: true
  31627. });
  31628. Object.defineProperty(Material, "LineStripDrawMode", {
  31629. /**
  31630. * Returns the line strip draw mode.
  31631. */
  31632. get: function () {
  31633. return Material._LineStripDrawMode;
  31634. },
  31635. enumerable: true,
  31636. configurable: true
  31637. });
  31638. Object.defineProperty(Material, "TriangleStripDrawMode", {
  31639. /**
  31640. * Returns the triangle strip draw mode.
  31641. */
  31642. get: function () {
  31643. return Material._TriangleStripDrawMode;
  31644. },
  31645. enumerable: true,
  31646. configurable: true
  31647. });
  31648. Object.defineProperty(Material, "TriangleFanDrawMode", {
  31649. /**
  31650. * Returns the triangle fan draw mode.
  31651. */
  31652. get: function () {
  31653. return Material._TriangleFanDrawMode;
  31654. },
  31655. enumerable: true,
  31656. configurable: true
  31657. });
  31658. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  31659. /**
  31660. * Returns the clock-wise side orientation.
  31661. */
  31662. get: function () {
  31663. return Material._ClockWiseSideOrientation;
  31664. },
  31665. enumerable: true,
  31666. configurable: true
  31667. });
  31668. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  31669. /**
  31670. * Returns the counter clock-wise side orientation.
  31671. */
  31672. get: function () {
  31673. return Material._CounterClockWiseSideOrientation;
  31674. },
  31675. enumerable: true,
  31676. configurable: true
  31677. });
  31678. Object.defineProperty(Material, "TextureDirtyFlag", {
  31679. /**
  31680. * Returns the dirty texture flag value.
  31681. */
  31682. get: function () {
  31683. return Material._TextureDirtyFlag;
  31684. },
  31685. enumerable: true,
  31686. configurable: true
  31687. });
  31688. Object.defineProperty(Material, "LightDirtyFlag", {
  31689. /**
  31690. * Returns the dirty light flag value.
  31691. */
  31692. get: function () {
  31693. return Material._LightDirtyFlag;
  31694. },
  31695. enumerable: true,
  31696. configurable: true
  31697. });
  31698. Object.defineProperty(Material, "FresnelDirtyFlag", {
  31699. /**
  31700. * Returns the dirty fresnel flag value.
  31701. */
  31702. get: function () {
  31703. return Material._FresnelDirtyFlag;
  31704. },
  31705. enumerable: true,
  31706. configurable: true
  31707. });
  31708. Object.defineProperty(Material, "AttributesDirtyFlag", {
  31709. /**
  31710. * Returns the dirty attributes flag value.
  31711. */
  31712. get: function () {
  31713. return Material._AttributesDirtyFlag;
  31714. },
  31715. enumerable: true,
  31716. configurable: true
  31717. });
  31718. Object.defineProperty(Material, "MiscDirtyFlag", {
  31719. /**
  31720. * Returns the dirty misc flag value.
  31721. */
  31722. get: function () {
  31723. return Material._MiscDirtyFlag;
  31724. },
  31725. enumerable: true,
  31726. configurable: true
  31727. });
  31728. Object.defineProperty(Material.prototype, "alpha", {
  31729. /**
  31730. * Gets the alpha value of the material.
  31731. */
  31732. get: function () {
  31733. return this._alpha;
  31734. },
  31735. /**
  31736. * Sets the alpha value of the material.
  31737. */
  31738. set: function (value) {
  31739. if (this._alpha === value) {
  31740. return;
  31741. }
  31742. this._alpha = value;
  31743. this.markAsDirty(Material.MiscDirtyFlag);
  31744. },
  31745. enumerable: true,
  31746. configurable: true
  31747. });
  31748. Object.defineProperty(Material.prototype, "backFaceCulling", {
  31749. /**
  31750. * Gets the back-face culling state.
  31751. */
  31752. get: function () {
  31753. return this._backFaceCulling;
  31754. },
  31755. /**
  31756. * Sets the back-face culling state.
  31757. */
  31758. set: function (value) {
  31759. if (this._backFaceCulling === value) {
  31760. return;
  31761. }
  31762. this._backFaceCulling = value;
  31763. this.markAsDirty(Material.TextureDirtyFlag);
  31764. },
  31765. enumerable: true,
  31766. configurable: true
  31767. });
  31768. Object.defineProperty(Material.prototype, "onDispose", {
  31769. /**
  31770. * Called during a dispose event.
  31771. */
  31772. set: function (callback) {
  31773. if (this._onDisposeObserver) {
  31774. this.onDisposeObservable.remove(this._onDisposeObserver);
  31775. }
  31776. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31777. },
  31778. enumerable: true,
  31779. configurable: true
  31780. });
  31781. Object.defineProperty(Material.prototype, "onBind", {
  31782. /**
  31783. * Called during a bind event.
  31784. */
  31785. set: function (callback) {
  31786. if (this._onBindObserver) {
  31787. this.onBindObservable.remove(this._onBindObserver);
  31788. }
  31789. this._onBindObserver = this.onBindObservable.add(callback);
  31790. },
  31791. enumerable: true,
  31792. configurable: true
  31793. });
  31794. Object.defineProperty(Material.prototype, "alphaMode", {
  31795. /**
  31796. * Gets the value of the alpha mode.
  31797. */
  31798. get: function () {
  31799. return this._alphaMode;
  31800. },
  31801. /**
  31802. * Sets the value of the alpha mode.
  31803. *
  31804. * | Value | Type | Description |
  31805. * | --- | --- | --- |
  31806. * | 0 | ALPHA_DISABLE | |
  31807. * | 1 | ALPHA_ADD | |
  31808. * | 2 | ALPHA_COMBINE | |
  31809. * | 3 | ALPHA_SUBTRACT | |
  31810. * | 4 | ALPHA_MULTIPLY | |
  31811. * | 5 | ALPHA_MAXIMIZED | |
  31812. * | 6 | ALPHA_ONEONE | |
  31813. * | 7 | ALPHA_PREMULTIPLIED | |
  31814. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  31815. * | 9 | ALPHA_INTERPOLATE | |
  31816. * | 10 | ALPHA_SCREENMODE | |
  31817. *
  31818. */
  31819. set: function (value) {
  31820. if (this._alphaMode === value) {
  31821. return;
  31822. }
  31823. this._alphaMode = value;
  31824. this.markAsDirty(Material.TextureDirtyFlag);
  31825. },
  31826. enumerable: true,
  31827. configurable: true
  31828. });
  31829. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  31830. /**
  31831. * Gets the depth pre-pass value.
  31832. */
  31833. get: function () {
  31834. return this._needDepthPrePass;
  31835. },
  31836. /**
  31837. * Sets the need depth pre-pass value.
  31838. */
  31839. set: function (value) {
  31840. if (this._needDepthPrePass === value) {
  31841. return;
  31842. }
  31843. this._needDepthPrePass = value;
  31844. if (this._needDepthPrePass) {
  31845. this.checkReadyOnEveryCall = true;
  31846. }
  31847. },
  31848. enumerable: true,
  31849. configurable: true
  31850. });
  31851. Object.defineProperty(Material.prototype, "fogEnabled", {
  31852. /**
  31853. * Gets the value of the fog enabled state.
  31854. */
  31855. get: function () {
  31856. return this._fogEnabled;
  31857. },
  31858. /**
  31859. * Sets the state for enabling fog.
  31860. */
  31861. set: function (value) {
  31862. if (this._fogEnabled === value) {
  31863. return;
  31864. }
  31865. this._fogEnabled = value;
  31866. this.markAsDirty(Material.MiscDirtyFlag);
  31867. },
  31868. enumerable: true,
  31869. configurable: true
  31870. });
  31871. Object.defineProperty(Material.prototype, "wireframe", {
  31872. /**
  31873. * Gets a value specifying if wireframe mode is enabled.
  31874. */
  31875. get: function () {
  31876. switch (this._fillMode) {
  31877. case Material.WireFrameFillMode:
  31878. case Material.LineListDrawMode:
  31879. case Material.LineLoopDrawMode:
  31880. case Material.LineStripDrawMode:
  31881. return true;
  31882. }
  31883. return this._scene.forceWireframe;
  31884. },
  31885. /**
  31886. * Sets the state of wireframe mode.
  31887. */
  31888. set: function (value) {
  31889. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  31890. },
  31891. enumerable: true,
  31892. configurable: true
  31893. });
  31894. Object.defineProperty(Material.prototype, "pointsCloud", {
  31895. /**
  31896. * Gets the value specifying if point clouds are enabled.
  31897. */
  31898. get: function () {
  31899. switch (this._fillMode) {
  31900. case Material.PointFillMode:
  31901. case Material.PointListDrawMode:
  31902. return true;
  31903. }
  31904. return this._scene.forcePointsCloud;
  31905. },
  31906. /**
  31907. * Sets the state of point cloud mode.
  31908. */
  31909. set: function (value) {
  31910. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  31911. },
  31912. enumerable: true,
  31913. configurable: true
  31914. });
  31915. Object.defineProperty(Material.prototype, "fillMode", {
  31916. /**
  31917. * Gets the material fill mode.
  31918. */
  31919. get: function () {
  31920. return this._fillMode;
  31921. },
  31922. /**
  31923. * Sets the material fill mode.
  31924. */
  31925. set: function (value) {
  31926. if (this._fillMode === value) {
  31927. return;
  31928. }
  31929. this._fillMode = value;
  31930. this.markAsDirty(Material.MiscDirtyFlag);
  31931. },
  31932. enumerable: true,
  31933. configurable: true
  31934. });
  31935. /**
  31936. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31937. * subclasses should override adding information pertainent to themselves.
  31938. * @returns - String with material information.
  31939. */
  31940. Material.prototype.toString = function (fullDetails) {
  31941. var ret = "Name: " + this.name;
  31942. if (fullDetails) {
  31943. }
  31944. return ret;
  31945. };
  31946. /**
  31947. * Gets the class name of the material.
  31948. * @returns - String with the class name of the material.
  31949. */
  31950. Material.prototype.getClassName = function () {
  31951. return "Material";
  31952. };
  31953. Object.defineProperty(Material.prototype, "isFrozen", {
  31954. /**
  31955. * Specifies if updates for the material been locked.
  31956. */
  31957. get: function () {
  31958. return this.checkReadyOnlyOnce;
  31959. },
  31960. enumerable: true,
  31961. configurable: true
  31962. });
  31963. /**
  31964. * Locks updates for the material.
  31965. */
  31966. Material.prototype.freeze = function () {
  31967. this.checkReadyOnlyOnce = true;
  31968. };
  31969. /**
  31970. * Unlocks updates for the material.
  31971. */
  31972. Material.prototype.unfreeze = function () {
  31973. this.checkReadyOnlyOnce = false;
  31974. };
  31975. /**
  31976. * Specifies if the material is ready to be used.
  31977. * @param mesh - BJS mesh.
  31978. * @param useInstances - Specifies if instances should be used.
  31979. * @returns - Boolean indicating if the material is ready to be used.
  31980. */
  31981. Material.prototype.isReady = function (mesh, useInstances) {
  31982. return true;
  31983. };
  31984. /**
  31985. * Specifies that the submesh is ready to be used.
  31986. * @param mesh - BJS mesh.
  31987. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  31988. * @param useInstances - Specifies that instances should be used.
  31989. * @returns - boolean indicating that the submesh is ready or not.
  31990. */
  31991. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31992. return false;
  31993. };
  31994. /**
  31995. * Returns the material effect.
  31996. * @returns - Nullable material effect.
  31997. */
  31998. Material.prototype.getEffect = function () {
  31999. return this._effect;
  32000. };
  32001. /**
  32002. * Returns the BJS scene.
  32003. * @returns - BJS Scene.
  32004. */
  32005. Material.prototype.getScene = function () {
  32006. return this._scene;
  32007. };
  32008. /**
  32009. * Specifies if the material will require alpha blending
  32010. * @returns - Boolean specifying if alpha blending is needed.
  32011. */
  32012. Material.prototype.needAlphaBlending = function () {
  32013. return (this.alpha < 1.0);
  32014. };
  32015. /**
  32016. * Specifies if the mesh will require alpha blending.
  32017. * @param mesh - BJS mesh.
  32018. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  32019. */
  32020. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  32021. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  32022. };
  32023. /**
  32024. * Specifies if this material should be rendered in alpha test mode.
  32025. * @returns - Boolean specifying if an alpha test is needed.
  32026. */
  32027. Material.prototype.needAlphaTesting = function () {
  32028. return false;
  32029. };
  32030. /**
  32031. * Gets the texture used for the alpha test.
  32032. * @returns - Nullable alpha test texture.
  32033. */
  32034. Material.prototype.getAlphaTestTexture = function () {
  32035. return null;
  32036. };
  32037. /**
  32038. * Marks the material to indicate that it needs to be re-calculated.
  32039. */
  32040. Material.prototype.markDirty = function () {
  32041. this._wasPreviouslyReady = false;
  32042. };
  32043. Material.prototype._preBind = function (effect, overrideOrientation) {
  32044. if (overrideOrientation === void 0) { overrideOrientation = null; }
  32045. var engine = this._scene.getEngine();
  32046. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  32047. var reverse = orientation === Material.ClockWiseSideOrientation;
  32048. engine.enableEffect(effect ? effect : this._effect);
  32049. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  32050. return reverse;
  32051. };
  32052. /**
  32053. * Binds the material to the mesh.
  32054. * @param world - World transformation matrix.
  32055. * @param mesh - Mesh to bind the material to.
  32056. */
  32057. Material.prototype.bind = function (world, mesh) {
  32058. };
  32059. /**
  32060. * Binds the submesh to the material.
  32061. * @param world - World transformation matrix.
  32062. * @param mesh - Mesh containing the submesh.
  32063. * @param subMesh - Submesh to bind the material to.
  32064. */
  32065. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  32066. };
  32067. /**
  32068. * Binds the world matrix to the material.
  32069. * @param world - World transformation matrix.
  32070. */
  32071. Material.prototype.bindOnlyWorldMatrix = function (world) {
  32072. };
  32073. /**
  32074. * Binds the scene's uniform buffer to the effect.
  32075. * @param effect - Effect to bind to the scene uniform buffer.
  32076. * @param sceneUbo - Scene uniform buffer.
  32077. */
  32078. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  32079. sceneUbo.bindToEffect(effect, "Scene");
  32080. };
  32081. /**
  32082. * Binds the view matrix to the effect.
  32083. * @param effect - Effect to bind the view matrix to.
  32084. */
  32085. Material.prototype.bindView = function (effect) {
  32086. if (!this._useUBO) {
  32087. effect.setMatrix("view", this.getScene().getViewMatrix());
  32088. }
  32089. else {
  32090. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  32091. }
  32092. };
  32093. /**
  32094. * Binds the view projection matrix to the effect.
  32095. * @param effect - Effect to bind the view projection matrix to.
  32096. */
  32097. Material.prototype.bindViewProjection = function (effect) {
  32098. if (!this._useUBO) {
  32099. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  32100. }
  32101. else {
  32102. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  32103. }
  32104. };
  32105. /**
  32106. * Specifies if material alpha testing should be turned on for the mesh.
  32107. * @param mesh - BJS mesh.
  32108. */
  32109. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  32110. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  32111. };
  32112. /**
  32113. * Processes to execute after binding the material to a mesh.
  32114. * @param mesh - BJS mesh.
  32115. */
  32116. Material.prototype._afterBind = function (mesh) {
  32117. this._scene._cachedMaterial = this;
  32118. if (mesh) {
  32119. this._scene._cachedVisibility = mesh.visibility;
  32120. }
  32121. else {
  32122. this._scene._cachedVisibility = 1;
  32123. }
  32124. if (mesh) {
  32125. this.onBindObservable.notifyObservers(mesh);
  32126. }
  32127. if (this.disableDepthWrite) {
  32128. var engine = this._scene.getEngine();
  32129. this._cachedDepthWriteState = engine.getDepthWrite();
  32130. engine.setDepthWrite(false);
  32131. }
  32132. };
  32133. /**
  32134. * Unbinds the material from the mesh.
  32135. */
  32136. Material.prototype.unbind = function () {
  32137. this.onUnBindObservable.notifyObservers(this);
  32138. if (this.disableDepthWrite) {
  32139. var engine = this._scene.getEngine();
  32140. engine.setDepthWrite(this._cachedDepthWriteState);
  32141. }
  32142. };
  32143. /**
  32144. * Gets the active textures from the material.
  32145. * @returns - Array of textures.
  32146. */
  32147. Material.prototype.getActiveTextures = function () {
  32148. return [];
  32149. };
  32150. /**
  32151. * Specifies if the material uses a texture.
  32152. * @param texture - Texture to check against the material.
  32153. * @returns - Boolean specifying if the material uses the texture.
  32154. */
  32155. Material.prototype.hasTexture = function (texture) {
  32156. return false;
  32157. };
  32158. /**
  32159. * Makes a duplicate of the material, and gives it a new name.
  32160. * @param name - Name to call the duplicated material.
  32161. * @returns - Nullable cloned material
  32162. */
  32163. Material.prototype.clone = function (name) {
  32164. return null;
  32165. };
  32166. /**
  32167. * Gets the meshes bound to the material.
  32168. * @returns - Array of meshes bound to the material.
  32169. */
  32170. Material.prototype.getBindedMeshes = function () {
  32171. var result = new Array();
  32172. for (var index = 0; index < this._scene.meshes.length; index++) {
  32173. var mesh = this._scene.meshes[index];
  32174. if (mesh.material === this) {
  32175. result.push(mesh);
  32176. }
  32177. }
  32178. return result;
  32179. };
  32180. /**
  32181. * Force shader compilation
  32182. * @param mesh - BJS mesh.
  32183. * @param onCompiled - function to execute once the material is compiled.
  32184. * @param options - options to pass to this function.
  32185. */
  32186. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  32187. var _this = this;
  32188. var localOptions = __assign({ clipPlane: false }, options);
  32189. var subMesh = new BABYLON.BaseSubMesh();
  32190. var scene = this.getScene();
  32191. var checkReady = function () {
  32192. if (!_this._scene || !_this._scene.getEngine()) {
  32193. return;
  32194. }
  32195. if (subMesh._materialDefines) {
  32196. subMesh._materialDefines._renderId = -1;
  32197. }
  32198. var clipPlaneState = scene.clipPlane;
  32199. if (localOptions.clipPlane) {
  32200. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  32201. }
  32202. if (_this.storeEffectOnSubMeshes) {
  32203. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  32204. if (onCompiled) {
  32205. onCompiled(_this);
  32206. }
  32207. }
  32208. else {
  32209. setTimeout(checkReady, 16);
  32210. }
  32211. }
  32212. else {
  32213. if (_this.isReady(mesh)) {
  32214. if (onCompiled) {
  32215. onCompiled(_this);
  32216. }
  32217. }
  32218. else {
  32219. setTimeout(checkReady, 16);
  32220. }
  32221. }
  32222. if (localOptions.clipPlane) {
  32223. scene.clipPlane = clipPlaneState;
  32224. }
  32225. };
  32226. checkReady();
  32227. };
  32228. /**
  32229. * Force shader compilation.
  32230. * @param mesh The mesh that will use this material
  32231. * @param options Additional options for compiling the shaders
  32232. * @returns A promise that resolves when the compilation completes
  32233. */
  32234. Material.prototype.forceCompilationAsync = function (mesh, options) {
  32235. var _this = this;
  32236. return new Promise(function (resolve) {
  32237. _this.forceCompilation(mesh, function () {
  32238. resolve();
  32239. }, options);
  32240. });
  32241. };
  32242. /**
  32243. * Marks a define in the material to indicate that it needs to be re-computed.
  32244. * @param flag - Material define flag.
  32245. */
  32246. Material.prototype.markAsDirty = function (flag) {
  32247. if (flag & Material.TextureDirtyFlag) {
  32248. this._markAllSubMeshesAsTexturesDirty();
  32249. }
  32250. if (flag & Material.LightDirtyFlag) {
  32251. this._markAllSubMeshesAsLightsDirty();
  32252. }
  32253. if (flag & Material.FresnelDirtyFlag) {
  32254. this._markAllSubMeshesAsFresnelDirty();
  32255. }
  32256. if (flag & Material.AttributesDirtyFlag) {
  32257. this._markAllSubMeshesAsAttributesDirty();
  32258. }
  32259. if (flag & Material.MiscDirtyFlag) {
  32260. this._markAllSubMeshesAsMiscDirty();
  32261. }
  32262. this.getScene().resetCachedMaterial();
  32263. };
  32264. /**
  32265. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  32266. * @param func - function which checks material defines against the submeshes.
  32267. */
  32268. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  32269. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  32270. var mesh = _a[_i];
  32271. if (!mesh.subMeshes) {
  32272. continue;
  32273. }
  32274. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  32275. var subMesh = _c[_b];
  32276. if (subMesh.getMaterial() !== this) {
  32277. continue;
  32278. }
  32279. if (!subMesh._materialDefines) {
  32280. continue;
  32281. }
  32282. func(subMesh._materialDefines);
  32283. }
  32284. }
  32285. };
  32286. /**
  32287. * Indicates that image processing needs to be re-calculated for all submeshes.
  32288. */
  32289. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  32290. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  32291. };
  32292. /**
  32293. * Indicates that textures need to be re-calculated for all submeshes.
  32294. */
  32295. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  32296. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  32297. };
  32298. /**
  32299. * Indicates that fresnel needs to be re-calculated for all submeshes.
  32300. */
  32301. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  32302. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  32303. };
  32304. /**
  32305. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  32306. */
  32307. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  32308. this._markAllSubMeshesAsDirty(function (defines) {
  32309. defines.markAsFresnelDirty();
  32310. defines.markAsMiscDirty();
  32311. });
  32312. };
  32313. /**
  32314. * Indicates that lights need to be re-calculated for all submeshes.
  32315. */
  32316. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  32317. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  32318. };
  32319. /**
  32320. * Indicates that attributes need to be re-calculated for all submeshes.
  32321. */
  32322. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  32323. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  32324. };
  32325. /**
  32326. * Indicates that misc needs to be re-calculated for all submeshes.
  32327. */
  32328. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  32329. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  32330. };
  32331. /**
  32332. * Indicates that textures and misc need to be re-calculated for all submeshes.
  32333. */
  32334. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  32335. this._markAllSubMeshesAsDirty(function (defines) {
  32336. defines.markAsTexturesDirty();
  32337. defines.markAsMiscDirty();
  32338. });
  32339. };
  32340. /**
  32341. * Disposes the material.
  32342. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  32343. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  32344. */
  32345. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  32346. // Animations
  32347. this.getScene().stopAnimation(this);
  32348. this.getScene().freeProcessedMaterials();
  32349. // Remove from scene
  32350. var index = this._scene.materials.indexOf(this);
  32351. if (index >= 0) {
  32352. this._scene.materials.splice(index, 1);
  32353. }
  32354. // Remove from meshes
  32355. for (index = 0; index < this._scene.meshes.length; index++) {
  32356. var mesh = this._scene.meshes[index];
  32357. if (mesh.material === this) {
  32358. mesh.material = null;
  32359. if (mesh.geometry) {
  32360. var geometry = (mesh.geometry);
  32361. if (this.storeEffectOnSubMeshes) {
  32362. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  32363. var subMesh = _a[_i];
  32364. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  32365. if (forceDisposeEffect && subMesh._materialEffect) {
  32366. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  32367. }
  32368. }
  32369. }
  32370. else {
  32371. geometry._releaseVertexArrayObject(this._effect);
  32372. }
  32373. }
  32374. }
  32375. }
  32376. this._uniformBuffer.dispose();
  32377. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  32378. if (forceDisposeEffect && this._effect) {
  32379. if (!this.storeEffectOnSubMeshes) {
  32380. this._scene.getEngine()._releaseEffect(this._effect);
  32381. }
  32382. this._effect = null;
  32383. }
  32384. // Callback
  32385. this.onDisposeObservable.notifyObservers(this);
  32386. this.onDisposeObservable.clear();
  32387. this.onBindObservable.clear();
  32388. this.onUnBindObservable.clear();
  32389. };
  32390. /**
  32391. * Serializes this material.
  32392. * @returns - serialized material object.
  32393. */
  32394. Material.prototype.serialize = function () {
  32395. return BABYLON.SerializationHelper.Serialize(this);
  32396. };
  32397. /**
  32398. * Creates a MultiMaterial from parse MultiMaterial data.
  32399. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  32400. * @param scene - BJS scene.
  32401. * @returns - MultiMaterial.
  32402. */
  32403. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  32404. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  32405. multiMaterial.id = parsedMultiMaterial.id;
  32406. if (BABYLON.Tags) {
  32407. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  32408. }
  32409. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  32410. var subMatId = parsedMultiMaterial.materials[matIndex];
  32411. if (subMatId) {
  32412. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  32413. }
  32414. else {
  32415. multiMaterial.subMaterials.push(null);
  32416. }
  32417. }
  32418. return multiMaterial;
  32419. };
  32420. /**
  32421. * Creates a material from parsed material data.
  32422. * @param parsedMaterial - Parsed material data.
  32423. * @param scene - BJS scene.
  32424. * @param rootUrl - Root URL containing the material information.
  32425. * @returns - Parsed material.
  32426. */
  32427. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  32428. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  32429. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  32430. }
  32431. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  32432. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  32433. if (!BABYLON.LegacyPBRMaterial) {
  32434. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  32435. return;
  32436. }
  32437. }
  32438. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  32439. return materialType.Parse(parsedMaterial, scene, rootUrl);
  32440. ;
  32441. };
  32442. // Triangle views
  32443. Material._TriangleFillMode = 0;
  32444. Material._WireFrameFillMode = 1;
  32445. Material._PointFillMode = 2;
  32446. // Draw modes
  32447. Material._PointListDrawMode = 3;
  32448. Material._LineListDrawMode = 4;
  32449. Material._LineLoopDrawMode = 5;
  32450. Material._LineStripDrawMode = 6;
  32451. Material._TriangleStripDrawMode = 7;
  32452. Material._TriangleFanDrawMode = 8;
  32453. /**
  32454. * Stores the clock-wise side orientation.
  32455. */
  32456. Material._ClockWiseSideOrientation = 0;
  32457. /**
  32458. * Stores the counter clock-wise side orientation.
  32459. */
  32460. Material._CounterClockWiseSideOrientation = 1;
  32461. /**
  32462. * The dirty texture flag value.
  32463. */
  32464. Material._TextureDirtyFlag = 1;
  32465. /**
  32466. * The dirty light flag value.
  32467. */
  32468. Material._LightDirtyFlag = 2;
  32469. /**
  32470. * The dirty fresnel flag value.
  32471. */
  32472. Material._FresnelDirtyFlag = 4;
  32473. /**
  32474. * The dirty attribute flag value.
  32475. */
  32476. Material._AttributesDirtyFlag = 8;
  32477. /**
  32478. * The dirty misc flag value.
  32479. */
  32480. Material._MiscDirtyFlag = 16;
  32481. __decorate([
  32482. BABYLON.serialize()
  32483. ], Material.prototype, "id", void 0);
  32484. __decorate([
  32485. BABYLON.serialize()
  32486. ], Material.prototype, "name", void 0);
  32487. __decorate([
  32488. BABYLON.serialize()
  32489. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  32490. __decorate([
  32491. BABYLON.serialize()
  32492. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  32493. __decorate([
  32494. BABYLON.serialize()
  32495. ], Material.prototype, "state", void 0);
  32496. __decorate([
  32497. BABYLON.serialize("alpha")
  32498. ], Material.prototype, "_alpha", void 0);
  32499. __decorate([
  32500. BABYLON.serialize("backFaceCulling")
  32501. ], Material.prototype, "_backFaceCulling", void 0);
  32502. __decorate([
  32503. BABYLON.serialize()
  32504. ], Material.prototype, "sideOrientation", void 0);
  32505. __decorate([
  32506. BABYLON.serialize("alphaMode")
  32507. ], Material.prototype, "_alphaMode", void 0);
  32508. __decorate([
  32509. BABYLON.serialize()
  32510. ], Material.prototype, "_needDepthPrePass", void 0);
  32511. __decorate([
  32512. BABYLON.serialize()
  32513. ], Material.prototype, "disableDepthWrite", void 0);
  32514. __decorate([
  32515. BABYLON.serialize()
  32516. ], Material.prototype, "forceDepthWrite", void 0);
  32517. __decorate([
  32518. BABYLON.serialize()
  32519. ], Material.prototype, "separateCullingPass", void 0);
  32520. __decorate([
  32521. BABYLON.serialize("fogEnabled")
  32522. ], Material.prototype, "_fogEnabled", void 0);
  32523. __decorate([
  32524. BABYLON.serialize()
  32525. ], Material.prototype, "pointSize", void 0);
  32526. __decorate([
  32527. BABYLON.serialize()
  32528. ], Material.prototype, "zOffset", void 0);
  32529. __decorate([
  32530. BABYLON.serialize()
  32531. ], Material.prototype, "wireframe", null);
  32532. __decorate([
  32533. BABYLON.serialize()
  32534. ], Material.prototype, "pointsCloud", null);
  32535. __decorate([
  32536. BABYLON.serialize()
  32537. ], Material.prototype, "fillMode", null);
  32538. return Material;
  32539. }());
  32540. BABYLON.Material = Material;
  32541. })(BABYLON || (BABYLON = {}));
  32542. //# sourceMappingURL=babylon.material.js.map
  32543. "use strict";
  32544. var BABYLON;
  32545. (function (BABYLON) {
  32546. var UniformBuffer = /** @class */ (function () {
  32547. /**
  32548. * Uniform buffer objects.
  32549. *
  32550. * Handles blocks of uniform on the GPU.
  32551. *
  32552. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  32553. *
  32554. * For more information, please refer to :
  32555. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  32556. */
  32557. function UniformBuffer(engine, data, dynamic) {
  32558. this._engine = engine;
  32559. this._noUBO = !engine.supportsUniformBuffers;
  32560. this._dynamic = dynamic;
  32561. this._data = data || [];
  32562. this._uniformLocations = {};
  32563. this._uniformSizes = {};
  32564. this._uniformLocationPointer = 0;
  32565. this._needSync = false;
  32566. if (this._noUBO) {
  32567. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  32568. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  32569. this.updateFloat = this._updateFloatForEffect;
  32570. this.updateFloat2 = this._updateFloat2ForEffect;
  32571. this.updateFloat3 = this._updateFloat3ForEffect;
  32572. this.updateFloat4 = this._updateFloat4ForEffect;
  32573. this.updateMatrix = this._updateMatrixForEffect;
  32574. this.updateVector3 = this._updateVector3ForEffect;
  32575. this.updateVector4 = this._updateVector4ForEffect;
  32576. this.updateColor3 = this._updateColor3ForEffect;
  32577. this.updateColor4 = this._updateColor4ForEffect;
  32578. }
  32579. else {
  32580. this._engine._uniformBuffers.push(this);
  32581. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  32582. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  32583. this.updateFloat = this._updateFloatForUniform;
  32584. this.updateFloat2 = this._updateFloat2ForUniform;
  32585. this.updateFloat3 = this._updateFloat3ForUniform;
  32586. this.updateFloat4 = this._updateFloat4ForUniform;
  32587. this.updateMatrix = this._updateMatrixForUniform;
  32588. this.updateVector3 = this._updateVector3ForUniform;
  32589. this.updateVector4 = this._updateVector4ForUniform;
  32590. this.updateColor3 = this._updateColor3ForUniform;
  32591. this.updateColor4 = this._updateColor4ForUniform;
  32592. }
  32593. }
  32594. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  32595. // Properties
  32596. /**
  32597. * Indicates if the buffer is using the WebGL2 UBO implementation,
  32598. * or just falling back on setUniformXXX calls.
  32599. */
  32600. get: function () {
  32601. return !this._noUBO;
  32602. },
  32603. enumerable: true,
  32604. configurable: true
  32605. });
  32606. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  32607. /**
  32608. * Indicates if the WebGL underlying uniform buffer is in sync
  32609. * with the javascript cache data.
  32610. */
  32611. get: function () {
  32612. return !this._needSync;
  32613. },
  32614. enumerable: true,
  32615. configurable: true
  32616. });
  32617. /**
  32618. * Indicates if the WebGL underlying uniform buffer is dynamic.
  32619. * Also, a dynamic UniformBuffer will disable cache verification and always
  32620. * update the underlying WebGL uniform buffer to the GPU.
  32621. */
  32622. UniformBuffer.prototype.isDynamic = function () {
  32623. return this._dynamic !== undefined;
  32624. };
  32625. /**
  32626. * The data cache on JS side.
  32627. */
  32628. UniformBuffer.prototype.getData = function () {
  32629. return this._bufferData;
  32630. };
  32631. /**
  32632. * The underlying WebGL Uniform buffer.
  32633. */
  32634. UniformBuffer.prototype.getBuffer = function () {
  32635. return this._buffer;
  32636. };
  32637. /**
  32638. * std140 layout specifies how to align data within an UBO structure.
  32639. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  32640. * for specs.
  32641. */
  32642. UniformBuffer.prototype._fillAlignment = function (size) {
  32643. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  32644. // and 4x4 matrices
  32645. // TODO : change if other types are used
  32646. var alignment;
  32647. if (size <= 2) {
  32648. alignment = size;
  32649. }
  32650. else {
  32651. alignment = 4;
  32652. }
  32653. if ((this._uniformLocationPointer % alignment) !== 0) {
  32654. var oldPointer = this._uniformLocationPointer;
  32655. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  32656. var diff = this._uniformLocationPointer - oldPointer;
  32657. for (var i = 0; i < diff; i++) {
  32658. this._data.push(0);
  32659. }
  32660. }
  32661. };
  32662. /**
  32663. * Adds an uniform in the buffer.
  32664. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  32665. * for the layout to be correct !
  32666. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32667. * @param {number|number[]} size Data size, or data directly.
  32668. */
  32669. UniformBuffer.prototype.addUniform = function (name, size) {
  32670. if (this._noUBO) {
  32671. return;
  32672. }
  32673. if (this._uniformLocations[name] !== undefined) {
  32674. // Already existing uniform
  32675. return;
  32676. }
  32677. // This function must be called in the order of the shader layout !
  32678. // size can be the size of the uniform, or data directly
  32679. var data;
  32680. if (size instanceof Array) {
  32681. data = size;
  32682. size = data.length;
  32683. }
  32684. else {
  32685. size = size;
  32686. data = [];
  32687. // Fill with zeros
  32688. for (var i = 0; i < size; i++) {
  32689. data.push(0);
  32690. }
  32691. }
  32692. this._fillAlignment(size);
  32693. this._uniformSizes[name] = size;
  32694. this._uniformLocations[name] = this._uniformLocationPointer;
  32695. this._uniformLocationPointer += size;
  32696. for (var i = 0; i < size; i++) {
  32697. this._data.push(data[i]);
  32698. }
  32699. this._needSync = true;
  32700. };
  32701. /**
  32702. * Wrapper for addUniform.
  32703. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32704. * @param {Matrix} mat A 4x4 matrix.
  32705. */
  32706. UniformBuffer.prototype.addMatrix = function (name, mat) {
  32707. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  32708. };
  32709. /**
  32710. * Wrapper for addUniform.
  32711. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32712. * @param {number} x
  32713. * @param {number} y
  32714. */
  32715. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  32716. var temp = [x, y];
  32717. this.addUniform(name, temp);
  32718. };
  32719. /**
  32720. * Wrapper for addUniform.
  32721. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32722. * @param {number} x
  32723. * @param {number} y
  32724. * @param {number} z
  32725. */
  32726. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  32727. var temp = [x, y, z];
  32728. this.addUniform(name, temp);
  32729. };
  32730. /**
  32731. * Wrapper for addUniform.
  32732. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32733. * @param {Color3} color
  32734. */
  32735. UniformBuffer.prototype.addColor3 = function (name, color) {
  32736. var temp = new Array();
  32737. color.toArray(temp);
  32738. this.addUniform(name, temp);
  32739. };
  32740. /**
  32741. * Wrapper for addUniform.
  32742. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32743. * @param {Color3} color
  32744. * @param {number} alpha
  32745. */
  32746. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  32747. var temp = new Array();
  32748. color.toArray(temp);
  32749. temp.push(alpha);
  32750. this.addUniform(name, temp);
  32751. };
  32752. /**
  32753. * Wrapper for addUniform.
  32754. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32755. * @param {Vector3} vector
  32756. */
  32757. UniformBuffer.prototype.addVector3 = function (name, vector) {
  32758. var temp = new Array();
  32759. vector.toArray(temp);
  32760. this.addUniform(name, temp);
  32761. };
  32762. /**
  32763. * Wrapper for addUniform.
  32764. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32765. */
  32766. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  32767. this.addUniform(name, 12);
  32768. };
  32769. /**
  32770. * Wrapper for addUniform.
  32771. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32772. */
  32773. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  32774. this.addUniform(name, 8);
  32775. };
  32776. /**
  32777. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  32778. */
  32779. UniformBuffer.prototype.create = function () {
  32780. if (this._noUBO) {
  32781. return;
  32782. }
  32783. if (this._buffer) {
  32784. return; // nothing to do
  32785. }
  32786. // See spec, alignment must be filled as a vec4
  32787. this._fillAlignment(4);
  32788. this._bufferData = new Float32Array(this._data);
  32789. this._rebuild();
  32790. this._needSync = true;
  32791. };
  32792. UniformBuffer.prototype._rebuild = function () {
  32793. if (this._noUBO) {
  32794. return;
  32795. }
  32796. if (this._dynamic) {
  32797. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  32798. }
  32799. else {
  32800. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  32801. }
  32802. };
  32803. /**
  32804. * Updates the WebGL Uniform Buffer on the GPU.
  32805. * If the `dynamic` flag is set to true, no cache comparison is done.
  32806. * Otherwise, the buffer will be updated only if the cache differs.
  32807. */
  32808. UniformBuffer.prototype.update = function () {
  32809. if (!this._buffer) {
  32810. this.create();
  32811. return;
  32812. }
  32813. if (!this._dynamic && !this._needSync) {
  32814. return;
  32815. }
  32816. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  32817. this._needSync = false;
  32818. };
  32819. /**
  32820. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  32821. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32822. * @param {number[]|Float32Array} data Flattened data
  32823. * @param {number} size Size of the data.
  32824. */
  32825. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  32826. var location = this._uniformLocations[uniformName];
  32827. if (location === undefined) {
  32828. if (this._buffer) {
  32829. // Cannot add an uniform if the buffer is already created
  32830. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  32831. return;
  32832. }
  32833. this.addUniform(uniformName, size);
  32834. location = this._uniformLocations[uniformName];
  32835. }
  32836. if (!this._buffer) {
  32837. this.create();
  32838. }
  32839. if (!this._dynamic) {
  32840. // Cache for static uniform buffers
  32841. var changed = false;
  32842. for (var i = 0; i < size; i++) {
  32843. if (this._bufferData[location + i] !== data[i]) {
  32844. changed = true;
  32845. this._bufferData[location + i] = data[i];
  32846. }
  32847. }
  32848. this._needSync = this._needSync || changed;
  32849. }
  32850. else {
  32851. // No cache for dynamic
  32852. for (var i = 0; i < size; i++) {
  32853. this._bufferData[location + i] = data[i];
  32854. }
  32855. }
  32856. };
  32857. // Update methods
  32858. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  32859. // To match std140, matrix must be realigned
  32860. for (var i = 0; i < 3; i++) {
  32861. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  32862. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  32863. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  32864. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32865. }
  32866. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  32867. };
  32868. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  32869. this._currentEffect.setMatrix3x3(name, matrix);
  32870. };
  32871. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  32872. this._currentEffect.setMatrix2x2(name, matrix);
  32873. };
  32874. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  32875. // To match std140, matrix must be realigned
  32876. for (var i = 0; i < 2; i++) {
  32877. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  32878. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  32879. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  32880. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32881. }
  32882. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  32883. };
  32884. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  32885. this._currentEffect.setFloat(name, x);
  32886. };
  32887. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  32888. UniformBuffer._tempBuffer[0] = x;
  32889. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  32890. };
  32891. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  32892. if (suffix === void 0) { suffix = ""; }
  32893. this._currentEffect.setFloat2(name + suffix, x, y);
  32894. };
  32895. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  32896. if (suffix === void 0) { suffix = ""; }
  32897. UniformBuffer._tempBuffer[0] = x;
  32898. UniformBuffer._tempBuffer[1] = y;
  32899. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  32900. };
  32901. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  32902. if (suffix === void 0) { suffix = ""; }
  32903. this._currentEffect.setFloat3(name + suffix, x, y, z);
  32904. };
  32905. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  32906. if (suffix === void 0) { suffix = ""; }
  32907. UniformBuffer._tempBuffer[0] = x;
  32908. UniformBuffer._tempBuffer[1] = y;
  32909. UniformBuffer._tempBuffer[2] = z;
  32910. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32911. };
  32912. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  32913. if (suffix === void 0) { suffix = ""; }
  32914. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  32915. };
  32916. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  32917. if (suffix === void 0) { suffix = ""; }
  32918. UniformBuffer._tempBuffer[0] = x;
  32919. UniformBuffer._tempBuffer[1] = y;
  32920. UniformBuffer._tempBuffer[2] = z;
  32921. UniformBuffer._tempBuffer[3] = w;
  32922. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32923. };
  32924. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  32925. this._currentEffect.setMatrix(name, mat);
  32926. };
  32927. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  32928. this.updateUniform(name, mat.toArray(), 16);
  32929. };
  32930. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  32931. this._currentEffect.setVector3(name, vector);
  32932. };
  32933. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  32934. vector.toArray(UniformBuffer._tempBuffer);
  32935. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32936. };
  32937. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  32938. this._currentEffect.setVector4(name, vector);
  32939. };
  32940. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  32941. vector.toArray(UniformBuffer._tempBuffer);
  32942. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32943. };
  32944. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  32945. if (suffix === void 0) { suffix = ""; }
  32946. this._currentEffect.setColor3(name + suffix, color);
  32947. };
  32948. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  32949. if (suffix === void 0) { suffix = ""; }
  32950. color.toArray(UniformBuffer._tempBuffer);
  32951. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32952. };
  32953. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  32954. if (suffix === void 0) { suffix = ""; }
  32955. this._currentEffect.setColor4(name + suffix, color, alpha);
  32956. };
  32957. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  32958. if (suffix === void 0) { suffix = ""; }
  32959. color.toArray(UniformBuffer._tempBuffer);
  32960. UniformBuffer._tempBuffer[3] = alpha;
  32961. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32962. };
  32963. /**
  32964. * Sets a sampler uniform on the effect.
  32965. * @param {string} name Name of the sampler.
  32966. * @param {Texture} texture
  32967. */
  32968. UniformBuffer.prototype.setTexture = function (name, texture) {
  32969. this._currentEffect.setTexture(name, texture);
  32970. };
  32971. /**
  32972. * Directly updates the value of the uniform in the cache AND on the GPU.
  32973. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32974. * @param {number[]|Float32Array} data Flattened data
  32975. */
  32976. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  32977. this.updateUniform(uniformName, data, data.length);
  32978. this.update();
  32979. };
  32980. /**
  32981. * Binds this uniform buffer to an effect.
  32982. * @param {Effect} effect
  32983. * @param {string} name Name of the uniform block in the shader.
  32984. */
  32985. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  32986. this._currentEffect = effect;
  32987. if (this._noUBO || !this._buffer) {
  32988. return;
  32989. }
  32990. effect.bindUniformBuffer(this._buffer, name);
  32991. };
  32992. /**
  32993. * Disposes the uniform buffer.
  32994. */
  32995. UniformBuffer.prototype.dispose = function () {
  32996. if (this._noUBO) {
  32997. return;
  32998. }
  32999. var index = this._engine._uniformBuffers.indexOf(this);
  33000. if (index !== -1) {
  33001. this._engine._uniformBuffers.splice(index, 1);
  33002. }
  33003. if (!this._buffer) {
  33004. return;
  33005. }
  33006. if (this._engine._releaseBuffer(this._buffer)) {
  33007. this._buffer = null;
  33008. }
  33009. };
  33010. // Pool for avoiding memory leaks
  33011. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  33012. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  33013. return UniformBuffer;
  33014. }());
  33015. BABYLON.UniformBuffer = UniformBuffer;
  33016. })(BABYLON || (BABYLON = {}));
  33017. //# sourceMappingURL=babylon.uniformBuffer.js.map
  33018. "use strict";
  33019. var BABYLON;
  33020. (function (BABYLON) {
  33021. var VertexData = /** @class */ (function () {
  33022. function VertexData() {
  33023. }
  33024. VertexData.prototype.set = function (data, kind) {
  33025. switch (kind) {
  33026. case BABYLON.VertexBuffer.PositionKind:
  33027. this.positions = data;
  33028. break;
  33029. case BABYLON.VertexBuffer.NormalKind:
  33030. this.normals = data;
  33031. break;
  33032. case BABYLON.VertexBuffer.TangentKind:
  33033. this.tangents = data;
  33034. break;
  33035. case BABYLON.VertexBuffer.UVKind:
  33036. this.uvs = data;
  33037. break;
  33038. case BABYLON.VertexBuffer.UV2Kind:
  33039. this.uvs2 = data;
  33040. break;
  33041. case BABYLON.VertexBuffer.UV3Kind:
  33042. this.uvs3 = data;
  33043. break;
  33044. case BABYLON.VertexBuffer.UV4Kind:
  33045. this.uvs4 = data;
  33046. break;
  33047. case BABYLON.VertexBuffer.UV5Kind:
  33048. this.uvs5 = data;
  33049. break;
  33050. case BABYLON.VertexBuffer.UV6Kind:
  33051. this.uvs6 = data;
  33052. break;
  33053. case BABYLON.VertexBuffer.ColorKind:
  33054. this.colors = data;
  33055. break;
  33056. case BABYLON.VertexBuffer.MatricesIndicesKind:
  33057. this.matricesIndices = data;
  33058. break;
  33059. case BABYLON.VertexBuffer.MatricesWeightsKind:
  33060. this.matricesWeights = data;
  33061. break;
  33062. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  33063. this.matricesIndicesExtra = data;
  33064. break;
  33065. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  33066. this.matricesWeightsExtra = data;
  33067. break;
  33068. }
  33069. };
  33070. /**
  33071. * Associates the vertexData to the passed Mesh.
  33072. * Sets it as updatable or not (default `false`).
  33073. * Returns the VertexData.
  33074. */
  33075. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  33076. this._applyTo(mesh, updatable);
  33077. return this;
  33078. };
  33079. /**
  33080. * Associates the vertexData to the passed Geometry.
  33081. * Sets it as updatable or not (default `false`).
  33082. * Returns the VertexData.
  33083. */
  33084. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  33085. this._applyTo(geometry, updatable);
  33086. return this;
  33087. };
  33088. /**
  33089. * Updates the associated mesh.
  33090. * Returns the VertexData.
  33091. */
  33092. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  33093. this._update(mesh);
  33094. return this;
  33095. };
  33096. /**
  33097. * Updates the associated geometry.
  33098. * Returns the VertexData.
  33099. */
  33100. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  33101. this._update(geometry);
  33102. return this;
  33103. };
  33104. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  33105. if (updatable === void 0) { updatable = false; }
  33106. if (this.positions) {
  33107. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  33108. }
  33109. if (this.normals) {
  33110. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  33111. }
  33112. if (this.tangents) {
  33113. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  33114. }
  33115. if (this.uvs) {
  33116. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  33117. }
  33118. if (this.uvs2) {
  33119. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  33120. }
  33121. if (this.uvs3) {
  33122. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  33123. }
  33124. if (this.uvs4) {
  33125. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  33126. }
  33127. if (this.uvs5) {
  33128. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  33129. }
  33130. if (this.uvs6) {
  33131. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  33132. }
  33133. if (this.colors) {
  33134. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  33135. }
  33136. if (this.matricesIndices) {
  33137. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  33138. }
  33139. if (this.matricesWeights) {
  33140. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  33141. }
  33142. if (this.matricesIndicesExtra) {
  33143. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  33144. }
  33145. if (this.matricesWeightsExtra) {
  33146. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  33147. }
  33148. if (this.indices) {
  33149. meshOrGeometry.setIndices(this.indices, null, updatable);
  33150. }
  33151. return this;
  33152. };
  33153. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  33154. if (this.positions) {
  33155. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  33156. }
  33157. if (this.normals) {
  33158. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  33159. }
  33160. if (this.tangents) {
  33161. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  33162. }
  33163. if (this.uvs) {
  33164. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  33165. }
  33166. if (this.uvs2) {
  33167. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  33168. }
  33169. if (this.uvs3) {
  33170. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  33171. }
  33172. if (this.uvs4) {
  33173. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  33174. }
  33175. if (this.uvs5) {
  33176. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  33177. }
  33178. if (this.uvs6) {
  33179. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  33180. }
  33181. if (this.colors) {
  33182. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  33183. }
  33184. if (this.matricesIndices) {
  33185. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  33186. }
  33187. if (this.matricesWeights) {
  33188. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  33189. }
  33190. if (this.matricesIndicesExtra) {
  33191. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  33192. }
  33193. if (this.matricesWeightsExtra) {
  33194. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  33195. }
  33196. if (this.indices) {
  33197. meshOrGeometry.setIndices(this.indices, null);
  33198. }
  33199. return this;
  33200. };
  33201. /**
  33202. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  33203. * Returns the VertexData.
  33204. */
  33205. VertexData.prototype.transform = function (matrix) {
  33206. var transformed = BABYLON.Vector3.Zero();
  33207. var index;
  33208. if (this.positions) {
  33209. var position = BABYLON.Vector3.Zero();
  33210. for (index = 0; index < this.positions.length; index += 3) {
  33211. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  33212. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  33213. this.positions[index] = transformed.x;
  33214. this.positions[index + 1] = transformed.y;
  33215. this.positions[index + 2] = transformed.z;
  33216. }
  33217. }
  33218. if (this.normals) {
  33219. var normal = BABYLON.Vector3.Zero();
  33220. for (index = 0; index < this.normals.length; index += 3) {
  33221. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  33222. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  33223. this.normals[index] = transformed.x;
  33224. this.normals[index + 1] = transformed.y;
  33225. this.normals[index + 2] = transformed.z;
  33226. }
  33227. }
  33228. if (this.tangents) {
  33229. var tangent = BABYLON.Vector4.Zero();
  33230. var tangentTransformed = BABYLON.Vector4.Zero();
  33231. for (index = 0; index < this.tangents.length; index += 4) {
  33232. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  33233. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  33234. this.tangents[index] = tangentTransformed.x;
  33235. this.tangents[index + 1] = tangentTransformed.y;
  33236. this.tangents[index + 2] = tangentTransformed.z;
  33237. this.tangents[index + 3] = tangentTransformed.w;
  33238. }
  33239. }
  33240. return this;
  33241. };
  33242. /**
  33243. * Merges the passed VertexData into the current one.
  33244. * Returns the modified VertexData.
  33245. */
  33246. VertexData.prototype.merge = function (other) {
  33247. this._validate();
  33248. other._validate();
  33249. if (!this.normals !== !other.normals ||
  33250. !this.tangents !== !other.tangents ||
  33251. !this.uvs !== !other.uvs ||
  33252. !this.uvs2 !== !other.uvs2 ||
  33253. !this.uvs3 !== !other.uvs3 ||
  33254. !this.uvs4 !== !other.uvs4 ||
  33255. !this.uvs5 !== !other.uvs5 ||
  33256. !this.uvs6 !== !other.uvs6 ||
  33257. !this.colors !== !other.colors ||
  33258. !this.matricesIndices !== !other.matricesIndices ||
  33259. !this.matricesWeights !== !other.matricesWeights ||
  33260. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  33261. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  33262. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  33263. }
  33264. if (other.indices) {
  33265. if (!this.indices) {
  33266. this.indices = [];
  33267. }
  33268. var offset = this.positions ? this.positions.length / 3 : 0;
  33269. for (var index = 0; index < other.indices.length; index++) {
  33270. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  33271. this.indices.push(other.indices[index] + offset);
  33272. }
  33273. }
  33274. this.positions = this._mergeElement(this.positions, other.positions);
  33275. this.normals = this._mergeElement(this.normals, other.normals);
  33276. this.tangents = this._mergeElement(this.tangents, other.tangents);
  33277. this.uvs = this._mergeElement(this.uvs, other.uvs);
  33278. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  33279. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  33280. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  33281. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  33282. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  33283. this.colors = this._mergeElement(this.colors, other.colors);
  33284. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  33285. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  33286. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  33287. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  33288. return this;
  33289. };
  33290. VertexData.prototype._mergeElement = function (source, other) {
  33291. if (!source) {
  33292. return other;
  33293. }
  33294. if (!other) {
  33295. return source;
  33296. }
  33297. var len = other.length + source.length;
  33298. var isSrcTypedArray = source instanceof Float32Array;
  33299. var isOthTypedArray = other instanceof Float32Array;
  33300. // use non-loop method when the source is Float32Array
  33301. if (isSrcTypedArray) {
  33302. var ret32 = new Float32Array(len);
  33303. ret32.set(source);
  33304. ret32.set(other, source.length);
  33305. return ret32;
  33306. // source is number[], when other is also use concat
  33307. }
  33308. else if (!isOthTypedArray) {
  33309. return source.concat(other);
  33310. // source is a number[], but other is a Float32Array, loop required
  33311. }
  33312. else {
  33313. var ret = source.slice(0); // copy source to a separate array
  33314. for (var i = 0, len = other.length; i < len; i++) {
  33315. ret.push(other[i]);
  33316. }
  33317. return ret;
  33318. }
  33319. };
  33320. VertexData.prototype._validate = function () {
  33321. if (!this.positions) {
  33322. throw new Error("Positions are required");
  33323. }
  33324. var getElementCount = function (kind, values) {
  33325. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  33326. if ((values.length % stride) !== 0) {
  33327. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  33328. }
  33329. return values.length / stride;
  33330. };
  33331. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  33332. var validateElementCount = function (kind, values) {
  33333. var elementCount = getElementCount(kind, values);
  33334. if (elementCount !== positionsElementCount) {
  33335. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  33336. }
  33337. };
  33338. if (this.normals)
  33339. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  33340. if (this.tangents)
  33341. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  33342. if (this.uvs)
  33343. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  33344. if (this.uvs2)
  33345. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  33346. if (this.uvs3)
  33347. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  33348. if (this.uvs4)
  33349. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  33350. if (this.uvs5)
  33351. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  33352. if (this.uvs6)
  33353. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  33354. if (this.colors)
  33355. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  33356. if (this.matricesIndices)
  33357. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  33358. if (this.matricesWeights)
  33359. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  33360. if (this.matricesIndicesExtra)
  33361. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  33362. if (this.matricesWeightsExtra)
  33363. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  33364. };
  33365. /**
  33366. * Serializes the VertexData.
  33367. * Returns a serialized object.
  33368. */
  33369. VertexData.prototype.serialize = function () {
  33370. var serializationObject = this.serialize();
  33371. if (this.positions) {
  33372. serializationObject.positions = this.positions;
  33373. }
  33374. if (this.normals) {
  33375. serializationObject.normals = this.normals;
  33376. }
  33377. if (this.tangents) {
  33378. serializationObject.tangents = this.tangents;
  33379. }
  33380. if (this.uvs) {
  33381. serializationObject.uvs = this.uvs;
  33382. }
  33383. if (this.uvs2) {
  33384. serializationObject.uvs2 = this.uvs2;
  33385. }
  33386. if (this.uvs3) {
  33387. serializationObject.uvs3 = this.uvs3;
  33388. }
  33389. if (this.uvs4) {
  33390. serializationObject.uvs4 = this.uvs4;
  33391. }
  33392. if (this.uvs5) {
  33393. serializationObject.uvs5 = this.uvs5;
  33394. }
  33395. if (this.uvs6) {
  33396. serializationObject.uvs6 = this.uvs6;
  33397. }
  33398. if (this.colors) {
  33399. serializationObject.colors = this.colors;
  33400. }
  33401. if (this.matricesIndices) {
  33402. serializationObject.matricesIndices = this.matricesIndices;
  33403. serializationObject.matricesIndices._isExpanded = true;
  33404. }
  33405. if (this.matricesWeights) {
  33406. serializationObject.matricesWeights = this.matricesWeights;
  33407. }
  33408. if (this.matricesIndicesExtra) {
  33409. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  33410. serializationObject.matricesIndicesExtra._isExpanded = true;
  33411. }
  33412. if (this.matricesWeightsExtra) {
  33413. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  33414. }
  33415. serializationObject.indices = this.indices;
  33416. return serializationObject;
  33417. };
  33418. // Statics
  33419. /**
  33420. * Returns the object VertexData associated to the passed mesh.
  33421. */
  33422. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  33423. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  33424. };
  33425. /**
  33426. * Returns the object VertexData associated to the passed geometry.
  33427. */
  33428. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  33429. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  33430. };
  33431. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  33432. var result = new VertexData();
  33433. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33434. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  33435. }
  33436. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33437. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  33438. }
  33439. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  33440. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  33441. }
  33442. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33443. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  33444. }
  33445. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33446. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  33447. }
  33448. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  33449. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  33450. }
  33451. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  33452. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  33453. }
  33454. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  33455. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  33456. }
  33457. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  33458. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  33459. }
  33460. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  33461. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  33462. }
  33463. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33464. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  33465. }
  33466. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33467. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  33468. }
  33469. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  33470. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  33471. }
  33472. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  33473. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  33474. }
  33475. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  33476. return result;
  33477. };
  33478. /**
  33479. * Creates the vertexData of the Ribbon.
  33480. */
  33481. VertexData.CreateRibbon = function (options) {
  33482. var pathArray = options.pathArray;
  33483. var closeArray = options.closeArray || false;
  33484. var closePath = options.closePath || false;
  33485. var invertUV = options.invertUV || false;
  33486. var defaultOffset = Math.floor(pathArray[0].length / 2);
  33487. var offset = options.offset || defaultOffset;
  33488. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  33489. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33490. var customUV = options.uvs;
  33491. var customColors = options.colors;
  33492. var positions = [];
  33493. var indices = [];
  33494. var normals = [];
  33495. var uvs = [];
  33496. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  33497. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  33498. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  33499. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  33500. var minlg; // minimal length among all paths from pathArray
  33501. var lg = []; // array of path lengths : nb of vertex per path
  33502. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  33503. var p; // path iterator
  33504. var i; // point iterator
  33505. var j; // point iterator
  33506. // if single path in pathArray
  33507. if (pathArray.length < 2) {
  33508. var ar1 = [];
  33509. var ar2 = [];
  33510. for (i = 0; i < pathArray[0].length - offset; i++) {
  33511. ar1.push(pathArray[0][i]);
  33512. ar2.push(pathArray[0][i + offset]);
  33513. }
  33514. pathArray = [ar1, ar2];
  33515. }
  33516. // positions and horizontal distances (u)
  33517. var idc = 0;
  33518. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  33519. var path;
  33520. var l;
  33521. minlg = pathArray[0].length;
  33522. var vectlg;
  33523. var dist;
  33524. for (p = 0; p < pathArray.length; p++) {
  33525. uTotalDistance[p] = 0;
  33526. us[p] = [0];
  33527. path = pathArray[p];
  33528. l = path.length;
  33529. minlg = (minlg < l) ? minlg : l;
  33530. j = 0;
  33531. while (j < l) {
  33532. positions.push(path[j].x, path[j].y, path[j].z);
  33533. if (j > 0) {
  33534. vectlg = path[j].subtract(path[j - 1]).length();
  33535. dist = vectlg + uTotalDistance[p];
  33536. us[p].push(dist);
  33537. uTotalDistance[p] = dist;
  33538. }
  33539. j++;
  33540. }
  33541. if (closePath) {
  33542. j--;
  33543. positions.push(path[0].x, path[0].y, path[0].z);
  33544. vectlg = path[j].subtract(path[0]).length();
  33545. dist = vectlg + uTotalDistance[p];
  33546. us[p].push(dist);
  33547. uTotalDistance[p] = dist;
  33548. }
  33549. lg[p] = l + closePathCorr;
  33550. idx[p] = idc;
  33551. idc += (l + closePathCorr);
  33552. }
  33553. // vertical distances (v)
  33554. var path1;
  33555. var path2;
  33556. var vertex1 = null;
  33557. var vertex2 = null;
  33558. for (i = 0; i < minlg + closePathCorr; i++) {
  33559. vTotalDistance[i] = 0;
  33560. vs[i] = [0];
  33561. for (p = 0; p < pathArray.length - 1; p++) {
  33562. path1 = pathArray[p];
  33563. path2 = pathArray[p + 1];
  33564. if (i === minlg) {
  33565. vertex1 = path1[0];
  33566. vertex2 = path2[0];
  33567. }
  33568. else {
  33569. vertex1 = path1[i];
  33570. vertex2 = path2[i];
  33571. }
  33572. vectlg = vertex2.subtract(vertex1).length();
  33573. dist = vectlg + vTotalDistance[i];
  33574. vs[i].push(dist);
  33575. vTotalDistance[i] = dist;
  33576. }
  33577. if (closeArray && vertex2 && vertex1) {
  33578. path1 = pathArray[p];
  33579. path2 = pathArray[0];
  33580. if (i === minlg) {
  33581. vertex2 = path2[0];
  33582. }
  33583. vectlg = vertex2.subtract(vertex1).length();
  33584. dist = vectlg + vTotalDistance[i];
  33585. vTotalDistance[i] = dist;
  33586. }
  33587. }
  33588. // uvs
  33589. var u;
  33590. var v;
  33591. if (customUV) {
  33592. for (p = 0; p < customUV.length; p++) {
  33593. uvs.push(customUV[p].x, customUV[p].y);
  33594. }
  33595. }
  33596. else {
  33597. for (p = 0; p < pathArray.length; p++) {
  33598. for (i = 0; i < minlg + closePathCorr; i++) {
  33599. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  33600. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  33601. if (invertUV) {
  33602. uvs.push(v, u);
  33603. }
  33604. else {
  33605. uvs.push(u, v);
  33606. }
  33607. }
  33608. }
  33609. }
  33610. // indices
  33611. p = 0; // path index
  33612. var pi = 0; // positions array index
  33613. var l1 = lg[p] - 1; // path1 length
  33614. var l2 = lg[p + 1] - 1; // path2 length
  33615. var min = (l1 < l2) ? l1 : l2; // current path stop index
  33616. var shft = idx[1] - idx[0]; // shift
  33617. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  33618. while (pi <= min && p < path1nb) {
  33619. // 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
  33620. indices.push(pi, pi + shft, pi + 1);
  33621. indices.push(pi + shft + 1, pi + 1, pi + shft);
  33622. pi += 1;
  33623. if (pi === min) {
  33624. p++;
  33625. if (p === lg.length - 1) {
  33626. shft = idx[0] - idx[p];
  33627. l1 = lg[p] - 1;
  33628. l2 = lg[0] - 1;
  33629. }
  33630. else {
  33631. shft = idx[p + 1] - idx[p];
  33632. l1 = lg[p] - 1;
  33633. l2 = lg[p + 1] - 1;
  33634. }
  33635. pi = idx[p];
  33636. min = (l1 < l2) ? l1 + pi : l2 + pi;
  33637. }
  33638. }
  33639. // normals
  33640. VertexData.ComputeNormals(positions, indices, normals);
  33641. if (closePath) {
  33642. var indexFirst = 0;
  33643. var indexLast = 0;
  33644. for (p = 0; p < pathArray.length; p++) {
  33645. indexFirst = idx[p] * 3;
  33646. if (p + 1 < pathArray.length) {
  33647. indexLast = (idx[p + 1] - 1) * 3;
  33648. }
  33649. else {
  33650. indexLast = normals.length - 3;
  33651. }
  33652. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  33653. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  33654. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  33655. normals[indexLast] = normals[indexFirst];
  33656. normals[indexLast + 1] = normals[indexFirst + 1];
  33657. normals[indexLast + 2] = normals[indexFirst + 2];
  33658. }
  33659. }
  33660. // sides
  33661. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33662. // Colors
  33663. var colors = null;
  33664. if (customColors) {
  33665. colors = new Float32Array(customColors.length * 4);
  33666. for (var c = 0; c < customColors.length; c++) {
  33667. colors[c * 4] = customColors[c].r;
  33668. colors[c * 4 + 1] = customColors[c].g;
  33669. colors[c * 4 + 2] = customColors[c].b;
  33670. colors[c * 4 + 3] = customColors[c].a;
  33671. }
  33672. }
  33673. // Result
  33674. var vertexData = new VertexData();
  33675. var positions32 = new Float32Array(positions);
  33676. var normals32 = new Float32Array(normals);
  33677. var uvs32 = new Float32Array(uvs);
  33678. vertexData.indices = indices;
  33679. vertexData.positions = positions32;
  33680. vertexData.normals = normals32;
  33681. vertexData.uvs = uvs32;
  33682. if (colors) {
  33683. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  33684. }
  33685. if (closePath) {
  33686. vertexData._idx = idx;
  33687. }
  33688. return vertexData;
  33689. };
  33690. /**
  33691. * Creates the VertexData of the Box.
  33692. */
  33693. VertexData.CreateBox = function (options) {
  33694. var normalsSource = [
  33695. new BABYLON.Vector3(0, 0, 1),
  33696. new BABYLON.Vector3(0, 0, -1),
  33697. new BABYLON.Vector3(1, 0, 0),
  33698. new BABYLON.Vector3(-1, 0, 0),
  33699. new BABYLON.Vector3(0, 1, 0),
  33700. new BABYLON.Vector3(0, -1, 0)
  33701. ];
  33702. var indices = [];
  33703. var positions = [];
  33704. var normals = [];
  33705. var uvs = [];
  33706. var width = options.width || options.size || 1;
  33707. var height = options.height || options.size || 1;
  33708. var depth = options.depth || options.size || 1;
  33709. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33710. var faceUV = options.faceUV || new Array(6);
  33711. var faceColors = options.faceColors;
  33712. var colors = [];
  33713. // default face colors and UV if undefined
  33714. for (var f = 0; f < 6; f++) {
  33715. if (faceUV[f] === undefined) {
  33716. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33717. }
  33718. if (faceColors && faceColors[f] === undefined) {
  33719. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33720. }
  33721. }
  33722. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  33723. // Create each face in turn.
  33724. for (var index = 0; index < normalsSource.length; index++) {
  33725. var normal = normalsSource[index];
  33726. // Get two vectors perpendicular to the face normal and to each other.
  33727. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  33728. var side2 = BABYLON.Vector3.Cross(normal, side1);
  33729. // Six indices (two triangles) per face.
  33730. var verticesLength = positions.length / 3;
  33731. indices.push(verticesLength);
  33732. indices.push(verticesLength + 1);
  33733. indices.push(verticesLength + 2);
  33734. indices.push(verticesLength);
  33735. indices.push(verticesLength + 2);
  33736. indices.push(verticesLength + 3);
  33737. // Four vertices per face.
  33738. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  33739. positions.push(vertex.x, vertex.y, vertex.z);
  33740. normals.push(normal.x, normal.y, normal.z);
  33741. uvs.push(faceUV[index].z, faceUV[index].w);
  33742. if (faceColors) {
  33743. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33744. }
  33745. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  33746. positions.push(vertex.x, vertex.y, vertex.z);
  33747. normals.push(normal.x, normal.y, normal.z);
  33748. uvs.push(faceUV[index].x, faceUV[index].w);
  33749. if (faceColors) {
  33750. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33751. }
  33752. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  33753. positions.push(vertex.x, vertex.y, vertex.z);
  33754. normals.push(normal.x, normal.y, normal.z);
  33755. uvs.push(faceUV[index].x, faceUV[index].y);
  33756. if (faceColors) {
  33757. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33758. }
  33759. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  33760. positions.push(vertex.x, vertex.y, vertex.z);
  33761. normals.push(normal.x, normal.y, normal.z);
  33762. uvs.push(faceUV[index].z, faceUV[index].y);
  33763. if (faceColors) {
  33764. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33765. }
  33766. }
  33767. // sides
  33768. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33769. // Result
  33770. var vertexData = new VertexData();
  33771. vertexData.indices = indices;
  33772. vertexData.positions = positions;
  33773. vertexData.normals = normals;
  33774. vertexData.uvs = uvs;
  33775. if (faceColors) {
  33776. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33777. vertexData.colors = totalColors;
  33778. }
  33779. return vertexData;
  33780. };
  33781. /**
  33782. * Creates the VertexData of the Sphere.
  33783. */
  33784. VertexData.CreateSphere = function (options) {
  33785. var segments = options.segments || 32;
  33786. var diameterX = options.diameterX || options.diameter || 1;
  33787. var diameterY = options.diameterY || options.diameter || 1;
  33788. var diameterZ = options.diameterZ || options.diameter || 1;
  33789. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33790. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33791. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33792. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33793. var totalZRotationSteps = 2 + segments;
  33794. var totalYRotationSteps = 2 * totalZRotationSteps;
  33795. var indices = [];
  33796. var positions = [];
  33797. var normals = [];
  33798. var uvs = [];
  33799. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33800. var normalizedZ = zRotationStep / totalZRotationSteps;
  33801. var angleZ = normalizedZ * Math.PI * slice;
  33802. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33803. var normalizedY = yRotationStep / totalYRotationSteps;
  33804. var angleY = normalizedY * Math.PI * 2 * arc;
  33805. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33806. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33807. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33808. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33809. var vertex = complete.multiply(radius);
  33810. var normal = complete.divide(radius).normalize();
  33811. positions.push(vertex.x, vertex.y, vertex.z);
  33812. normals.push(normal.x, normal.y, normal.z);
  33813. uvs.push(normalizedY, normalizedZ);
  33814. }
  33815. if (zRotationStep > 0) {
  33816. var verticesCount = positions.length / 3;
  33817. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33818. indices.push((firstIndex));
  33819. indices.push((firstIndex + 1));
  33820. indices.push(firstIndex + totalYRotationSteps + 1);
  33821. indices.push((firstIndex + totalYRotationSteps + 1));
  33822. indices.push((firstIndex + 1));
  33823. indices.push((firstIndex + totalYRotationSteps + 2));
  33824. }
  33825. }
  33826. }
  33827. // Sides
  33828. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33829. // Result
  33830. var vertexData = new VertexData();
  33831. vertexData.indices = indices;
  33832. vertexData.positions = positions;
  33833. vertexData.normals = normals;
  33834. vertexData.uvs = uvs;
  33835. return vertexData;
  33836. };
  33837. /**
  33838. * Creates the VertexData of the Cylinder or Cone.
  33839. */
  33840. VertexData.CreateCylinder = function (options) {
  33841. var height = options.height || 2;
  33842. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33843. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33844. var tessellation = options.tessellation || 24;
  33845. var subdivisions = options.subdivisions || 1;
  33846. var hasRings = options.hasRings ? true : false;
  33847. var enclose = options.enclose ? true : false;
  33848. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33849. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33850. var faceUV = options.faceUV || new Array(3);
  33851. var faceColors = options.faceColors;
  33852. // default face colors and UV if undefined
  33853. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33854. var ringNb = (hasRings) ? subdivisions : 1;
  33855. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33856. var f;
  33857. for (f = 0; f < surfaceNb; f++) {
  33858. if (faceColors && faceColors[f] === undefined) {
  33859. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33860. }
  33861. }
  33862. for (f = 0; f < surfaceNb; f++) {
  33863. if (faceUV && faceUV[f] === undefined) {
  33864. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33865. }
  33866. }
  33867. var indices = new Array();
  33868. var positions = new Array();
  33869. var normals = new Array();
  33870. var uvs = new Array();
  33871. var colors = new Array();
  33872. var angle_step = Math.PI * 2 * arc / tessellation;
  33873. var angle;
  33874. var h;
  33875. var radius;
  33876. var tan = (diameterBottom - diameterTop) / 2 / height;
  33877. var ringVertex = BABYLON.Vector3.Zero();
  33878. var ringNormal = BABYLON.Vector3.Zero();
  33879. var ringFirstVertex = BABYLON.Vector3.Zero();
  33880. var ringFirstNormal = BABYLON.Vector3.Zero();
  33881. var quadNormal = BABYLON.Vector3.Zero();
  33882. var Y = BABYLON.Axis.Y;
  33883. // positions, normals, uvs
  33884. var i;
  33885. var j;
  33886. var r;
  33887. var ringIdx = 1;
  33888. var s = 1; // surface index
  33889. var cs = 0;
  33890. var v = 0;
  33891. for (i = 0; i <= subdivisions; i++) {
  33892. h = i / subdivisions;
  33893. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33894. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33895. for (r = 0; r < ringIdx; r++) {
  33896. if (hasRings) {
  33897. s += r;
  33898. }
  33899. if (enclose) {
  33900. s += 2 * r;
  33901. }
  33902. for (j = 0; j <= tessellation; j++) {
  33903. angle = j * angle_step;
  33904. // position
  33905. ringVertex.x = Math.cos(-angle) * radius;
  33906. ringVertex.y = -height / 2 + h * height;
  33907. ringVertex.z = Math.sin(-angle) * radius;
  33908. // normal
  33909. if (diameterTop === 0 && i === subdivisions) {
  33910. // if no top cap, reuse former normals
  33911. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33912. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33913. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33914. }
  33915. else {
  33916. ringNormal.x = ringVertex.x;
  33917. ringNormal.z = ringVertex.z;
  33918. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33919. ringNormal.normalize();
  33920. }
  33921. // keep first ring vertex values for enclose
  33922. if (j === 0) {
  33923. ringFirstVertex.copyFrom(ringVertex);
  33924. ringFirstNormal.copyFrom(ringNormal);
  33925. }
  33926. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33927. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33928. if (hasRings) {
  33929. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33930. }
  33931. else {
  33932. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33933. }
  33934. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33935. if (faceColors) {
  33936. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33937. }
  33938. }
  33939. // if enclose, add four vertices and their dedicated normals
  33940. if (arc !== 1 && enclose) {
  33941. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33942. positions.push(0, ringVertex.y, 0);
  33943. positions.push(0, ringVertex.y, 0);
  33944. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33945. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33946. quadNormal.normalize();
  33947. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33948. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33949. quadNormal.normalize();
  33950. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33951. if (hasRings) {
  33952. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33953. }
  33954. else {
  33955. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33956. }
  33957. uvs.push(faceUV[s + 1].x, v);
  33958. uvs.push(faceUV[s + 1].z, v);
  33959. if (hasRings) {
  33960. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33961. }
  33962. else {
  33963. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33964. }
  33965. uvs.push(faceUV[s + 2].x, v);
  33966. uvs.push(faceUV[s + 2].z, v);
  33967. if (faceColors) {
  33968. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33969. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33970. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33971. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33972. }
  33973. }
  33974. if (cs !== s) {
  33975. cs = s;
  33976. }
  33977. }
  33978. }
  33979. // indices
  33980. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33981. var s;
  33982. i = 0;
  33983. for (s = 0; s < subdivisions; s++) {
  33984. var i0 = 0;
  33985. var i1 = 0;
  33986. var i2 = 0;
  33987. var i3 = 0;
  33988. for (j = 0; j < tessellation; j++) {
  33989. i0 = i * (e + 1) + j;
  33990. i1 = (i + 1) * (e + 1) + j;
  33991. i2 = i * (e + 1) + (j + 1);
  33992. i3 = (i + 1) * (e + 1) + (j + 1);
  33993. indices.push(i0, i1, i2);
  33994. indices.push(i3, i2, i1);
  33995. }
  33996. if (arc !== 1 && enclose) {
  33997. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33998. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33999. indices.push(i0 + 4, i1 + 4, i2 + 4);
  34000. indices.push(i3 + 4, i2 + 4, i1 + 4);
  34001. }
  34002. i = (hasRings) ? (i + 2) : (i + 1);
  34003. }
  34004. // Caps
  34005. var createCylinderCap = function (isTop) {
  34006. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  34007. if (radius === 0) {
  34008. return;
  34009. }
  34010. // Cap positions, normals & uvs
  34011. var angle;
  34012. var circleVector;
  34013. var i;
  34014. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  34015. var c = null;
  34016. if (faceColors) {
  34017. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  34018. }
  34019. // cap center
  34020. var vbase = positions.length / 3;
  34021. var offset = isTop ? height / 2 : -height / 2;
  34022. var center = new BABYLON.Vector3(0, offset, 0);
  34023. positions.push(center.x, center.y, center.z);
  34024. normals.push(0, isTop ? 1 : -1, 0);
  34025. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  34026. if (c) {
  34027. colors.push(c.r, c.g, c.b, c.a);
  34028. }
  34029. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  34030. for (i = 0; i <= tessellation; i++) {
  34031. angle = Math.PI * 2 * i * arc / tessellation;
  34032. var cos = Math.cos(-angle);
  34033. var sin = Math.sin(-angle);
  34034. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  34035. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  34036. positions.push(circleVector.x, circleVector.y, circleVector.z);
  34037. normals.push(0, isTop ? 1 : -1, 0);
  34038. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  34039. if (c) {
  34040. colors.push(c.r, c.g, c.b, c.a);
  34041. }
  34042. }
  34043. // Cap indices
  34044. for (i = 0; i < tessellation; i++) {
  34045. if (!isTop) {
  34046. indices.push(vbase);
  34047. indices.push(vbase + (i + 1));
  34048. indices.push(vbase + (i + 2));
  34049. }
  34050. else {
  34051. indices.push(vbase);
  34052. indices.push(vbase + (i + 2));
  34053. indices.push(vbase + (i + 1));
  34054. }
  34055. }
  34056. };
  34057. // add caps to geometry
  34058. createCylinderCap(false);
  34059. createCylinderCap(true);
  34060. // Sides
  34061. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34062. var vertexData = new VertexData();
  34063. vertexData.indices = indices;
  34064. vertexData.positions = positions;
  34065. vertexData.normals = normals;
  34066. vertexData.uvs = uvs;
  34067. if (faceColors) {
  34068. vertexData.colors = colors;
  34069. }
  34070. return vertexData;
  34071. };
  34072. /**
  34073. * Creates the VertexData of the Torus.
  34074. */
  34075. VertexData.CreateTorus = function (options) {
  34076. var indices = [];
  34077. var positions = [];
  34078. var normals = [];
  34079. var uvs = [];
  34080. var diameter = options.diameter || 1;
  34081. var thickness = options.thickness || 0.5;
  34082. var tessellation = options.tessellation || 16;
  34083. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34084. var stride = tessellation + 1;
  34085. for (var i = 0; i <= tessellation; i++) {
  34086. var u = i / tessellation;
  34087. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  34088. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  34089. for (var j = 0; j <= tessellation; j++) {
  34090. var v = 1 - j / tessellation;
  34091. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  34092. var dx = Math.cos(innerAngle);
  34093. var dy = Math.sin(innerAngle);
  34094. // Create a vertex.
  34095. var normal = new BABYLON.Vector3(dx, dy, 0);
  34096. var position = normal.scale(thickness / 2);
  34097. var textureCoordinate = new BABYLON.Vector2(u, v);
  34098. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  34099. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  34100. positions.push(position.x, position.y, position.z);
  34101. normals.push(normal.x, normal.y, normal.z);
  34102. uvs.push(textureCoordinate.x, textureCoordinate.y);
  34103. // And create indices for two triangles.
  34104. var nextI = (i + 1) % stride;
  34105. var nextJ = (j + 1) % stride;
  34106. indices.push(i * stride + j);
  34107. indices.push(i * stride + nextJ);
  34108. indices.push(nextI * stride + j);
  34109. indices.push(i * stride + nextJ);
  34110. indices.push(nextI * stride + nextJ);
  34111. indices.push(nextI * stride + j);
  34112. }
  34113. }
  34114. // Sides
  34115. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34116. // Result
  34117. var vertexData = new VertexData();
  34118. vertexData.indices = indices;
  34119. vertexData.positions = positions;
  34120. vertexData.normals = normals;
  34121. vertexData.uvs = uvs;
  34122. return vertexData;
  34123. };
  34124. /**
  34125. * Creates the VertexData of the LineSystem.
  34126. */
  34127. VertexData.CreateLineSystem = function (options) {
  34128. var indices = [];
  34129. var positions = [];
  34130. var lines = options.lines;
  34131. var colors = options.colors;
  34132. var vertexColors = [];
  34133. var idx = 0;
  34134. for (var l = 0; l < lines.length; l++) {
  34135. var points = lines[l];
  34136. for (var index = 0; index < points.length; index++) {
  34137. positions.push(points[index].x, points[index].y, points[index].z);
  34138. if (colors) {
  34139. var color = colors[l];
  34140. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  34141. }
  34142. if (index > 0) {
  34143. indices.push(idx - 1);
  34144. indices.push(idx);
  34145. }
  34146. idx++;
  34147. }
  34148. }
  34149. var vertexData = new VertexData();
  34150. vertexData.indices = indices;
  34151. vertexData.positions = positions;
  34152. if (colors) {
  34153. vertexData.colors = vertexColors;
  34154. }
  34155. return vertexData;
  34156. };
  34157. /**
  34158. * Create the VertexData of the DashedLines.
  34159. */
  34160. VertexData.CreateDashedLines = function (options) {
  34161. var dashSize = options.dashSize || 3;
  34162. var gapSize = options.gapSize || 1;
  34163. var dashNb = options.dashNb || 200;
  34164. var points = options.points;
  34165. var positions = new Array();
  34166. var indices = new Array();
  34167. var curvect = BABYLON.Vector3.Zero();
  34168. var lg = 0;
  34169. var nb = 0;
  34170. var shft = 0;
  34171. var dashshft = 0;
  34172. var curshft = 0;
  34173. var idx = 0;
  34174. var i = 0;
  34175. for (i = 0; i < points.length - 1; i++) {
  34176. points[i + 1].subtractToRef(points[i], curvect);
  34177. lg += curvect.length();
  34178. }
  34179. shft = lg / dashNb;
  34180. dashshft = dashSize * shft / (dashSize + gapSize);
  34181. for (i = 0; i < points.length - 1; i++) {
  34182. points[i + 1].subtractToRef(points[i], curvect);
  34183. nb = Math.floor(curvect.length() / shft);
  34184. curvect.normalize();
  34185. for (var j = 0; j < nb; j++) {
  34186. curshft = shft * j;
  34187. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  34188. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  34189. indices.push(idx, idx + 1);
  34190. idx += 2;
  34191. }
  34192. }
  34193. // Result
  34194. var vertexData = new VertexData();
  34195. vertexData.positions = positions;
  34196. vertexData.indices = indices;
  34197. return vertexData;
  34198. };
  34199. /**
  34200. * Creates the VertexData of the Ground.
  34201. */
  34202. VertexData.CreateGround = function (options) {
  34203. var indices = [];
  34204. var positions = [];
  34205. var normals = [];
  34206. var uvs = [];
  34207. var row, col;
  34208. var width = options.width || 1;
  34209. var height = options.height || 1;
  34210. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  34211. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  34212. for (row = 0; row <= subdivisionsY; row++) {
  34213. for (col = 0; col <= subdivisionsX; col++) {
  34214. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  34215. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34216. positions.push(position.x, position.y, position.z);
  34217. normals.push(normal.x, normal.y, normal.z);
  34218. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  34219. }
  34220. }
  34221. for (row = 0; row < subdivisionsY; row++) {
  34222. for (col = 0; col < subdivisionsX; col++) {
  34223. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34224. indices.push(col + 1 + row * (subdivisionsX + 1));
  34225. indices.push(col + row * (subdivisionsX + 1));
  34226. indices.push(col + (row + 1) * (subdivisionsX + 1));
  34227. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34228. indices.push(col + row * (subdivisionsX + 1));
  34229. }
  34230. }
  34231. // Result
  34232. var vertexData = new VertexData();
  34233. vertexData.indices = indices;
  34234. vertexData.positions = positions;
  34235. vertexData.normals = normals;
  34236. vertexData.uvs = uvs;
  34237. return vertexData;
  34238. };
  34239. /**
  34240. * Creates the VertexData of the TiledGround.
  34241. */
  34242. VertexData.CreateTiledGround = function (options) {
  34243. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  34244. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  34245. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  34246. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  34247. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  34248. var precision = options.precision || { w: 1, h: 1 };
  34249. var indices = new Array();
  34250. var positions = new Array();
  34251. var normals = new Array();
  34252. var uvs = new Array();
  34253. var row, col, tileRow, tileCol;
  34254. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  34255. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  34256. precision.w = (precision.w < 1) ? 1 : precision.w;
  34257. precision.h = (precision.h < 1) ? 1 : precision.h;
  34258. var tileSize = {
  34259. 'w': (xmax - xmin) / subdivisions.w,
  34260. 'h': (zmax - zmin) / subdivisions.h
  34261. };
  34262. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  34263. // Indices
  34264. var base = positions.length / 3;
  34265. var rowLength = precision.w + 1;
  34266. for (row = 0; row < precision.h; row++) {
  34267. for (col = 0; col < precision.w; col++) {
  34268. var square = [
  34269. base + col + row * rowLength,
  34270. base + (col + 1) + row * rowLength,
  34271. base + (col + 1) + (row + 1) * rowLength,
  34272. base + col + (row + 1) * rowLength
  34273. ];
  34274. indices.push(square[1]);
  34275. indices.push(square[2]);
  34276. indices.push(square[3]);
  34277. indices.push(square[0]);
  34278. indices.push(square[1]);
  34279. indices.push(square[3]);
  34280. }
  34281. }
  34282. // Position, normals and uvs
  34283. var position = BABYLON.Vector3.Zero();
  34284. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34285. for (row = 0; row <= precision.h; row++) {
  34286. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  34287. for (col = 0; col <= precision.w; col++) {
  34288. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  34289. position.y = 0;
  34290. positions.push(position.x, position.y, position.z);
  34291. normals.push(normal.x, normal.y, normal.z);
  34292. uvs.push(col / precision.w, row / precision.h);
  34293. }
  34294. }
  34295. }
  34296. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  34297. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  34298. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  34299. }
  34300. }
  34301. // Result
  34302. var vertexData = new VertexData();
  34303. vertexData.indices = indices;
  34304. vertexData.positions = positions;
  34305. vertexData.normals = normals;
  34306. vertexData.uvs = uvs;
  34307. return vertexData;
  34308. };
  34309. /**
  34310. * Creates the VertexData of the Ground designed from a heightmap.
  34311. */
  34312. VertexData.CreateGroundFromHeightMap = function (options) {
  34313. var indices = [];
  34314. var positions = [];
  34315. var normals = [];
  34316. var uvs = [];
  34317. var row, col;
  34318. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  34319. // Vertices
  34320. for (row = 0; row <= options.subdivisions; row++) {
  34321. for (col = 0; col <= options.subdivisions; col++) {
  34322. 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));
  34323. // Compute height
  34324. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  34325. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  34326. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  34327. var r = options.buffer[pos] / 255.0;
  34328. var g = options.buffer[pos + 1] / 255.0;
  34329. var b = options.buffer[pos + 2] / 255.0;
  34330. var gradient = r * filter.r + g * filter.g + b * filter.b;
  34331. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  34332. // Add vertex
  34333. positions.push(position.x, position.y, position.z);
  34334. normals.push(0, 0, 0);
  34335. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  34336. }
  34337. }
  34338. // Indices
  34339. for (row = 0; row < options.subdivisions; row++) {
  34340. for (col = 0; col < options.subdivisions; col++) {
  34341. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34342. indices.push(col + 1 + row * (options.subdivisions + 1));
  34343. indices.push(col + row * (options.subdivisions + 1));
  34344. indices.push(col + (row + 1) * (options.subdivisions + 1));
  34345. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34346. indices.push(col + row * (options.subdivisions + 1));
  34347. }
  34348. }
  34349. // Normals
  34350. VertexData.ComputeNormals(positions, indices, normals);
  34351. // Result
  34352. var vertexData = new VertexData();
  34353. vertexData.indices = indices;
  34354. vertexData.positions = positions;
  34355. vertexData.normals = normals;
  34356. vertexData.uvs = uvs;
  34357. return vertexData;
  34358. };
  34359. /**
  34360. * Creates the VertexData of the Plane.
  34361. */
  34362. VertexData.CreatePlane = function (options) {
  34363. var indices = [];
  34364. var positions = [];
  34365. var normals = [];
  34366. var uvs = [];
  34367. var width = options.width || options.size || 1;
  34368. var height = options.height || options.size || 1;
  34369. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34370. // Vertices
  34371. var halfWidth = width / 2.0;
  34372. var halfHeight = height / 2.0;
  34373. positions.push(-halfWidth, -halfHeight, 0);
  34374. normals.push(0, 0, -1.0);
  34375. uvs.push(0.0, 0.0);
  34376. positions.push(halfWidth, -halfHeight, 0);
  34377. normals.push(0, 0, -1.0);
  34378. uvs.push(1.0, 0.0);
  34379. positions.push(halfWidth, halfHeight, 0);
  34380. normals.push(0, 0, -1.0);
  34381. uvs.push(1.0, 1.0);
  34382. positions.push(-halfWidth, halfHeight, 0);
  34383. normals.push(0, 0, -1.0);
  34384. uvs.push(0.0, 1.0);
  34385. // Indices
  34386. indices.push(0);
  34387. indices.push(1);
  34388. indices.push(2);
  34389. indices.push(0);
  34390. indices.push(2);
  34391. indices.push(3);
  34392. // Sides
  34393. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34394. // Result
  34395. var vertexData = new VertexData();
  34396. vertexData.indices = indices;
  34397. vertexData.positions = positions;
  34398. vertexData.normals = normals;
  34399. vertexData.uvs = uvs;
  34400. return vertexData;
  34401. };
  34402. /**
  34403. * Creates the VertexData of the Disc or regular Polygon.
  34404. */
  34405. VertexData.CreateDisc = function (options) {
  34406. var positions = new Array();
  34407. var indices = new Array();
  34408. var normals = new Array();
  34409. var uvs = new Array();
  34410. var radius = options.radius || 0.5;
  34411. var tessellation = options.tessellation || 64;
  34412. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  34413. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34414. // positions and uvs
  34415. positions.push(0, 0, 0); // disc center first
  34416. uvs.push(0.5, 0.5);
  34417. var theta = Math.PI * 2 * arc;
  34418. var step = theta / tessellation;
  34419. for (var a = 0; a < theta; a += step) {
  34420. var x = Math.cos(a);
  34421. var y = Math.sin(a);
  34422. var u = (x + 1) / 2;
  34423. var v = (1 - y) / 2;
  34424. positions.push(radius * x, radius * y, 0);
  34425. uvs.push(u, v);
  34426. }
  34427. if (arc === 1) {
  34428. positions.push(positions[3], positions[4], positions[5]); // close the circle
  34429. uvs.push(uvs[2], uvs[3]);
  34430. }
  34431. //indices
  34432. var vertexNb = positions.length / 3;
  34433. for (var i = 1; i < vertexNb - 1; i++) {
  34434. indices.push(i + 1, 0, i);
  34435. }
  34436. // result
  34437. VertexData.ComputeNormals(positions, indices, normals);
  34438. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34439. var vertexData = new VertexData();
  34440. vertexData.indices = indices;
  34441. vertexData.positions = positions;
  34442. vertexData.normals = normals;
  34443. vertexData.uvs = uvs;
  34444. return vertexData;
  34445. };
  34446. /**
  34447. * Re-creates the VertexData of the Polygon for sideOrientation.
  34448. */
  34449. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  34450. var faceUV = fUV || new Array(3);
  34451. var faceColors = fColors;
  34452. var colors = [];
  34453. // default face colors and UV if undefined
  34454. for (var f = 0; f < 3; f++) {
  34455. if (faceUV[f] === undefined) {
  34456. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34457. }
  34458. if (faceColors && faceColors[f] === undefined) {
  34459. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34460. }
  34461. }
  34462. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34463. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34464. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  34465. var indices = polygon.getIndices();
  34466. // set face colours and textures
  34467. var idx = 0;
  34468. var face = 0;
  34469. for (var index = 0; index < normals.length; index += 3) {
  34470. //Edge Face no. 1
  34471. if (Math.abs(normals[index + 1]) < 0.001) {
  34472. face = 1;
  34473. }
  34474. //Top Face no. 0
  34475. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  34476. face = 0;
  34477. }
  34478. //Bottom Face no. 2
  34479. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  34480. face = 2;
  34481. }
  34482. idx = index / 3;
  34483. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  34484. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  34485. if (faceColors) {
  34486. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  34487. }
  34488. }
  34489. // sides
  34490. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  34491. // Result
  34492. var vertexData = new VertexData();
  34493. vertexData.indices = indices;
  34494. vertexData.positions = positions;
  34495. vertexData.normals = normals;
  34496. vertexData.uvs = uvs;
  34497. if (faceColors) {
  34498. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  34499. vertexData.colors = totalColors;
  34500. }
  34501. return vertexData;
  34502. };
  34503. /**
  34504. * Creates the VertexData of the IcoSphere.
  34505. */
  34506. VertexData.CreateIcoSphere = function (options) {
  34507. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34508. var radius = options.radius || 1;
  34509. var flat = (options.flat === undefined) ? true : options.flat;
  34510. var subdivisions = options.subdivisions || 4;
  34511. var radiusX = options.radiusX || radius;
  34512. var radiusY = options.radiusY || radius;
  34513. var radiusZ = options.radiusZ || radius;
  34514. var t = (1 + Math.sqrt(5)) / 2;
  34515. // 12 vertex x,y,z
  34516. var ico_vertices = [
  34517. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  34518. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  34519. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  34520. ];
  34521. // index of 3 vertex makes a face of icopshere
  34522. var ico_indices = [
  34523. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  34524. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  34525. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  34526. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  34527. ];
  34528. // vertex for uv have aliased position, not for UV
  34529. var vertices_unalias_id = [
  34530. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  34531. // vertex alias
  34532. 0,
  34533. 2,
  34534. 3,
  34535. 3,
  34536. 3,
  34537. 4,
  34538. 7,
  34539. 8,
  34540. 9,
  34541. 9,
  34542. 10,
  34543. 11 // 23: B + 12
  34544. ];
  34545. // uv as integer step (not pixels !)
  34546. var ico_vertexuv = [
  34547. 5, 1, 3, 1, 6, 4, 0, 0,
  34548. 5, 3, 4, 2, 2, 2, 4, 0,
  34549. 2, 0, 1, 1, 6, 0, 6, 2,
  34550. // vertex alias (for same vertex on different faces)
  34551. 0, 4,
  34552. 3, 3,
  34553. 4, 4,
  34554. 3, 1,
  34555. 4, 2,
  34556. 4, 4,
  34557. 0, 2,
  34558. 1, 1,
  34559. 2, 2,
  34560. 3, 3,
  34561. 1, 3,
  34562. 2, 4 // 23: B + 12
  34563. ];
  34564. // Vertices[0, 1, ...9, A, B] : position on UV plane
  34565. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  34566. // First island of uv mapping
  34567. // v = 4h 3+ 2
  34568. // v = 3h 9+ 4
  34569. // v = 2h 9+ 5 B
  34570. // v = 1h 9 1 0
  34571. // v = 0h 3 8 7 A
  34572. // u = 0 1 2 3 4 5 6 *a
  34573. // Second island of uv mapping
  34574. // v = 4h 0+ B+ 4+
  34575. // v = 3h A+ 2+
  34576. // v = 2h 7+ 6 3+
  34577. // v = 1h 8+ 3+
  34578. // v = 0h
  34579. // u = 0 1 2 3 4 5 6 *a
  34580. // Face layout on texture UV mapping
  34581. // ============
  34582. // \ 4 /\ 16 / ======
  34583. // \ / \ / /\ 11 /
  34584. // \/ 7 \/ / \ /
  34585. // ======= / 10 \/
  34586. // /\ 17 /\ =======
  34587. // / \ / \ \ 15 /\
  34588. // / 8 \/ 12 \ \ / \
  34589. // ============ \/ 6 \
  34590. // \ 18 /\ ============
  34591. // \ / \ \ 5 /\ 0 /
  34592. // \/ 13 \ \ / \ /
  34593. // ======= \/ 1 \/
  34594. // =============
  34595. // /\ 19 /\ 2 /\
  34596. // / \ / \ / \
  34597. // / 14 \/ 9 \/ 3 \
  34598. // ===================
  34599. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  34600. var ustep = 138 / 1024;
  34601. var vstep = 239 / 1024;
  34602. var uoffset = 60 / 1024;
  34603. var voffset = 26 / 1024;
  34604. // Second island should have margin, not to touch the first island
  34605. // avoid any borderline artefact in pixel rounding
  34606. var island_u_offset = -40 / 1024;
  34607. var island_v_offset = +20 / 1024;
  34608. // face is either island 0 or 1 :
  34609. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  34610. var island = [
  34611. 0, 0, 0, 0, 1,
  34612. 0, 0, 1, 1, 0,
  34613. 0, 0, 1, 1, 0,
  34614. 0, 1, 1, 1, 0 // 15 - 19
  34615. ];
  34616. var indices = new Array();
  34617. var positions = new Array();
  34618. var normals = new Array();
  34619. var uvs = new Array();
  34620. var current_indice = 0;
  34621. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  34622. var face_vertex_pos = new Array(3);
  34623. var face_vertex_uv = new Array(3);
  34624. var v012;
  34625. for (v012 = 0; v012 < 3; v012++) {
  34626. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  34627. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  34628. }
  34629. // create all with normals
  34630. for (var face = 0; face < 20; face++) {
  34631. // 3 vertex per face
  34632. for (v012 = 0; v012 < 3; v012++) {
  34633. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  34634. var v_id = ico_indices[3 * face + v012];
  34635. // vertex have 3D position (x,y,z)
  34636. 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]);
  34637. // Normalize to get normal, then scale to radius
  34638. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  34639. // uv Coordinates from vertex ID
  34640. 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);
  34641. }
  34642. // Subdivide the face (interpolate pos, norm, uv)
  34643. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  34644. // - norm is linear interpolation of vertex corner normal
  34645. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  34646. // - uv is linear interpolation
  34647. //
  34648. // Topology is as below for sub-divide by 2
  34649. // vertex shown as v0,v1,v2
  34650. // interp index is i1 to progress in range [v0,v1[
  34651. // interp index is i2 to progress in range [v0,v2[
  34652. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  34653. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34654. //
  34655. //
  34656. // i2 v2
  34657. // ^ ^
  34658. // / / \
  34659. // / / \
  34660. // / / \
  34661. // / / (0,1) \
  34662. // / #---------\
  34663. // / / \ (0,0)'/ \
  34664. // / / \ / \
  34665. // / / \ / \
  34666. // / / (0,0) \ / (1,0) \
  34667. // / #---------#---------\
  34668. // v0 v1
  34669. //
  34670. // --------------------> i1
  34671. //
  34672. // interp of (i1,i2):
  34673. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  34674. // along i1 : lerp(x0,x1, i1/(S-i2))
  34675. //
  34676. // centroid of triangle is needed to get help normal computation
  34677. // (c1,c2) are used for centroid location
  34678. var interp_vertex = function (i1, i2, c1, c2) {
  34679. // vertex is interpolated from
  34680. // - face_vertex_pos[0..2]
  34681. // - face_vertex_uv[0..2]
  34682. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  34683. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  34684. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  34685. pos_interp.normalize();
  34686. var vertex_normal;
  34687. if (flat) {
  34688. // in flat mode, recalculate normal as face centroid normal
  34689. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  34690. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  34691. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  34692. }
  34693. else {
  34694. // in smooth mode, recalculate normal from each single vertex position
  34695. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  34696. }
  34697. // Vertex normal need correction due to X,Y,Z radius scaling
  34698. vertex_normal.x /= radiusX;
  34699. vertex_normal.y /= radiusY;
  34700. vertex_normal.z /= radiusZ;
  34701. vertex_normal.normalize();
  34702. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  34703. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  34704. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  34705. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  34706. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  34707. uvs.push(uv_interp.x, uv_interp.y);
  34708. // push each vertex has member of a face
  34709. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  34710. indices.push(current_indice);
  34711. current_indice++;
  34712. };
  34713. for (var i2 = 0; i2 < subdivisions; i2++) {
  34714. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  34715. // face : (i1,i2) for /\ :
  34716. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  34717. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34718. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34719. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34720. if (i1 + i2 + 1 < subdivisions) {
  34721. // face : (i1,i2)' for \/ :
  34722. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34723. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34724. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34725. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34726. }
  34727. }
  34728. }
  34729. }
  34730. // Sides
  34731. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34732. // Result
  34733. var vertexData = new VertexData();
  34734. vertexData.indices = indices;
  34735. vertexData.positions = positions;
  34736. vertexData.normals = normals;
  34737. vertexData.uvs = uvs;
  34738. return vertexData;
  34739. };
  34740. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  34741. /**
  34742. * Creates the VertexData of the Polyhedron.
  34743. */
  34744. VertexData.CreatePolyhedron = function (options) {
  34745. // provided polyhedron types :
  34746. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  34747. // 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)
  34748. var polyhedra = [];
  34749. 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]] };
  34750. 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]] };
  34751. polyhedra[2] = {
  34752. 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]],
  34753. 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]]
  34754. };
  34755. polyhedra[3] = {
  34756. 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]],
  34757. 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]]
  34758. };
  34759. polyhedra[4] = {
  34760. 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]],
  34761. 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]]
  34762. };
  34763. 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]] };
  34764. 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]] };
  34765. 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]] };
  34766. 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]] };
  34767. 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]] };
  34768. 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]] };
  34769. 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]] };
  34770. 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]] };
  34771. 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]] };
  34772. polyhedra[14] = {
  34773. 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]],
  34774. 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]]
  34775. };
  34776. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  34777. var size = options.size;
  34778. var sizeX = options.sizeX || size || 1;
  34779. var sizeY = options.sizeY || size || 1;
  34780. var sizeZ = options.sizeZ || size || 1;
  34781. var data = options.custom || polyhedra[type];
  34782. var nbfaces = data.face.length;
  34783. var faceUV = options.faceUV || new Array(nbfaces);
  34784. var faceColors = options.faceColors;
  34785. var flat = (options.flat === undefined) ? true : options.flat;
  34786. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34787. var positions = new Array();
  34788. var indices = new Array();
  34789. var normals = new Array();
  34790. var uvs = new Array();
  34791. var colors = new Array();
  34792. var index = 0;
  34793. var faceIdx = 0; // face cursor in the array "indexes"
  34794. var indexes = new Array();
  34795. var i = 0;
  34796. var f = 0;
  34797. var u, v, ang, x, y, tmp;
  34798. // default face colors and UV if undefined
  34799. if (flat) {
  34800. for (f = 0; f < nbfaces; f++) {
  34801. if (faceColors && faceColors[f] === undefined) {
  34802. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34803. }
  34804. if (faceUV && faceUV[f] === undefined) {
  34805. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34806. }
  34807. }
  34808. }
  34809. if (!flat) {
  34810. for (i = 0; i < data.vertex.length; i++) {
  34811. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34812. uvs.push(0, 0);
  34813. }
  34814. for (f = 0; f < nbfaces; f++) {
  34815. for (i = 0; i < data.face[f].length - 2; i++) {
  34816. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34817. }
  34818. }
  34819. }
  34820. else {
  34821. for (f = 0; f < nbfaces; f++) {
  34822. var fl = data.face[f].length; // number of vertices of the current face
  34823. ang = 2 * Math.PI / fl;
  34824. x = 0.5 * Math.tan(ang / 2);
  34825. y = 0.5;
  34826. // positions, uvs, colors
  34827. for (i = 0; i < fl; i++) {
  34828. // positions
  34829. 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);
  34830. indexes.push(index);
  34831. index++;
  34832. // uvs
  34833. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34834. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34835. uvs.push(u, v);
  34836. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34837. y = x * Math.sin(ang) + y * Math.cos(ang);
  34838. x = tmp;
  34839. // colors
  34840. if (faceColors) {
  34841. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34842. }
  34843. }
  34844. // indices from indexes
  34845. for (i = 0; i < fl - 2; i++) {
  34846. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34847. }
  34848. faceIdx += fl;
  34849. }
  34850. }
  34851. VertexData.ComputeNormals(positions, indices, normals);
  34852. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34853. var vertexData = new VertexData();
  34854. vertexData.positions = positions;
  34855. vertexData.indices = indices;
  34856. vertexData.normals = normals;
  34857. vertexData.uvs = uvs;
  34858. if (faceColors && flat) {
  34859. vertexData.colors = colors;
  34860. }
  34861. return vertexData;
  34862. };
  34863. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34864. /**
  34865. * Creates the VertexData of the Torus Knot.
  34866. */
  34867. VertexData.CreateTorusKnot = function (options) {
  34868. var indices = new Array();
  34869. var positions = new Array();
  34870. var normals = new Array();
  34871. var uvs = new Array();
  34872. var radius = options.radius || 2;
  34873. var tube = options.tube || 0.5;
  34874. var radialSegments = options.radialSegments || 32;
  34875. var tubularSegments = options.tubularSegments || 32;
  34876. var p = options.p || 2;
  34877. var q = options.q || 3;
  34878. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34879. // Helper
  34880. var getPos = function (angle) {
  34881. var cu = Math.cos(angle);
  34882. var su = Math.sin(angle);
  34883. var quOverP = q / p * angle;
  34884. var cs = Math.cos(quOverP);
  34885. var tx = radius * (2 + cs) * 0.5 * cu;
  34886. var ty = radius * (2 + cs) * su * 0.5;
  34887. var tz = radius * Math.sin(quOverP) * 0.5;
  34888. return new BABYLON.Vector3(tx, ty, tz);
  34889. };
  34890. // Vertices
  34891. var i;
  34892. var j;
  34893. for (i = 0; i <= radialSegments; i++) {
  34894. var modI = i % radialSegments;
  34895. var u = modI / radialSegments * 2 * p * Math.PI;
  34896. var p1 = getPos(u);
  34897. var p2 = getPos(u + 0.01);
  34898. var tang = p2.subtract(p1);
  34899. var n = p2.add(p1);
  34900. var bitan = BABYLON.Vector3.Cross(tang, n);
  34901. n = BABYLON.Vector3.Cross(bitan, tang);
  34902. bitan.normalize();
  34903. n.normalize();
  34904. for (j = 0; j < tubularSegments; j++) {
  34905. var modJ = j % tubularSegments;
  34906. var v = modJ / tubularSegments * 2 * Math.PI;
  34907. var cx = -tube * Math.cos(v);
  34908. var cy = tube * Math.sin(v);
  34909. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34910. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34911. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34912. uvs.push(i / radialSegments);
  34913. uvs.push(j / tubularSegments);
  34914. }
  34915. }
  34916. for (i = 0; i < radialSegments; i++) {
  34917. for (j = 0; j < tubularSegments; j++) {
  34918. var jNext = (j + 1) % tubularSegments;
  34919. var a = i * tubularSegments + j;
  34920. var b = (i + 1) * tubularSegments + j;
  34921. var c = (i + 1) * tubularSegments + jNext;
  34922. var d = i * tubularSegments + jNext;
  34923. indices.push(d);
  34924. indices.push(b);
  34925. indices.push(a);
  34926. indices.push(d);
  34927. indices.push(c);
  34928. indices.push(b);
  34929. }
  34930. }
  34931. // Normals
  34932. VertexData.ComputeNormals(positions, indices, normals);
  34933. // Sides
  34934. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34935. // Result
  34936. var vertexData = new VertexData();
  34937. vertexData.indices = indices;
  34938. vertexData.positions = positions;
  34939. vertexData.normals = normals;
  34940. vertexData.uvs = uvs;
  34941. return vertexData;
  34942. };
  34943. // Tools
  34944. /**
  34945. * @param {any} - positions (number[] or Float32Array)
  34946. * @param {any} - indices (number[] or Uint16Array)
  34947. * @param {any} - normals (number[] or Float32Array)
  34948. * options (optional) :
  34949. * facetPositions : optional array of facet positions (vector3)
  34950. * facetNormals : optional array of facet normals (vector3)
  34951. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34952. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34953. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34954. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34955. * bInfo : optional bounding info, required for facetPartitioning computation
  34956. * useRightHandedSystem: optional boolean to for right handed system computation
  34957. * depthSort : optional boolean to enable the facet depth sort computation
  34958. * distanceTo : optional Vector3 to compute the facet depth from this location
  34959. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  34960. */
  34961. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34962. // temporary scalar variables
  34963. var index = 0; // facet index
  34964. var p1p2x = 0.0; // p1p2 vector x coordinate
  34965. var p1p2y = 0.0; // p1p2 vector y coordinate
  34966. var p1p2z = 0.0; // p1p2 vector z coordinate
  34967. var p3p2x = 0.0; // p3p2 vector x coordinate
  34968. var p3p2y = 0.0; // p3p2 vector y coordinate
  34969. var p3p2z = 0.0; // p3p2 vector z coordinate
  34970. var faceNormalx = 0.0; // facet normal x coordinate
  34971. var faceNormaly = 0.0; // facet normal y coordinate
  34972. var faceNormalz = 0.0; // facet normal z coordinate
  34973. var length = 0.0; // facet normal length before normalization
  34974. var v1x = 0; // vector1 x index in the positions array
  34975. var v1y = 0; // vector1 y index in the positions array
  34976. var v1z = 0; // vector1 z index in the positions array
  34977. var v2x = 0; // vector2 x index in the positions array
  34978. var v2y = 0; // vector2 y index in the positions array
  34979. var v2z = 0; // vector2 z index in the positions array
  34980. var v3x = 0; // vector3 x index in the positions array
  34981. var v3y = 0; // vector3 y index in the positions array
  34982. var v3z = 0; // vector3 z index in the positions array
  34983. var computeFacetNormals = false;
  34984. var computeFacetPositions = false;
  34985. var computeFacetPartitioning = false;
  34986. var computeDepthSort = false;
  34987. var faceNormalSign = 1;
  34988. var ratio = 0;
  34989. var distanceTo = null;
  34990. if (options) {
  34991. computeFacetNormals = (options.facetNormals) ? true : false;
  34992. computeFacetPositions = (options.facetPositions) ? true : false;
  34993. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34994. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  34995. ratio = options.ratio || 0;
  34996. computeDepthSort = (options.depthSort) ? true : false;
  34997. distanceTo = (options.distanceTo);
  34998. if (computeDepthSort) {
  34999. if (distanceTo === undefined) {
  35000. distanceTo = BABYLON.Vector3.Zero();
  35001. }
  35002. var depthSortedFacets = options.depthSortedFacets;
  35003. }
  35004. }
  35005. // facetPartitioning reinit if needed
  35006. var xSubRatio = 0;
  35007. var ySubRatio = 0;
  35008. var zSubRatio = 0;
  35009. var subSq = 0;
  35010. if (computeFacetPartitioning && options && options.bbSize) {
  35011. var ox = 0; // X partitioning index for facet position
  35012. var oy = 0; // Y partinioning index for facet position
  35013. var oz = 0; // Z partinioning index for facet position
  35014. var b1x = 0; // X partitioning index for facet v1 vertex
  35015. var b1y = 0; // Y partitioning index for facet v1 vertex
  35016. var b1z = 0; // z partitioning index for facet v1 vertex
  35017. var b2x = 0; // X partitioning index for facet v2 vertex
  35018. var b2y = 0; // Y partitioning index for facet v2 vertex
  35019. var b2z = 0; // Z partitioning index for facet v2 vertex
  35020. var b3x = 0; // X partitioning index for facet v3 vertex
  35021. var b3y = 0; // Y partitioning index for facet v3 vertex
  35022. var b3z = 0; // Z partitioning index for facet v3 vertex
  35023. var block_idx_o = 0; // facet barycenter block index
  35024. var block_idx_v1 = 0; // v1 vertex block index
  35025. var block_idx_v2 = 0; // v2 vertex block index
  35026. var block_idx_v3 = 0; // v3 vertex block index
  35027. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  35028. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  35029. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  35030. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  35031. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  35032. subSq = options.subDiv.max * options.subDiv.max;
  35033. options.facetPartitioning.length = 0;
  35034. }
  35035. // reset the normals
  35036. for (index = 0; index < positions.length; index++) {
  35037. normals[index] = 0.0;
  35038. }
  35039. // Loop : 1 indice triplet = 1 facet
  35040. var nbFaces = (indices.length / 3) | 0;
  35041. for (index = 0; index < nbFaces; index++) {
  35042. // get the indexes of the coordinates of each vertex of the facet
  35043. v1x = indices[index * 3] * 3;
  35044. v1y = v1x + 1;
  35045. v1z = v1x + 2;
  35046. v2x = indices[index * 3 + 1] * 3;
  35047. v2y = v2x + 1;
  35048. v2z = v2x + 2;
  35049. v3x = indices[index * 3 + 2] * 3;
  35050. v3y = v3x + 1;
  35051. v3z = v3x + 2;
  35052. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  35053. p1p2y = positions[v1y] - positions[v2y];
  35054. p1p2z = positions[v1z] - positions[v2z];
  35055. p3p2x = positions[v3x] - positions[v2x];
  35056. p3p2y = positions[v3y] - positions[v2y];
  35057. p3p2z = positions[v3z] - positions[v2z];
  35058. // compute the face normal with the cross product
  35059. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  35060. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  35061. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  35062. // normalize this normal and store it in the array facetData
  35063. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  35064. length = (length === 0) ? 1.0 : length;
  35065. faceNormalx /= length;
  35066. faceNormaly /= length;
  35067. faceNormalz /= length;
  35068. if (computeFacetNormals && options) {
  35069. options.facetNormals[index].x = faceNormalx;
  35070. options.facetNormals[index].y = faceNormaly;
  35071. options.facetNormals[index].z = faceNormalz;
  35072. }
  35073. if (computeFacetPositions && options) {
  35074. // compute and the facet barycenter coordinates in the array facetPositions
  35075. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  35076. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  35077. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  35078. }
  35079. if (computeFacetPartitioning && options) {
  35080. // store the facet indexes in arrays in the main facetPartitioning array :
  35081. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  35082. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  35083. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  35084. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  35085. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  35086. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  35087. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  35088. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  35089. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  35090. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  35091. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  35092. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  35093. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  35094. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  35095. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  35096. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  35097. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  35098. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  35099. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  35100. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  35101. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  35102. // push each facet index in each block containing the vertex
  35103. options.facetPartitioning[block_idx_v1].push(index);
  35104. if (block_idx_v2 != block_idx_v1) {
  35105. options.facetPartitioning[block_idx_v2].push(index);
  35106. }
  35107. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  35108. options.facetPartitioning[block_idx_v3].push(index);
  35109. }
  35110. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  35111. options.facetPartitioning[block_idx_o].push(index);
  35112. }
  35113. }
  35114. if (computeDepthSort && options && options.facetPositions) {
  35115. var dsf = depthSortedFacets[index];
  35116. dsf.ind = index * 3;
  35117. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  35118. }
  35119. // compute the normals anyway
  35120. normals[v1x] += faceNormalx; // accumulate all the normals per face
  35121. normals[v1y] += faceNormaly;
  35122. normals[v1z] += faceNormalz;
  35123. normals[v2x] += faceNormalx;
  35124. normals[v2y] += faceNormaly;
  35125. normals[v2z] += faceNormalz;
  35126. normals[v3x] += faceNormalx;
  35127. normals[v3y] += faceNormaly;
  35128. normals[v3z] += faceNormalz;
  35129. }
  35130. // last normalization of each normal
  35131. for (index = 0; index < normals.length / 3; index++) {
  35132. faceNormalx = normals[index * 3];
  35133. faceNormaly = normals[index * 3 + 1];
  35134. faceNormalz = normals[index * 3 + 2];
  35135. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  35136. length = (length === 0) ? 1.0 : length;
  35137. faceNormalx /= length;
  35138. faceNormaly /= length;
  35139. faceNormalz /= length;
  35140. normals[index * 3] = faceNormalx;
  35141. normals[index * 3 + 1] = faceNormaly;
  35142. normals[index * 3 + 2] = faceNormalz;
  35143. }
  35144. };
  35145. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  35146. var li = indices.length;
  35147. var ln = normals.length;
  35148. var i;
  35149. var n;
  35150. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  35151. switch (sideOrientation) {
  35152. case BABYLON.Mesh.FRONTSIDE:
  35153. // nothing changed
  35154. break;
  35155. case BABYLON.Mesh.BACKSIDE:
  35156. var tmp;
  35157. // indices
  35158. for (i = 0; i < li; i += 3) {
  35159. tmp = indices[i];
  35160. indices[i] = indices[i + 2];
  35161. indices[i + 2] = tmp;
  35162. }
  35163. // normals
  35164. for (n = 0; n < ln; n++) {
  35165. normals[n] = -normals[n];
  35166. }
  35167. break;
  35168. case BABYLON.Mesh.DOUBLESIDE:
  35169. // positions
  35170. var lp = positions.length;
  35171. var l = lp / 3;
  35172. for (var p = 0; p < lp; p++) {
  35173. positions[lp + p] = positions[p];
  35174. }
  35175. // indices
  35176. for (i = 0; i < li; i += 3) {
  35177. indices[i + li] = indices[i + 2] + l;
  35178. indices[i + 1 + li] = indices[i + 1] + l;
  35179. indices[i + 2 + li] = indices[i] + l;
  35180. }
  35181. // normals
  35182. for (n = 0; n < ln; n++) {
  35183. normals[ln + n] = -normals[n];
  35184. }
  35185. // uvs
  35186. var lu = uvs.length;
  35187. var u = 0;
  35188. for (u = 0; u < lu; u++) {
  35189. uvs[u + lu] = uvs[u];
  35190. }
  35191. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  35192. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  35193. u = 0;
  35194. for (i = 0; i < lu / 2; i++) {
  35195. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  35196. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  35197. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  35198. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  35199. u += 2;
  35200. }
  35201. break;
  35202. }
  35203. };
  35204. /**
  35205. * Creates a new VertexData from the imported parameters.
  35206. */
  35207. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  35208. var vertexData = new VertexData();
  35209. // positions
  35210. var positions = parsedVertexData.positions;
  35211. if (positions) {
  35212. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  35213. }
  35214. // normals
  35215. var normals = parsedVertexData.normals;
  35216. if (normals) {
  35217. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  35218. }
  35219. // tangents
  35220. var tangents = parsedVertexData.tangents;
  35221. if (tangents) {
  35222. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  35223. }
  35224. // uvs
  35225. var uvs = parsedVertexData.uvs;
  35226. if (uvs) {
  35227. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  35228. }
  35229. // uv2s
  35230. var uv2s = parsedVertexData.uv2s;
  35231. if (uv2s) {
  35232. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  35233. }
  35234. // uv3s
  35235. var uv3s = parsedVertexData.uv3s;
  35236. if (uv3s) {
  35237. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  35238. }
  35239. // uv4s
  35240. var uv4s = parsedVertexData.uv4s;
  35241. if (uv4s) {
  35242. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  35243. }
  35244. // uv5s
  35245. var uv5s = parsedVertexData.uv5s;
  35246. if (uv5s) {
  35247. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  35248. }
  35249. // uv6s
  35250. var uv6s = parsedVertexData.uv6s;
  35251. if (uv6s) {
  35252. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  35253. }
  35254. // colors
  35255. var colors = parsedVertexData.colors;
  35256. if (colors) {
  35257. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  35258. }
  35259. // matricesIndices
  35260. var matricesIndices = parsedVertexData.matricesIndices;
  35261. if (matricesIndices) {
  35262. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  35263. }
  35264. // matricesWeights
  35265. var matricesWeights = parsedVertexData.matricesWeights;
  35266. if (matricesWeights) {
  35267. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  35268. }
  35269. // indices
  35270. var indices = parsedVertexData.indices;
  35271. if (indices) {
  35272. vertexData.indices = indices;
  35273. }
  35274. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  35275. };
  35276. return VertexData;
  35277. }());
  35278. BABYLON.VertexData = VertexData;
  35279. })(BABYLON || (BABYLON = {}));
  35280. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  35281. "use strict";
  35282. var BABYLON;
  35283. (function (BABYLON) {
  35284. /**
  35285. * Class used to store geometry data (vertex buffers + index buffer)
  35286. */
  35287. var Geometry = /** @class */ (function () {
  35288. /**
  35289. * Creates a new geometry
  35290. * @param id defines the unique ID
  35291. * @param scene defines the hosting scene
  35292. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  35293. * @param updatable defines if geometry must be updatable (false by default)
  35294. * @param mesh defines the mesh that will be associated with the geometry
  35295. */
  35296. function Geometry(id, scene, vertexData, updatable, mesh) {
  35297. if (updatable === void 0) { updatable = false; }
  35298. if (mesh === void 0) { mesh = null; }
  35299. /**
  35300. * Gets the delay loading state of the geometry (none by default which means not delayed)
  35301. */
  35302. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35303. this._totalVertices = 0;
  35304. this._isDisposed = false;
  35305. this._indexBufferIsUpdatable = false;
  35306. this.id = id;
  35307. this._engine = scene.getEngine();
  35308. this._meshes = [];
  35309. this._scene = scene;
  35310. //Init vertex buffer cache
  35311. this._vertexBuffers = {};
  35312. this._indices = [];
  35313. this._updatable = updatable;
  35314. // vertexData
  35315. if (vertexData) {
  35316. this.setAllVerticesData(vertexData, updatable);
  35317. }
  35318. else {
  35319. this._totalVertices = 0;
  35320. this._indices = [];
  35321. }
  35322. if (this._engine.getCaps().vertexArrayObject) {
  35323. this._vertexArrayObjects = {};
  35324. }
  35325. // applyToMesh
  35326. if (mesh) {
  35327. if (mesh.getClassName() === "LinesMesh") {
  35328. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  35329. this.updateExtend();
  35330. }
  35331. this.applyToMesh(mesh);
  35332. mesh.computeWorldMatrix(true);
  35333. }
  35334. }
  35335. Object.defineProperty(Geometry.prototype, "boundingBias", {
  35336. /**
  35337. * 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
  35338. */
  35339. get: function () {
  35340. return this._boundingBias;
  35341. },
  35342. /**
  35343. * 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
  35344. */
  35345. set: function (value) {
  35346. if (this._boundingBias && this._boundingBias.equals(value)) {
  35347. return;
  35348. }
  35349. this._boundingBias = value.clone();
  35350. this.updateBoundingInfo(true, null);
  35351. },
  35352. enumerable: true,
  35353. configurable: true
  35354. });
  35355. /**
  35356. * Static function used to attach a new empty geometry to a mesh
  35357. * @param mesh defines the mesh to attach the geometry to
  35358. * @returns the new {BABYLON.Geometry}
  35359. */
  35360. Geometry.CreateGeometryForMesh = function (mesh) {
  35361. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  35362. geometry.applyToMesh(mesh);
  35363. return geometry;
  35364. };
  35365. Object.defineProperty(Geometry.prototype, "extend", {
  35366. /**
  35367. * Gets the current extend of the geometry
  35368. */
  35369. get: function () {
  35370. return this._extend;
  35371. },
  35372. enumerable: true,
  35373. configurable: true
  35374. });
  35375. /**
  35376. * Gets the hosting scene
  35377. * @returns the hosting {BABYLON.Scene}
  35378. */
  35379. Geometry.prototype.getScene = function () {
  35380. return this._scene;
  35381. };
  35382. /**
  35383. * Gets the hosting engine
  35384. * @returns the hosting {BABYLON.Engine}
  35385. */
  35386. Geometry.prototype.getEngine = function () {
  35387. return this._engine;
  35388. };
  35389. /**
  35390. * Defines if the geometry is ready to use
  35391. * @returns true if the geometry is ready to be used
  35392. */
  35393. Geometry.prototype.isReady = function () {
  35394. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  35395. };
  35396. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  35397. /**
  35398. * Gets a value indicating that the geometry should not be serialized
  35399. */
  35400. get: function () {
  35401. for (var index = 0; index < this._meshes.length; index++) {
  35402. if (!this._meshes[index].doNotSerialize) {
  35403. return false;
  35404. }
  35405. }
  35406. return true;
  35407. },
  35408. enumerable: true,
  35409. configurable: true
  35410. });
  35411. /** @ignore */
  35412. Geometry.prototype._rebuild = function () {
  35413. if (this._vertexArrayObjects) {
  35414. this._vertexArrayObjects = {};
  35415. }
  35416. // Index buffer
  35417. if (this._meshes.length !== 0 && this._indices) {
  35418. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35419. }
  35420. // Vertex buffers
  35421. for (var key in this._vertexBuffers) {
  35422. var vertexBuffer = this._vertexBuffers[key];
  35423. vertexBuffer._rebuild();
  35424. }
  35425. };
  35426. /**
  35427. * Affects all gemetry data in one call
  35428. * @param vertexData defines the geometry data
  35429. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  35430. */
  35431. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35432. vertexData.applyToGeometry(this, updatable);
  35433. this.notifyUpdate();
  35434. };
  35435. /**
  35436. * Set specific vertex data
  35437. * @param kind defines the data kind (Position, normal, etc...)
  35438. * @param data defines the vertex data to use
  35439. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  35440. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  35441. */
  35442. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  35443. if (updatable === void 0) { updatable = false; }
  35444. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  35445. this.setVerticesBuffer(buffer);
  35446. };
  35447. /**
  35448. * Removes a specific vertex data
  35449. * @param kind defines the data kind (Position, normal, etc...)
  35450. */
  35451. Geometry.prototype.removeVerticesData = function (kind) {
  35452. if (this._vertexBuffers[kind]) {
  35453. this._vertexBuffers[kind].dispose();
  35454. delete this._vertexBuffers[kind];
  35455. }
  35456. };
  35457. /**
  35458. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  35459. * @param buffer defines the vertex buffer to use
  35460. */
  35461. Geometry.prototype.setVerticesBuffer = function (buffer) {
  35462. var kind = buffer.getKind();
  35463. if (this._vertexBuffers[kind]) {
  35464. this._vertexBuffers[kind].dispose();
  35465. }
  35466. this._vertexBuffers[kind] = buffer;
  35467. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35468. var data = buffer.getData();
  35469. var stride = buffer.getStrideSize();
  35470. this._totalVertices = data.length / stride;
  35471. this.updateExtend(data, stride);
  35472. this._resetPointsArrayCache();
  35473. var meshes = this._meshes;
  35474. var numOfMeshes = meshes.length;
  35475. for (var index = 0; index < numOfMeshes; index++) {
  35476. var mesh = meshes[index];
  35477. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35478. mesh._createGlobalSubMesh(false);
  35479. mesh.computeWorldMatrix(true);
  35480. }
  35481. }
  35482. this.notifyUpdate(kind);
  35483. if (this._vertexArrayObjects) {
  35484. this._disposeVertexArrayObjects();
  35485. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  35486. }
  35487. };
  35488. /**
  35489. * Update a specific vertex buffer
  35490. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  35491. * It will do nothing if the buffer is not updatable
  35492. * @param kind defines the data kind (Position, normal, etc...)
  35493. * @param data defines the data to use
  35494. * @param offset defines the offset in the target buffer where to store the data
  35495. */
  35496. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  35497. var vertexBuffer = this.getVertexBuffer(kind);
  35498. if (!vertexBuffer) {
  35499. return;
  35500. }
  35501. vertexBuffer.updateDirectly(data, offset);
  35502. this.notifyUpdate(kind);
  35503. };
  35504. /**
  35505. * Update a specific vertex buffer
  35506. * This function will create a new buffer if the current one is not updatable
  35507. * @param kind defines the data kind (Position, normal, etc...)
  35508. * @param data defines the data to use
  35509. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  35510. */
  35511. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  35512. if (updateExtends === void 0) { updateExtends = false; }
  35513. var vertexBuffer = this.getVertexBuffer(kind);
  35514. if (!vertexBuffer) {
  35515. return;
  35516. }
  35517. vertexBuffer.update(data);
  35518. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35519. var stride = vertexBuffer.getStrideSize();
  35520. this._totalVertices = data.length / stride;
  35521. this.updateBoundingInfo(updateExtends, data);
  35522. }
  35523. this.notifyUpdate(kind);
  35524. };
  35525. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  35526. if (updateExtends) {
  35527. this.updateExtend(data);
  35528. }
  35529. var meshes = this._meshes;
  35530. var numOfMeshes = meshes.length;
  35531. this._resetPointsArrayCache();
  35532. for (var index = 0; index < numOfMeshes; index++) {
  35533. var mesh = meshes[index];
  35534. if (updateExtends) {
  35535. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35536. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  35537. var subMesh = mesh.subMeshes[subIndex];
  35538. subMesh.refreshBoundingInfo();
  35539. }
  35540. }
  35541. }
  35542. };
  35543. /** @ignore */
  35544. Geometry.prototype._bind = function (effect, indexToBind) {
  35545. if (!effect) {
  35546. return;
  35547. }
  35548. if (indexToBind === undefined) {
  35549. indexToBind = this._indexBuffer;
  35550. }
  35551. var vbs = this.getVertexBuffers();
  35552. if (!vbs) {
  35553. return;
  35554. }
  35555. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  35556. this._engine.bindBuffers(vbs, indexToBind, effect);
  35557. return;
  35558. }
  35559. // Using VAO
  35560. if (!this._vertexArrayObjects[effect.key]) {
  35561. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  35562. }
  35563. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  35564. };
  35565. /**
  35566. * Gets total number of vertices
  35567. * @returns the total number of vertices
  35568. */
  35569. Geometry.prototype.getTotalVertices = function () {
  35570. if (!this.isReady()) {
  35571. return 0;
  35572. }
  35573. return this._totalVertices;
  35574. };
  35575. /**
  35576. * Gets a specific vertex data attached to this geometry
  35577. * @param kind defines the data kind (Position, normal, etc...)
  35578. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35579. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  35580. * @returns a float array containing vertex data
  35581. */
  35582. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  35583. var vertexBuffer = this.getVertexBuffer(kind);
  35584. if (!vertexBuffer) {
  35585. return null;
  35586. }
  35587. var orig = vertexBuffer.getData();
  35588. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  35589. return orig;
  35590. }
  35591. else {
  35592. var len = orig.length;
  35593. var copy = [];
  35594. for (var i = 0; i < len; i++) {
  35595. copy.push(orig[i]);
  35596. }
  35597. return copy;
  35598. }
  35599. };
  35600. /**
  35601. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  35602. * @param kind defines the data kind (Position, normal, etc...)
  35603. * @returns true if the vertex buffer with the specified kind is updatable
  35604. */
  35605. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  35606. var vb = this._vertexBuffers[kind];
  35607. if (!vb) {
  35608. return false;
  35609. }
  35610. return vb.isUpdatable();
  35611. };
  35612. /**
  35613. * Gets a specific vertex buffer
  35614. * @param kind defines the data kind (Position, normal, etc...)
  35615. * @returns a {BABYLON.VertexBuffer}
  35616. */
  35617. Geometry.prototype.getVertexBuffer = function (kind) {
  35618. if (!this.isReady()) {
  35619. return null;
  35620. }
  35621. return this._vertexBuffers[kind];
  35622. };
  35623. /**
  35624. * Returns all vertex buffers
  35625. * @return an object holding all vertex buffers indexed by kind
  35626. */
  35627. Geometry.prototype.getVertexBuffers = function () {
  35628. if (!this.isReady()) {
  35629. return null;
  35630. }
  35631. return this._vertexBuffers;
  35632. };
  35633. /**
  35634. * Gets a boolean indicating if specific vertex buffer is present
  35635. * @param kind defines the data kind (Position, normal, etc...)
  35636. * @returns true if data is present
  35637. */
  35638. Geometry.prototype.isVerticesDataPresent = function (kind) {
  35639. if (!this._vertexBuffers) {
  35640. if (this._delayInfo) {
  35641. return this._delayInfo.indexOf(kind) !== -1;
  35642. }
  35643. return false;
  35644. }
  35645. return this._vertexBuffers[kind] !== undefined;
  35646. };
  35647. /**
  35648. * Gets a list of all attached data kinds (Position, normal, etc...)
  35649. * @returns a list of string containing all kinds
  35650. */
  35651. Geometry.prototype.getVerticesDataKinds = function () {
  35652. var result = [];
  35653. var kind;
  35654. if (!this._vertexBuffers && this._delayInfo) {
  35655. for (kind in this._delayInfo) {
  35656. result.push(kind);
  35657. }
  35658. }
  35659. else {
  35660. for (kind in this._vertexBuffers) {
  35661. result.push(kind);
  35662. }
  35663. }
  35664. return result;
  35665. };
  35666. /**
  35667. * Update index buffer
  35668. * @param indices defines the indices to store in the index buffer
  35669. * @param offset defines the offset in the target buffer where to store the data
  35670. */
  35671. Geometry.prototype.updateIndices = function (indices, offset) {
  35672. if (!this._indexBuffer) {
  35673. return;
  35674. }
  35675. if (!this._indexBufferIsUpdatable) {
  35676. this.setIndices(indices, null, true);
  35677. }
  35678. else {
  35679. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  35680. }
  35681. };
  35682. /**
  35683. * Creates a new index buffer
  35684. * @param indices defines the indices to store in the index buffer
  35685. * @param totalVertices defines the total number of vertices (could be null)
  35686. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  35687. */
  35688. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  35689. if (totalVertices === void 0) { totalVertices = null; }
  35690. if (updatable === void 0) { updatable = false; }
  35691. if (this._indexBuffer) {
  35692. this._engine._releaseBuffer(this._indexBuffer);
  35693. }
  35694. this._disposeVertexArrayObjects();
  35695. this._indices = indices;
  35696. this._indexBufferIsUpdatable = updatable;
  35697. if (this._meshes.length !== 0 && this._indices) {
  35698. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  35699. }
  35700. if (totalVertices != undefined) {
  35701. this._totalVertices = totalVertices;
  35702. }
  35703. var meshes = this._meshes;
  35704. var numOfMeshes = meshes.length;
  35705. for (var index = 0; index < numOfMeshes; index++) {
  35706. meshes[index]._createGlobalSubMesh(true);
  35707. }
  35708. this.notifyUpdate();
  35709. };
  35710. /**
  35711. * Return the total number of indices
  35712. * @returns the total number of indices
  35713. */
  35714. Geometry.prototype.getTotalIndices = function () {
  35715. if (!this.isReady()) {
  35716. return 0;
  35717. }
  35718. return this._indices.length;
  35719. };
  35720. /**
  35721. * Gets the index buffer array
  35722. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35723. * @returns the index buffer array
  35724. */
  35725. Geometry.prototype.getIndices = function (copyWhenShared) {
  35726. if (!this.isReady()) {
  35727. return null;
  35728. }
  35729. var orig = this._indices;
  35730. if (!copyWhenShared || this._meshes.length === 1) {
  35731. return orig;
  35732. }
  35733. else {
  35734. var len = orig.length;
  35735. var copy = [];
  35736. for (var i = 0; i < len; i++) {
  35737. copy.push(orig[i]);
  35738. }
  35739. return copy;
  35740. }
  35741. };
  35742. /**
  35743. * Gets the index buffer
  35744. * @return the index buffer
  35745. */
  35746. Geometry.prototype.getIndexBuffer = function () {
  35747. if (!this.isReady()) {
  35748. return null;
  35749. }
  35750. return this._indexBuffer;
  35751. };
  35752. /** @ignore */
  35753. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  35754. if (effect === void 0) { effect = null; }
  35755. if (!effect || !this._vertexArrayObjects) {
  35756. return;
  35757. }
  35758. if (this._vertexArrayObjects[effect.key]) {
  35759. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  35760. delete this._vertexArrayObjects[effect.key];
  35761. }
  35762. };
  35763. /**
  35764. * Release the associated resources for a specific mesh
  35765. * @param mesh defines the source mesh
  35766. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  35767. */
  35768. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  35769. var meshes = this._meshes;
  35770. var index = meshes.indexOf(mesh);
  35771. if (index === -1) {
  35772. return;
  35773. }
  35774. meshes.splice(index, 1);
  35775. mesh._geometry = null;
  35776. if (meshes.length === 0 && shouldDispose) {
  35777. this.dispose();
  35778. }
  35779. };
  35780. /**
  35781. * Apply current geometry to a given mesh
  35782. * @param mesh defines the mesh to apply geometry to
  35783. */
  35784. Geometry.prototype.applyToMesh = function (mesh) {
  35785. if (mesh._geometry === this) {
  35786. return;
  35787. }
  35788. var previousGeometry = mesh._geometry;
  35789. if (previousGeometry) {
  35790. previousGeometry.releaseForMesh(mesh);
  35791. }
  35792. var meshes = this._meshes;
  35793. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35794. mesh._geometry = this;
  35795. this._scene.pushGeometry(this);
  35796. meshes.push(mesh);
  35797. if (this.isReady()) {
  35798. this._applyToMesh(mesh);
  35799. }
  35800. else {
  35801. mesh._boundingInfo = this._boundingInfo;
  35802. }
  35803. };
  35804. Geometry.prototype.updateExtend = function (data, stride) {
  35805. if (data === void 0) { data = null; }
  35806. if (!data) {
  35807. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35808. }
  35809. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35810. };
  35811. Geometry.prototype._applyToMesh = function (mesh) {
  35812. var numOfMeshes = this._meshes.length;
  35813. // vertexBuffers
  35814. for (var kind in this._vertexBuffers) {
  35815. if (numOfMeshes === 1) {
  35816. this._vertexBuffers[kind].create();
  35817. }
  35818. var buffer = this._vertexBuffers[kind].getBuffer();
  35819. if (buffer)
  35820. buffer.references = numOfMeshes;
  35821. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35822. if (!this._extend) {
  35823. this.updateExtend(this._vertexBuffers[kind].getData());
  35824. }
  35825. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35826. mesh._createGlobalSubMesh(false);
  35827. //bounding info was just created again, world matrix should be applied again.
  35828. mesh._updateBoundingInfo();
  35829. }
  35830. }
  35831. // indexBuffer
  35832. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35833. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35834. }
  35835. if (this._indexBuffer) {
  35836. this._indexBuffer.references = numOfMeshes;
  35837. }
  35838. };
  35839. Geometry.prototype.notifyUpdate = function (kind) {
  35840. if (this.onGeometryUpdated) {
  35841. this.onGeometryUpdated(this, kind);
  35842. }
  35843. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  35844. var mesh = _a[_i];
  35845. mesh._markSubMeshesAsAttributesDirty();
  35846. }
  35847. };
  35848. /**
  35849. * Load the geometry if it was flagged as delay loaded
  35850. * @param scene defines the hosting scene
  35851. * @param onLoaded defines a callback called when the geometry is loaded
  35852. */
  35853. Geometry.prototype.load = function (scene, onLoaded) {
  35854. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35855. return;
  35856. }
  35857. if (this.isReady()) {
  35858. if (onLoaded) {
  35859. onLoaded();
  35860. }
  35861. return;
  35862. }
  35863. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35864. this._queueLoad(scene, onLoaded);
  35865. };
  35866. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35867. var _this = this;
  35868. if (!this.delayLoadingFile) {
  35869. return;
  35870. }
  35871. scene._addPendingData(this);
  35872. scene._loadFile(this.delayLoadingFile, function (data) {
  35873. if (!_this._delayLoadingFunction) {
  35874. return;
  35875. }
  35876. _this._delayLoadingFunction(JSON.parse(data), _this);
  35877. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35878. _this._delayInfo = [];
  35879. scene._removePendingData(_this);
  35880. var meshes = _this._meshes;
  35881. var numOfMeshes = meshes.length;
  35882. for (var index = 0; index < numOfMeshes; index++) {
  35883. _this._applyToMesh(meshes[index]);
  35884. }
  35885. if (onLoaded) {
  35886. onLoaded();
  35887. }
  35888. }, undefined, true);
  35889. };
  35890. /**
  35891. * Invert the geometry to move from a right handed system to a left handed one.
  35892. */
  35893. Geometry.prototype.toLeftHanded = function () {
  35894. // Flip faces
  35895. var tIndices = this.getIndices(false);
  35896. if (tIndices != null && tIndices.length > 0) {
  35897. for (var i = 0; i < tIndices.length; i += 3) {
  35898. var tTemp = tIndices[i + 0];
  35899. tIndices[i + 0] = tIndices[i + 2];
  35900. tIndices[i + 2] = tTemp;
  35901. }
  35902. this.setIndices(tIndices);
  35903. }
  35904. // Negate position.z
  35905. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35906. if (tPositions != null && tPositions.length > 0) {
  35907. for (var i = 0; i < tPositions.length; i += 3) {
  35908. tPositions[i + 2] = -tPositions[i + 2];
  35909. }
  35910. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35911. }
  35912. // Negate normal.z
  35913. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35914. if (tNormals != null && tNormals.length > 0) {
  35915. for (var i = 0; i < tNormals.length; i += 3) {
  35916. tNormals[i + 2] = -tNormals[i + 2];
  35917. }
  35918. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35919. }
  35920. };
  35921. // Cache
  35922. /** @ignore */
  35923. Geometry.prototype._resetPointsArrayCache = function () {
  35924. this._positions = null;
  35925. };
  35926. /** @ignore */
  35927. Geometry.prototype._generatePointsArray = function () {
  35928. if (this._positions)
  35929. return true;
  35930. this._positions = [];
  35931. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35932. if (!data) {
  35933. return false;
  35934. }
  35935. for (var index = 0; index < data.length; index += 3) {
  35936. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  35937. }
  35938. return true;
  35939. };
  35940. /**
  35941. * Gets a value indicating if the geometry is disposed
  35942. * @returns true if the geometry was disposed
  35943. */
  35944. Geometry.prototype.isDisposed = function () {
  35945. return this._isDisposed;
  35946. };
  35947. Geometry.prototype._disposeVertexArrayObjects = function () {
  35948. if (this._vertexArrayObjects) {
  35949. for (var kind in this._vertexArrayObjects) {
  35950. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  35951. }
  35952. this._vertexArrayObjects = {};
  35953. }
  35954. };
  35955. /**
  35956. * Free all associated resources
  35957. */
  35958. Geometry.prototype.dispose = function () {
  35959. var meshes = this._meshes;
  35960. var numOfMeshes = meshes.length;
  35961. var index;
  35962. for (index = 0; index < numOfMeshes; index++) {
  35963. this.releaseForMesh(meshes[index]);
  35964. }
  35965. this._meshes = [];
  35966. this._disposeVertexArrayObjects();
  35967. for (var kind in this._vertexBuffers) {
  35968. this._vertexBuffers[kind].dispose();
  35969. }
  35970. this._vertexBuffers = {};
  35971. this._totalVertices = 0;
  35972. if (this._indexBuffer) {
  35973. this._engine._releaseBuffer(this._indexBuffer);
  35974. }
  35975. this._indexBuffer = null;
  35976. this._indices = [];
  35977. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35978. this.delayLoadingFile = null;
  35979. this._delayLoadingFunction = null;
  35980. this._delayInfo = [];
  35981. this._boundingInfo = null;
  35982. this._scene.removeGeometry(this);
  35983. this._isDisposed = true;
  35984. };
  35985. /**
  35986. * Clone the current geometry into a new geometry
  35987. * @param id defines the unique ID of the new geometry
  35988. * @returns a new geometry object
  35989. */
  35990. Geometry.prototype.copy = function (id) {
  35991. var vertexData = new BABYLON.VertexData();
  35992. vertexData.indices = [];
  35993. var indices = this.getIndices();
  35994. if (indices) {
  35995. for (var index = 0; index < indices.length; index++) {
  35996. vertexData.indices.push(indices[index]);
  35997. }
  35998. }
  35999. var updatable = false;
  36000. var stopChecking = false;
  36001. var kind;
  36002. for (kind in this._vertexBuffers) {
  36003. // using slice() to make a copy of the array and not just reference it
  36004. var data = this.getVerticesData(kind);
  36005. if (data instanceof Float32Array) {
  36006. vertexData.set(new Float32Array(data), kind);
  36007. }
  36008. else {
  36009. vertexData.set(data.slice(0), kind);
  36010. }
  36011. if (!stopChecking) {
  36012. var vb = this.getVertexBuffer(kind);
  36013. if (vb) {
  36014. updatable = vb.isUpdatable();
  36015. stopChecking = !updatable;
  36016. }
  36017. }
  36018. }
  36019. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  36020. geometry.delayLoadState = this.delayLoadState;
  36021. geometry.delayLoadingFile = this.delayLoadingFile;
  36022. geometry._delayLoadingFunction = this._delayLoadingFunction;
  36023. for (kind in this._delayInfo) {
  36024. geometry._delayInfo = geometry._delayInfo || [];
  36025. geometry._delayInfo.push(kind);
  36026. }
  36027. // Bounding info
  36028. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  36029. return geometry;
  36030. };
  36031. /**
  36032. * Serialize the current geometry info (and not the vertices data) into a JSON object
  36033. * @return a JSON representation of the current geometry data (without the vertices data)
  36034. */
  36035. Geometry.prototype.serialize = function () {
  36036. var serializationObject = {};
  36037. serializationObject.id = this.id;
  36038. serializationObject.updatable = this._updatable;
  36039. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  36040. serializationObject.tags = BABYLON.Tags.GetTags(this);
  36041. }
  36042. return serializationObject;
  36043. };
  36044. Geometry.prototype.toNumberArray = function (origin) {
  36045. if (Array.isArray(origin)) {
  36046. return origin;
  36047. }
  36048. else {
  36049. return Array.prototype.slice.call(origin);
  36050. }
  36051. };
  36052. /**
  36053. * Serialize all vertices data into a JSON oject
  36054. * @returns a JSON representation of the current geometry data
  36055. */
  36056. Geometry.prototype.serializeVerticeData = function () {
  36057. var serializationObject = this.serialize();
  36058. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36059. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  36060. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  36061. serializationObject.positions._updatable = true;
  36062. }
  36063. }
  36064. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36065. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  36066. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  36067. serializationObject.normals._updatable = true;
  36068. }
  36069. }
  36070. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36071. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  36072. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  36073. serializationObject.tangets._updatable = true;
  36074. }
  36075. }
  36076. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36077. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  36078. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  36079. serializationObject.uvs._updatable = true;
  36080. }
  36081. }
  36082. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36083. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  36084. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  36085. serializationObject.uv2s._updatable = true;
  36086. }
  36087. }
  36088. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36089. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  36090. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  36091. serializationObject.uv3s._updatable = true;
  36092. }
  36093. }
  36094. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36095. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  36096. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  36097. serializationObject.uv4s._updatable = true;
  36098. }
  36099. }
  36100. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36101. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  36102. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  36103. serializationObject.uv5s._updatable = true;
  36104. }
  36105. }
  36106. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36107. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  36108. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  36109. serializationObject.uv6s._updatable = true;
  36110. }
  36111. }
  36112. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36113. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  36114. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  36115. serializationObject.colors._updatable = true;
  36116. }
  36117. }
  36118. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36119. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  36120. serializationObject.matricesIndices._isExpanded = true;
  36121. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36122. serializationObject.matricesIndices._updatable = true;
  36123. }
  36124. }
  36125. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36126. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  36127. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36128. serializationObject.matricesWeights._updatable = true;
  36129. }
  36130. }
  36131. serializationObject.indices = this.toNumberArray(this.getIndices());
  36132. return serializationObject;
  36133. };
  36134. // Statics
  36135. /**
  36136. * Extracts a clone of a mesh geometry
  36137. * @param mesh defines the source mesh
  36138. * @param id defines the unique ID of the new geometry object
  36139. * @returns the new geometry object
  36140. */
  36141. Geometry.ExtractFromMesh = function (mesh, id) {
  36142. var geometry = mesh._geometry;
  36143. if (!geometry) {
  36144. return null;
  36145. }
  36146. return geometry.copy(id);
  36147. };
  36148. /**
  36149. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  36150. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  36151. * Be aware Math.random() could cause collisions, but:
  36152. * "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"
  36153. * @returns a string containing a new GUID
  36154. */
  36155. Geometry.RandomId = function () {
  36156. return BABYLON.Tools.RandomId();
  36157. };
  36158. /** @ignore */
  36159. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  36160. var scene = mesh.getScene();
  36161. // Geometry
  36162. var geometryId = parsedGeometry.geometryId;
  36163. if (geometryId) {
  36164. var geometry = scene.getGeometryByID(geometryId);
  36165. if (geometry) {
  36166. geometry.applyToMesh(mesh);
  36167. }
  36168. }
  36169. else if (parsedGeometry instanceof ArrayBuffer) {
  36170. var binaryInfo = mesh._binaryInfo;
  36171. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  36172. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  36173. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  36174. }
  36175. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  36176. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  36177. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  36178. }
  36179. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  36180. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  36181. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  36182. }
  36183. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  36184. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  36185. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  36186. }
  36187. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  36188. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  36189. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  36190. }
  36191. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  36192. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  36193. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  36194. }
  36195. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  36196. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  36197. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  36198. }
  36199. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  36200. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  36201. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  36202. }
  36203. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  36204. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  36205. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  36206. }
  36207. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  36208. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  36209. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  36210. }
  36211. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  36212. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  36213. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  36214. }
  36215. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  36216. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  36217. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  36218. }
  36219. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  36220. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  36221. mesh.setIndices(indicesData, null);
  36222. }
  36223. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  36224. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  36225. mesh.subMeshes = [];
  36226. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  36227. var materialIndex = subMeshesData[(i * 5) + 0];
  36228. var verticesStart = subMeshesData[(i * 5) + 1];
  36229. var verticesCount = subMeshesData[(i * 5) + 2];
  36230. var indexStart = subMeshesData[(i * 5) + 3];
  36231. var indexCount = subMeshesData[(i * 5) + 4];
  36232. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  36233. }
  36234. }
  36235. }
  36236. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  36237. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  36238. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  36239. if (parsedGeometry.tangents) {
  36240. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  36241. }
  36242. if (parsedGeometry.uvs) {
  36243. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  36244. }
  36245. if (parsedGeometry.uvs2) {
  36246. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  36247. }
  36248. if (parsedGeometry.uvs3) {
  36249. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  36250. }
  36251. if (parsedGeometry.uvs4) {
  36252. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  36253. }
  36254. if (parsedGeometry.uvs5) {
  36255. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  36256. }
  36257. if (parsedGeometry.uvs6) {
  36258. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  36259. }
  36260. if (parsedGeometry.colors) {
  36261. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  36262. }
  36263. if (parsedGeometry.matricesIndices) {
  36264. if (!parsedGeometry.matricesIndices._isExpanded) {
  36265. var floatIndices = [];
  36266. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  36267. var matricesIndex = parsedGeometry.matricesIndices[i];
  36268. floatIndices.push(matricesIndex & 0x000000FF);
  36269. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36270. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36271. floatIndices.push(matricesIndex >> 24);
  36272. }
  36273. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  36274. }
  36275. else {
  36276. delete parsedGeometry.matricesIndices._isExpanded;
  36277. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  36278. }
  36279. }
  36280. if (parsedGeometry.matricesIndicesExtra) {
  36281. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  36282. var floatIndices = [];
  36283. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  36284. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  36285. floatIndices.push(matricesIndex & 0x000000FF);
  36286. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36287. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36288. floatIndices.push(matricesIndex >> 24);
  36289. }
  36290. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  36291. }
  36292. else {
  36293. delete parsedGeometry.matricesIndices._isExpanded;
  36294. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  36295. }
  36296. }
  36297. if (parsedGeometry.matricesWeights) {
  36298. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  36299. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  36300. }
  36301. if (parsedGeometry.matricesWeightsExtra) {
  36302. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  36303. }
  36304. mesh.setIndices(parsedGeometry.indices, null);
  36305. }
  36306. // SubMeshes
  36307. if (parsedGeometry.subMeshes) {
  36308. mesh.subMeshes = [];
  36309. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  36310. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  36311. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  36312. }
  36313. }
  36314. // Flat shading
  36315. if (mesh._shouldGenerateFlatShading) {
  36316. mesh.convertToFlatShadedMesh();
  36317. delete mesh._shouldGenerateFlatShading;
  36318. }
  36319. // Update
  36320. mesh.computeWorldMatrix(true);
  36321. // Octree
  36322. var sceneOctree = scene.selectionOctree;
  36323. if (sceneOctree !== undefined && sceneOctree !== null) {
  36324. sceneOctree.addMesh(mesh);
  36325. }
  36326. };
  36327. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  36328. var epsilon = 1e-3;
  36329. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  36330. return;
  36331. }
  36332. var noInfluenceBoneIndex = 0.0;
  36333. if (parsedGeometry.skeletonId > -1) {
  36334. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  36335. if (!skeleton) {
  36336. return;
  36337. }
  36338. noInfluenceBoneIndex = skeleton.bones.length;
  36339. }
  36340. else {
  36341. return;
  36342. }
  36343. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  36344. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  36345. var matricesWeights = parsedGeometry.matricesWeights;
  36346. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  36347. var influencers = parsedGeometry.numBoneInfluencer;
  36348. var size = matricesWeights.length;
  36349. for (var i = 0; i < size; i += 4) {
  36350. var weight = 0.0;
  36351. var firstZeroWeight = -1;
  36352. for (var j = 0; j < 4; j++) {
  36353. var w = matricesWeights[i + j];
  36354. weight += w;
  36355. if (w < epsilon && firstZeroWeight < 0) {
  36356. firstZeroWeight = j;
  36357. }
  36358. }
  36359. if (matricesWeightsExtra) {
  36360. for (var j = 0; j < 4; j++) {
  36361. var w = matricesWeightsExtra[i + j];
  36362. weight += w;
  36363. if (w < epsilon && firstZeroWeight < 0) {
  36364. firstZeroWeight = j + 4;
  36365. }
  36366. }
  36367. }
  36368. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  36369. firstZeroWeight = influencers - 1;
  36370. }
  36371. if (weight > epsilon) {
  36372. var mweight = 1.0 / weight;
  36373. for (var j = 0; j < 4; j++) {
  36374. matricesWeights[i + j] *= mweight;
  36375. }
  36376. if (matricesWeightsExtra) {
  36377. for (var j = 0; j < 4; j++) {
  36378. matricesWeightsExtra[i + j] *= mweight;
  36379. }
  36380. }
  36381. }
  36382. else {
  36383. if (firstZeroWeight >= 4) {
  36384. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  36385. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  36386. }
  36387. else {
  36388. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  36389. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  36390. }
  36391. }
  36392. }
  36393. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  36394. if (parsedGeometry.matricesWeightsExtra) {
  36395. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  36396. }
  36397. };
  36398. /**
  36399. * Create a new geometry from persisted data (Using .babylon file format)
  36400. * @param parsedVertexData defines the persisted data
  36401. * @param scene defines the hosting scene
  36402. * @param rootUrl defines the root url to use to load assets (like delayed data)
  36403. * @returns the new geometry object
  36404. */
  36405. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  36406. if (scene.getGeometryByID(parsedVertexData.id)) {
  36407. return null; // null since geometry could be something else than a box...
  36408. }
  36409. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  36410. if (BABYLON.Tags) {
  36411. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  36412. }
  36413. if (parsedVertexData.delayLoadingFile) {
  36414. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  36415. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  36416. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  36417. geometry._delayInfo = [];
  36418. if (parsedVertexData.hasUVs) {
  36419. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  36420. }
  36421. if (parsedVertexData.hasUVs2) {
  36422. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  36423. }
  36424. if (parsedVertexData.hasUVs3) {
  36425. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  36426. }
  36427. if (parsedVertexData.hasUVs4) {
  36428. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  36429. }
  36430. if (parsedVertexData.hasUVs5) {
  36431. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  36432. }
  36433. if (parsedVertexData.hasUVs6) {
  36434. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  36435. }
  36436. if (parsedVertexData.hasColors) {
  36437. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  36438. }
  36439. if (parsedVertexData.hasMatricesIndices) {
  36440. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36441. }
  36442. if (parsedVertexData.hasMatricesWeights) {
  36443. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36444. }
  36445. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  36446. }
  36447. else {
  36448. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  36449. }
  36450. scene.pushGeometry(geometry, true);
  36451. return geometry;
  36452. };
  36453. return Geometry;
  36454. }());
  36455. BABYLON.Geometry = Geometry;
  36456. // Primitives
  36457. /// Abstract class
  36458. /**
  36459. * Abstract class used to provide common services for all typed geometries
  36460. */
  36461. var _PrimitiveGeometry = /** @class */ (function (_super) {
  36462. __extends(_PrimitiveGeometry, _super);
  36463. /**
  36464. * Creates a new typed geometry
  36465. * @param id defines the unique ID of the geometry
  36466. * @param scene defines the hosting scene
  36467. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36468. * @param mesh defines the hosting mesh (can be null)
  36469. */
  36470. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  36471. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  36472. if (mesh === void 0) { mesh = null; }
  36473. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  36474. _this._canBeRegenerated = _canBeRegenerated;
  36475. _this._beingRegenerated = true;
  36476. _this.regenerate();
  36477. _this._beingRegenerated = false;
  36478. return _this;
  36479. }
  36480. /**
  36481. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  36482. * @returns true if the geometry can be regenerated
  36483. */
  36484. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  36485. return this._canBeRegenerated;
  36486. };
  36487. /**
  36488. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  36489. */
  36490. _PrimitiveGeometry.prototype.regenerate = function () {
  36491. if (!this._canBeRegenerated) {
  36492. return;
  36493. }
  36494. this._beingRegenerated = true;
  36495. this.setAllVerticesData(this._regenerateVertexData(), false);
  36496. this._beingRegenerated = false;
  36497. };
  36498. /**
  36499. * Clone the geometry
  36500. * @param id defines the unique ID of the new geometry
  36501. * @returns the new geometry
  36502. */
  36503. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  36504. return _super.prototype.copy.call(this, id);
  36505. };
  36506. // overrides
  36507. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  36508. if (!this._beingRegenerated) {
  36509. return;
  36510. }
  36511. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  36512. };
  36513. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  36514. if (!this._beingRegenerated) {
  36515. return;
  36516. }
  36517. _super.prototype.setVerticesData.call(this, kind, data, false);
  36518. };
  36519. // to override
  36520. /** @ignore */
  36521. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  36522. throw new Error("Abstract method");
  36523. };
  36524. _PrimitiveGeometry.prototype.copy = function (id) {
  36525. throw new Error("Must be overriden in sub-classes.");
  36526. };
  36527. _PrimitiveGeometry.prototype.serialize = function () {
  36528. var serializationObject = _super.prototype.serialize.call(this);
  36529. serializationObject.canBeRegenerated = this.canBeRegenerated();
  36530. return serializationObject;
  36531. };
  36532. return _PrimitiveGeometry;
  36533. }(Geometry));
  36534. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  36535. /**
  36536. * Creates a ribbon geometry
  36537. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  36538. */
  36539. var RibbonGeometry = /** @class */ (function (_super) {
  36540. __extends(RibbonGeometry, _super);
  36541. /**
  36542. * Creates a ribbon geometry
  36543. * @param id defines the unique ID of the geometry
  36544. * @param scene defines the hosting scene
  36545. * @param pathArray defines the array of paths to use
  36546. * @param closeArray defines if the last path and the first path must be joined
  36547. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  36548. * @param offset defines the offset between points
  36549. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36550. * @param mesh defines the hosting mesh (can be null)
  36551. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36552. */
  36553. function RibbonGeometry(id, scene,
  36554. /**
  36555. * Defines the array of paths to use
  36556. */
  36557. pathArray,
  36558. /**
  36559. * Defines if the last and first points of each path in your pathArray must be joined
  36560. */
  36561. closeArray,
  36562. /**
  36563. * Defines if the last and first points of each path in your pathArray must be joined
  36564. */
  36565. closePath,
  36566. /**
  36567. * Defines the offset between points
  36568. */
  36569. offset, canBeRegenerated, mesh,
  36570. /**
  36571. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36572. */
  36573. side) {
  36574. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36575. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36576. _this.pathArray = pathArray;
  36577. _this.closeArray = closeArray;
  36578. _this.closePath = closePath;
  36579. _this.offset = offset;
  36580. _this.side = side;
  36581. return _this;
  36582. }
  36583. /** @ignore */
  36584. RibbonGeometry.prototype._regenerateVertexData = function () {
  36585. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  36586. };
  36587. RibbonGeometry.prototype.copy = function (id) {
  36588. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  36589. };
  36590. return RibbonGeometry;
  36591. }(_PrimitiveGeometry));
  36592. BABYLON.RibbonGeometry = RibbonGeometry;
  36593. /**
  36594. * Creates a box geometry
  36595. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  36596. */
  36597. var BoxGeometry = /** @class */ (function (_super) {
  36598. __extends(BoxGeometry, _super);
  36599. /**
  36600. * Creates a box geometry
  36601. * @param id defines the unique ID of the geometry
  36602. * @param scene defines the hosting scene
  36603. * @param size defines the zise of the box (width, height and depth are the same)
  36604. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36605. * @param mesh defines the hosting mesh (can be null)
  36606. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36607. */
  36608. function BoxGeometry(id, scene,
  36609. /**
  36610. * Defines the zise of the box (width, height and depth are the same)
  36611. */
  36612. size, canBeRegenerated, mesh,
  36613. /**
  36614. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36615. */
  36616. side) {
  36617. if (mesh === void 0) { mesh = null; }
  36618. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36619. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36620. _this.size = size;
  36621. _this.side = side;
  36622. return _this;
  36623. }
  36624. BoxGeometry.prototype._regenerateVertexData = function () {
  36625. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  36626. };
  36627. BoxGeometry.prototype.copy = function (id) {
  36628. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  36629. };
  36630. BoxGeometry.prototype.serialize = function () {
  36631. var serializationObject = _super.prototype.serialize.call(this);
  36632. serializationObject.size = this.size;
  36633. return serializationObject;
  36634. };
  36635. BoxGeometry.Parse = function (parsedBox, scene) {
  36636. if (scene.getGeometryByID(parsedBox.id)) {
  36637. return null; // null since geometry could be something else than a box...
  36638. }
  36639. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  36640. if (BABYLON.Tags) {
  36641. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  36642. }
  36643. scene.pushGeometry(box, true);
  36644. return box;
  36645. };
  36646. return BoxGeometry;
  36647. }(_PrimitiveGeometry));
  36648. BABYLON.BoxGeometry = BoxGeometry;
  36649. /**
  36650. * Creates a sphere geometry
  36651. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  36652. */
  36653. var SphereGeometry = /** @class */ (function (_super) {
  36654. __extends(SphereGeometry, _super);
  36655. /**
  36656. * Create a new sphere geometry
  36657. * @param id defines the unique ID of the geometry
  36658. * @param scene defines the hosting scene
  36659. * @param segments defines the number of segments to use to create the sphere
  36660. * @param diameter defines the diameter of the sphere
  36661. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36662. * @param mesh defines the hosting mesh (can be null)
  36663. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36664. */
  36665. function SphereGeometry(id, scene,
  36666. /**
  36667. * Defines the number of segments to use to create the sphere
  36668. */
  36669. segments,
  36670. /**
  36671. * Defines the diameter of the sphere
  36672. */
  36673. diameter, canBeRegenerated, mesh,
  36674. /**
  36675. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36676. */
  36677. side) {
  36678. if (mesh === void 0) { mesh = null; }
  36679. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36680. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36681. _this.segments = segments;
  36682. _this.diameter = diameter;
  36683. _this.side = side;
  36684. return _this;
  36685. }
  36686. SphereGeometry.prototype._regenerateVertexData = function () {
  36687. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  36688. };
  36689. SphereGeometry.prototype.copy = function (id) {
  36690. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  36691. };
  36692. SphereGeometry.prototype.serialize = function () {
  36693. var serializationObject = _super.prototype.serialize.call(this);
  36694. serializationObject.segments = this.segments;
  36695. serializationObject.diameter = this.diameter;
  36696. return serializationObject;
  36697. };
  36698. SphereGeometry.Parse = function (parsedSphere, scene) {
  36699. if (scene.getGeometryByID(parsedSphere.id)) {
  36700. return null; // null since geometry could be something else than a sphere...
  36701. }
  36702. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  36703. if (BABYLON.Tags) {
  36704. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  36705. }
  36706. scene.pushGeometry(sphere, true);
  36707. return sphere;
  36708. };
  36709. return SphereGeometry;
  36710. }(_PrimitiveGeometry));
  36711. BABYLON.SphereGeometry = SphereGeometry;
  36712. /**
  36713. * Creates a disc geometry
  36714. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  36715. */
  36716. var DiscGeometry = /** @class */ (function (_super) {
  36717. __extends(DiscGeometry, _super);
  36718. /**
  36719. * Creates a new disc geometry
  36720. * @param id defines the unique ID of the geometry
  36721. * @param scene defines the hosting scene
  36722. * @param radius defines the radius of the disc
  36723. * @param tessellation defines the tesselation factor to apply to the disc
  36724. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36725. * @param mesh defines the hosting mesh (can be null)
  36726. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36727. */
  36728. function DiscGeometry(id, scene,
  36729. /**
  36730. * Defines the radius of the disc
  36731. */
  36732. radius,
  36733. /**
  36734. * Defines the tesselation factor to apply to the disc
  36735. */
  36736. tessellation, canBeRegenerated, mesh,
  36737. /**
  36738. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36739. */
  36740. side) {
  36741. if (mesh === void 0) { mesh = null; }
  36742. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36743. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36744. _this.radius = radius;
  36745. _this.tessellation = tessellation;
  36746. _this.side = side;
  36747. return _this;
  36748. }
  36749. DiscGeometry.prototype._regenerateVertexData = function () {
  36750. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  36751. };
  36752. DiscGeometry.prototype.copy = function (id) {
  36753. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  36754. };
  36755. return DiscGeometry;
  36756. }(_PrimitiveGeometry));
  36757. BABYLON.DiscGeometry = DiscGeometry;
  36758. /**
  36759. * Creates a new cylinder geometry
  36760. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  36761. */
  36762. var CylinderGeometry = /** @class */ (function (_super) {
  36763. __extends(CylinderGeometry, _super);
  36764. /**
  36765. * Creates a new cylinder geometry
  36766. * @param id defines the unique ID of the geometry
  36767. * @param scene defines the hosting scene
  36768. * @param height defines the height of the cylinder
  36769. * @param diameterTop defines the diameter of the cylinder's top cap
  36770. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  36771. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  36772. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  36773. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36774. * @param mesh defines the hosting mesh (can be null)
  36775. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36776. */
  36777. function CylinderGeometry(id, scene,
  36778. /**
  36779. * Defines the height of the cylinder
  36780. */
  36781. height,
  36782. /**
  36783. * Defines the diameter of the cylinder's top cap
  36784. */
  36785. diameterTop,
  36786. /**
  36787. * Defines the diameter of the cylinder's bottom cap
  36788. */
  36789. diameterBottom,
  36790. /**
  36791. * Defines the tessellation factor to apply to the cylinder
  36792. */
  36793. tessellation,
  36794. /**
  36795. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  36796. */
  36797. subdivisions, canBeRegenerated, mesh,
  36798. /**
  36799. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36800. */
  36801. side) {
  36802. if (subdivisions === void 0) { subdivisions = 1; }
  36803. if (mesh === void 0) { mesh = null; }
  36804. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36805. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36806. _this.height = height;
  36807. _this.diameterTop = diameterTop;
  36808. _this.diameterBottom = diameterBottom;
  36809. _this.tessellation = tessellation;
  36810. _this.subdivisions = subdivisions;
  36811. _this.side = side;
  36812. return _this;
  36813. }
  36814. CylinderGeometry.prototype._regenerateVertexData = function () {
  36815. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36816. };
  36817. CylinderGeometry.prototype.copy = function (id) {
  36818. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36819. };
  36820. CylinderGeometry.prototype.serialize = function () {
  36821. var serializationObject = _super.prototype.serialize.call(this);
  36822. serializationObject.height = this.height;
  36823. serializationObject.diameterTop = this.diameterTop;
  36824. serializationObject.diameterBottom = this.diameterBottom;
  36825. serializationObject.tessellation = this.tessellation;
  36826. return serializationObject;
  36827. };
  36828. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  36829. if (scene.getGeometryByID(parsedCylinder.id)) {
  36830. return null; // null since geometry could be something else than a cylinder...
  36831. }
  36832. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36833. if (BABYLON.Tags) {
  36834. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36835. }
  36836. scene.pushGeometry(cylinder, true);
  36837. return cylinder;
  36838. };
  36839. return CylinderGeometry;
  36840. }(_PrimitiveGeometry));
  36841. BABYLON.CylinderGeometry = CylinderGeometry;
  36842. /**
  36843. * Creates a new torus geometry
  36844. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  36845. */
  36846. var TorusGeometry = /** @class */ (function (_super) {
  36847. __extends(TorusGeometry, _super);
  36848. /**
  36849. * Creates a new torus geometry
  36850. * @param id defines the unique ID of the geometry
  36851. * @param scene defines the hosting scene
  36852. * @param diameter defines the diameter of the torus
  36853. * @param thickness defines the thickness of the torus (ie. internal diameter)
  36854. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  36855. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36856. * @param mesh defines the hosting mesh (can be null)
  36857. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36858. */
  36859. function TorusGeometry(id, scene,
  36860. /**
  36861. * Defines the diameter of the torus
  36862. */
  36863. diameter,
  36864. /**
  36865. * Defines the thickness of the torus (ie. internal diameter)
  36866. */
  36867. thickness,
  36868. /**
  36869. * Defines the tesselation factor to apply to the torus
  36870. */
  36871. tessellation, canBeRegenerated, mesh,
  36872. /**
  36873. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36874. */
  36875. side) {
  36876. if (mesh === void 0) { mesh = null; }
  36877. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36878. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36879. _this.diameter = diameter;
  36880. _this.thickness = thickness;
  36881. _this.tessellation = tessellation;
  36882. _this.side = side;
  36883. return _this;
  36884. }
  36885. TorusGeometry.prototype._regenerateVertexData = function () {
  36886. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36887. };
  36888. TorusGeometry.prototype.copy = function (id) {
  36889. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36890. };
  36891. TorusGeometry.prototype.serialize = function () {
  36892. var serializationObject = _super.prototype.serialize.call(this);
  36893. serializationObject.diameter = this.diameter;
  36894. serializationObject.thickness = this.thickness;
  36895. serializationObject.tessellation = this.tessellation;
  36896. return serializationObject;
  36897. };
  36898. TorusGeometry.Parse = function (parsedTorus, scene) {
  36899. if (scene.getGeometryByID(parsedTorus.id)) {
  36900. return null; // null since geometry could be something else than a torus...
  36901. }
  36902. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36903. if (BABYLON.Tags) {
  36904. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36905. }
  36906. scene.pushGeometry(torus, true);
  36907. return torus;
  36908. };
  36909. return TorusGeometry;
  36910. }(_PrimitiveGeometry));
  36911. BABYLON.TorusGeometry = TorusGeometry;
  36912. /**
  36913. * Creates a new ground geometry
  36914. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  36915. */
  36916. var GroundGeometry = /** @class */ (function (_super) {
  36917. __extends(GroundGeometry, _super);
  36918. /**
  36919. * Creates a new ground geometry
  36920. * @param id defines the unique ID of the geometry
  36921. * @param scene defines the hosting scene
  36922. * @param width defines the width of the ground
  36923. * @param height defines the height of the ground
  36924. * @param subdivisions defines the subdivisions to apply to the ground
  36925. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36926. * @param mesh defines the hosting mesh (can be null)
  36927. */
  36928. function GroundGeometry(id, scene,
  36929. /**
  36930. * Defines the width of the ground
  36931. */
  36932. width,
  36933. /**
  36934. * Defines the height of the ground
  36935. */
  36936. height,
  36937. /**
  36938. * Defines the subdivisions to apply to the ground
  36939. */
  36940. subdivisions, canBeRegenerated, mesh) {
  36941. if (mesh === void 0) { mesh = null; }
  36942. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36943. _this.width = width;
  36944. _this.height = height;
  36945. _this.subdivisions = subdivisions;
  36946. return _this;
  36947. }
  36948. GroundGeometry.prototype._regenerateVertexData = function () {
  36949. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  36950. };
  36951. GroundGeometry.prototype.copy = function (id) {
  36952. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  36953. };
  36954. GroundGeometry.prototype.serialize = function () {
  36955. var serializationObject = _super.prototype.serialize.call(this);
  36956. serializationObject.width = this.width;
  36957. serializationObject.height = this.height;
  36958. serializationObject.subdivisions = this.subdivisions;
  36959. return serializationObject;
  36960. };
  36961. GroundGeometry.Parse = function (parsedGround, scene) {
  36962. if (scene.getGeometryByID(parsedGround.id)) {
  36963. return null; // null since geometry could be something else than a ground...
  36964. }
  36965. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  36966. if (BABYLON.Tags) {
  36967. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  36968. }
  36969. scene.pushGeometry(ground, true);
  36970. return ground;
  36971. };
  36972. return GroundGeometry;
  36973. }(_PrimitiveGeometry));
  36974. BABYLON.GroundGeometry = GroundGeometry;
  36975. /**
  36976. * Creates a tiled ground geometry
  36977. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  36978. */
  36979. var TiledGroundGeometry = /** @class */ (function (_super) {
  36980. __extends(TiledGroundGeometry, _super);
  36981. /**
  36982. * Creates a tiled ground geometry
  36983. * @param id defines the unique ID of the geometry
  36984. * @param scene defines the hosting scene
  36985. * @param xmin defines the minimum value on X axis
  36986. * @param zmin defines the minimum value on Z axis
  36987. * @param xmax defines the maximum value on X axis
  36988. * @param zmax defines the maximum value on Z axis
  36989. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  36990. * @param precision defines the precision to use when computing the tiles
  36991. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36992. * @param mesh defines the hosting mesh (can be null)
  36993. */
  36994. function TiledGroundGeometry(id, scene,
  36995. /**
  36996. * Defines the minimum value on X axis
  36997. */
  36998. xmin,
  36999. /**
  37000. * Defines the minimum value on Z axis
  37001. */
  37002. zmin,
  37003. /**
  37004. * Defines the maximum value on X axis
  37005. */
  37006. xmax,
  37007. /**
  37008. * Defines the maximum value on Z axis
  37009. */
  37010. zmax,
  37011. /**
  37012. * Defines the subdivisions to apply to the ground
  37013. */
  37014. subdivisions,
  37015. /**
  37016. * Defines the precision to use when computing the tiles
  37017. */
  37018. precision, canBeRegenerated, mesh) {
  37019. if (mesh === void 0) { mesh = null; }
  37020. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37021. _this.xmin = xmin;
  37022. _this.zmin = zmin;
  37023. _this.xmax = xmax;
  37024. _this.zmax = zmax;
  37025. _this.subdivisions = subdivisions;
  37026. _this.precision = precision;
  37027. return _this;
  37028. }
  37029. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  37030. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  37031. };
  37032. TiledGroundGeometry.prototype.copy = function (id) {
  37033. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  37034. };
  37035. return TiledGroundGeometry;
  37036. }(_PrimitiveGeometry));
  37037. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  37038. /**
  37039. * Creates a plane geometry
  37040. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  37041. */
  37042. var PlaneGeometry = /** @class */ (function (_super) {
  37043. __extends(PlaneGeometry, _super);
  37044. /**
  37045. * Creates a plane geometry
  37046. * @param id defines the unique ID of the geometry
  37047. * @param scene defines the hosting scene
  37048. * @param size defines the size of the plane (width === height)
  37049. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  37050. * @param mesh defines the hosting mesh (can be null)
  37051. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37052. */
  37053. function PlaneGeometry(id, scene,
  37054. /**
  37055. * Defines the size of the plane (width === height)
  37056. */
  37057. size, canBeRegenerated, mesh,
  37058. /**
  37059. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37060. */
  37061. side) {
  37062. if (mesh === void 0) { mesh = null; }
  37063. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37064. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37065. _this.size = size;
  37066. _this.side = side;
  37067. return _this;
  37068. }
  37069. PlaneGeometry.prototype._regenerateVertexData = function () {
  37070. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  37071. };
  37072. PlaneGeometry.prototype.copy = function (id) {
  37073. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  37074. };
  37075. PlaneGeometry.prototype.serialize = function () {
  37076. var serializationObject = _super.prototype.serialize.call(this);
  37077. serializationObject.size = this.size;
  37078. return serializationObject;
  37079. };
  37080. PlaneGeometry.Parse = function (parsedPlane, scene) {
  37081. if (scene.getGeometryByID(parsedPlane.id)) {
  37082. return null; // null since geometry could be something else than a ground...
  37083. }
  37084. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  37085. if (BABYLON.Tags) {
  37086. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  37087. }
  37088. scene.pushGeometry(plane, true);
  37089. return plane;
  37090. };
  37091. return PlaneGeometry;
  37092. }(_PrimitiveGeometry));
  37093. BABYLON.PlaneGeometry = PlaneGeometry;
  37094. /**
  37095. * Creates a torus knot geometry
  37096. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  37097. */
  37098. var TorusKnotGeometry = /** @class */ (function (_super) {
  37099. __extends(TorusKnotGeometry, _super);
  37100. /**
  37101. * Creates a torus knot geometry
  37102. * @param id defines the unique ID of the geometry
  37103. * @param scene defines the hosting scene
  37104. * @param radius defines the radius of the torus knot
  37105. * @param tube defines the thickness of the torus knot tube
  37106. * @param radialSegments defines the number of radial segments
  37107. * @param tubularSegments defines the number of tubular segments
  37108. * @param p defines the first number of windings
  37109. * @param q defines the second number of windings
  37110. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  37111. * @param mesh defines the hosting mesh (can be null)
  37112. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37113. */
  37114. function TorusKnotGeometry(id, scene,
  37115. /**
  37116. * Defines the radius of the torus knot
  37117. */
  37118. radius,
  37119. /**
  37120. * Defines the thickness of the torus knot tube
  37121. */
  37122. tube,
  37123. /**
  37124. * Defines the number of radial segments
  37125. */
  37126. radialSegments,
  37127. /**
  37128. * Defines the number of tubular segments
  37129. */
  37130. tubularSegments,
  37131. /**
  37132. * Defines the first number of windings
  37133. */
  37134. p,
  37135. /**
  37136. * Defines the second number of windings
  37137. */
  37138. q, canBeRegenerated, mesh,
  37139. /**
  37140. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37141. */
  37142. side) {
  37143. if (mesh === void 0) { mesh = null; }
  37144. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37145. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37146. _this.radius = radius;
  37147. _this.tube = tube;
  37148. _this.radialSegments = radialSegments;
  37149. _this.tubularSegments = tubularSegments;
  37150. _this.p = p;
  37151. _this.q = q;
  37152. _this.side = side;
  37153. return _this;
  37154. }
  37155. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  37156. 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 });
  37157. };
  37158. TorusKnotGeometry.prototype.copy = function (id) {
  37159. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  37160. };
  37161. TorusKnotGeometry.prototype.serialize = function () {
  37162. var serializationObject = _super.prototype.serialize.call(this);
  37163. serializationObject.radius = this.radius;
  37164. serializationObject.tube = this.tube;
  37165. serializationObject.radialSegments = this.radialSegments;
  37166. serializationObject.tubularSegments = this.tubularSegments;
  37167. serializationObject.p = this.p;
  37168. serializationObject.q = this.q;
  37169. return serializationObject;
  37170. };
  37171. ;
  37172. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  37173. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  37174. return null; // null since geometry could be something else than a ground...
  37175. }
  37176. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  37177. if (BABYLON.Tags) {
  37178. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  37179. }
  37180. scene.pushGeometry(torusKnot, true);
  37181. return torusKnot;
  37182. };
  37183. return TorusKnotGeometry;
  37184. }(_PrimitiveGeometry));
  37185. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  37186. //}
  37187. })(BABYLON || (BABYLON = {}));
  37188. //# sourceMappingURL=babylon.geometry.js.map
  37189. "use strict";
  37190. var BABYLON;
  37191. (function (BABYLON) {
  37192. /**
  37193. * PostProcessManager is used to manage one or more post processes or post process pipelines
  37194. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  37195. */
  37196. var PostProcessManager = /** @class */ (function () {
  37197. /**
  37198. * Creates a new instance PostProcess
  37199. * @param scene The scene that the post process is associated with.
  37200. */
  37201. function PostProcessManager(scene) {
  37202. this._vertexBuffers = {};
  37203. this._scene = scene;
  37204. }
  37205. PostProcessManager.prototype._prepareBuffers = function () {
  37206. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  37207. return;
  37208. }
  37209. // VBO
  37210. var vertices = [];
  37211. vertices.push(1, 1);
  37212. vertices.push(-1, 1);
  37213. vertices.push(-1, -1);
  37214. vertices.push(1, -1);
  37215. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  37216. this._buildIndexBuffer();
  37217. };
  37218. PostProcessManager.prototype._buildIndexBuffer = function () {
  37219. // Indices
  37220. var indices = [];
  37221. indices.push(0);
  37222. indices.push(1);
  37223. indices.push(2);
  37224. indices.push(0);
  37225. indices.push(2);
  37226. indices.push(3);
  37227. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  37228. };
  37229. /**
  37230. * Rebuilds the vertex buffers of the manager.
  37231. */
  37232. PostProcessManager.prototype._rebuild = function () {
  37233. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37234. if (!vb) {
  37235. return;
  37236. }
  37237. vb._rebuild();
  37238. this._buildIndexBuffer();
  37239. };
  37240. // Methods
  37241. /**
  37242. * Prepares a frame to be run through a post process.
  37243. * @param sourceTexture The input texture to the post procesess. (default: null)
  37244. * @param postProcesses An array of post processes to be run. (default: null)
  37245. * @returns True if the post processes were able to be run.
  37246. */
  37247. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  37248. if (sourceTexture === void 0) { sourceTexture = null; }
  37249. if (postProcesses === void 0) { postProcesses = null; }
  37250. var camera = this._scene.activeCamera;
  37251. if (!camera) {
  37252. return false;
  37253. }
  37254. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  37255. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  37256. return false;
  37257. }
  37258. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  37259. return true;
  37260. };
  37261. /**
  37262. * Manually render a set of post processes to a texture.
  37263. * @param postProcesses An array of post processes to be run.
  37264. * @param targetTexture The target texture to render to.
  37265. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  37266. */
  37267. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  37268. if (targetTexture === void 0) { targetTexture = null; }
  37269. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  37270. var engine = this._scene.getEngine();
  37271. for (var index = 0; index < postProcesses.length; index++) {
  37272. if (index < postProcesses.length - 1) {
  37273. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  37274. }
  37275. else {
  37276. if (targetTexture) {
  37277. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  37278. }
  37279. else {
  37280. engine.restoreDefaultFramebuffer();
  37281. }
  37282. }
  37283. var pp = postProcesses[index];
  37284. var effect = pp.apply();
  37285. if (effect) {
  37286. pp.onBeforeRenderObservable.notifyObservers(effect);
  37287. // VBOs
  37288. this._prepareBuffers();
  37289. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37290. // Draw order
  37291. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  37292. pp.onAfterRenderObservable.notifyObservers(effect);
  37293. }
  37294. }
  37295. // Restore depth buffer
  37296. engine.setDepthBuffer(true);
  37297. engine.setDepthWrite(true);
  37298. };
  37299. /**
  37300. * Finalize the result of the output of the postprocesses.
  37301. * @param doNotPresent If true the result will not be displayed to the screen.
  37302. * @param targetTexture The target texture to render to.
  37303. * @param faceIndex The index of the face to bind the target texture to.
  37304. * @param postProcesses The array of post processes to render.
  37305. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  37306. */
  37307. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  37308. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  37309. var camera = this._scene.activeCamera;
  37310. if (!camera) {
  37311. return;
  37312. }
  37313. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  37314. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  37315. return;
  37316. }
  37317. var engine = this._scene.getEngine();
  37318. for (var index = 0, len = postProcesses.length; index < len; index++) {
  37319. var pp = postProcesses[index];
  37320. if (index < len - 1) {
  37321. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  37322. }
  37323. else {
  37324. if (targetTexture) {
  37325. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  37326. }
  37327. else {
  37328. engine.restoreDefaultFramebuffer();
  37329. }
  37330. }
  37331. if (doNotPresent) {
  37332. break;
  37333. }
  37334. var effect = pp.apply();
  37335. if (effect) {
  37336. pp.onBeforeRenderObservable.notifyObservers(effect);
  37337. // VBOs
  37338. this._prepareBuffers();
  37339. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37340. // Draw order
  37341. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  37342. pp.onAfterRenderObservable.notifyObservers(effect);
  37343. }
  37344. }
  37345. // Restore states
  37346. engine.setDepthBuffer(true);
  37347. engine.setDepthWrite(true);
  37348. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  37349. };
  37350. /**
  37351. * Disposes of the post process manager.
  37352. */
  37353. PostProcessManager.prototype.dispose = function () {
  37354. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37355. if (buffer) {
  37356. buffer.dispose();
  37357. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  37358. }
  37359. if (this._indexBuffer) {
  37360. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  37361. this._indexBuffer = null;
  37362. }
  37363. };
  37364. return PostProcessManager;
  37365. }());
  37366. BABYLON.PostProcessManager = PostProcessManager;
  37367. })(BABYLON || (BABYLON = {}));
  37368. //# sourceMappingURL=babylon.postProcessManager.js.map
  37369. "use strict";
  37370. var BABYLON;
  37371. (function (BABYLON) {
  37372. /**
  37373. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  37374. */
  37375. var PerformanceMonitor = /** @class */ (function () {
  37376. /**
  37377. * constructor
  37378. * @param frameSampleSize The number of samples required to saturate the sliding window
  37379. */
  37380. function PerformanceMonitor(frameSampleSize) {
  37381. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  37382. this._enabled = true;
  37383. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  37384. }
  37385. /**
  37386. * Samples current frame
  37387. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  37388. */
  37389. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  37390. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  37391. if (!this._enabled)
  37392. return;
  37393. if (this._lastFrameTimeMs != null) {
  37394. var dt = timeMs - this._lastFrameTimeMs;
  37395. this._rollingFrameTime.add(dt);
  37396. }
  37397. this._lastFrameTimeMs = timeMs;
  37398. };
  37399. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  37400. /**
  37401. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  37402. * @return Average frame time in milliseconds
  37403. */
  37404. get: function () {
  37405. return this._rollingFrameTime.average;
  37406. },
  37407. enumerable: true,
  37408. configurable: true
  37409. });
  37410. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  37411. /**
  37412. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  37413. * @return Frame time variance in milliseconds squared
  37414. */
  37415. get: function () {
  37416. return this._rollingFrameTime.variance;
  37417. },
  37418. enumerable: true,
  37419. configurable: true
  37420. });
  37421. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  37422. /**
  37423. * Returns the frame time of the most recent frame
  37424. * @return Frame time in milliseconds
  37425. */
  37426. get: function () {
  37427. return this._rollingFrameTime.history(0);
  37428. },
  37429. enumerable: true,
  37430. configurable: true
  37431. });
  37432. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  37433. /**
  37434. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  37435. * @return Framerate in frames per second
  37436. */
  37437. get: function () {
  37438. return 1000.0 / this._rollingFrameTime.average;
  37439. },
  37440. enumerable: true,
  37441. configurable: true
  37442. });
  37443. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  37444. /**
  37445. * Returns the average framerate in frames per second using the most recent frame time
  37446. * @return Framerate in frames per second
  37447. */
  37448. get: function () {
  37449. var history = this._rollingFrameTime.history(0);
  37450. if (history === 0) {
  37451. return 0;
  37452. }
  37453. return 1000.0 / history;
  37454. },
  37455. enumerable: true,
  37456. configurable: true
  37457. });
  37458. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  37459. /**
  37460. * Returns true if enough samples have been taken to completely fill the sliding window
  37461. * @return true if saturated
  37462. */
  37463. get: function () {
  37464. return this._rollingFrameTime.isSaturated();
  37465. },
  37466. enumerable: true,
  37467. configurable: true
  37468. });
  37469. /**
  37470. * Enables contributions to the sliding window sample set
  37471. */
  37472. PerformanceMonitor.prototype.enable = function () {
  37473. this._enabled = true;
  37474. };
  37475. /**
  37476. * Disables contributions to the sliding window sample set
  37477. * Samples will not be interpolated over the disabled period
  37478. */
  37479. PerformanceMonitor.prototype.disable = function () {
  37480. this._enabled = false;
  37481. //clear last sample to avoid interpolating over the disabled period when next enabled
  37482. this._lastFrameTimeMs = null;
  37483. };
  37484. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  37485. /**
  37486. * Returns true if sampling is enabled
  37487. * @return true if enabled
  37488. */
  37489. get: function () {
  37490. return this._enabled;
  37491. },
  37492. enumerable: true,
  37493. configurable: true
  37494. });
  37495. /**
  37496. * Resets performance monitor
  37497. */
  37498. PerformanceMonitor.prototype.reset = function () {
  37499. //clear last sample to avoid interpolating over the disabled period when next enabled
  37500. this._lastFrameTimeMs = null;
  37501. //wipe record
  37502. this._rollingFrameTime.reset();
  37503. };
  37504. return PerformanceMonitor;
  37505. }());
  37506. BABYLON.PerformanceMonitor = PerformanceMonitor;
  37507. /**
  37508. * RollingAverage
  37509. *
  37510. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  37511. */
  37512. var RollingAverage = /** @class */ (function () {
  37513. /**
  37514. * constructor
  37515. * @param length The number of samples required to saturate the sliding window
  37516. */
  37517. function RollingAverage(length) {
  37518. this._samples = new Array(length);
  37519. this.reset();
  37520. }
  37521. /**
  37522. * Adds a sample to the sample set
  37523. * @param v The sample value
  37524. */
  37525. RollingAverage.prototype.add = function (v) {
  37526. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  37527. var delta;
  37528. //we need to check if we've already wrapped round
  37529. if (this.isSaturated()) {
  37530. //remove bottom of stack from mean
  37531. var bottomValue = this._samples[this._pos];
  37532. delta = bottomValue - this.average;
  37533. this.average -= delta / (this._sampleCount - 1);
  37534. this._m2 -= delta * (bottomValue - this.average);
  37535. }
  37536. else {
  37537. this._sampleCount++;
  37538. }
  37539. //add new value to mean
  37540. delta = v - this.average;
  37541. this.average += delta / (this._sampleCount);
  37542. this._m2 += delta * (v - this.average);
  37543. //set the new variance
  37544. this.variance = this._m2 / (this._sampleCount - 1);
  37545. this._samples[this._pos] = v;
  37546. this._pos++;
  37547. this._pos %= this._samples.length; //positive wrap around
  37548. };
  37549. /**
  37550. * Returns previously added values or null if outside of history or outside the sliding window domain
  37551. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  37552. * @return Value previously recorded with add() or null if outside of range
  37553. */
  37554. RollingAverage.prototype.history = function (i) {
  37555. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  37556. return 0;
  37557. }
  37558. var i0 = this._wrapPosition(this._pos - 1.0);
  37559. return this._samples[this._wrapPosition(i0 - i)];
  37560. };
  37561. /**
  37562. * Returns true if enough samples have been taken to completely fill the sliding window
  37563. * @return true if sample-set saturated
  37564. */
  37565. RollingAverage.prototype.isSaturated = function () {
  37566. return this._sampleCount >= this._samples.length;
  37567. };
  37568. /**
  37569. * Resets the rolling average (equivalent to 0 samples taken so far)
  37570. */
  37571. RollingAverage.prototype.reset = function () {
  37572. this.average = 0;
  37573. this.variance = 0;
  37574. this._sampleCount = 0;
  37575. this._pos = 0;
  37576. this._m2 = 0;
  37577. };
  37578. /**
  37579. * Wraps a value around the sample range boundaries
  37580. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  37581. * @return Wrapped position in sample range
  37582. */
  37583. RollingAverage.prototype._wrapPosition = function (i) {
  37584. var max = this._samples.length;
  37585. return ((i % max) + max) % max;
  37586. };
  37587. return RollingAverage;
  37588. }());
  37589. BABYLON.RollingAverage = RollingAverage;
  37590. })(BABYLON || (BABYLON = {}));
  37591. //# sourceMappingURL=babylon.performanceMonitor.js.map
  37592. "use strict";
  37593. var BABYLON;
  37594. (function (BABYLON) {
  37595. /**
  37596. * This groups together the common properties used for image processing either in direct forward pass
  37597. * or through post processing effect depending on the use of the image processing pipeline in your scene
  37598. * or not.
  37599. */
  37600. var ImageProcessingConfiguration = /** @class */ (function () {
  37601. function ImageProcessingConfiguration() {
  37602. /**
  37603. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  37604. */
  37605. this.colorCurves = new BABYLON.ColorCurves();
  37606. this._colorCurvesEnabled = false;
  37607. this._colorGradingEnabled = false;
  37608. this._colorGradingWithGreenDepth = true;
  37609. this._colorGradingBGR = true;
  37610. this._exposure = 1.0;
  37611. this._toneMappingEnabled = false;
  37612. this._contrast = 1.0;
  37613. /**
  37614. * Vignette stretch size.
  37615. */
  37616. this.vignetteStretch = 0;
  37617. /**
  37618. * Vignette centre X Offset.
  37619. */
  37620. this.vignetteCentreX = 0;
  37621. /**
  37622. * Vignette centre Y Offset.
  37623. */
  37624. this.vignetteCentreY = 0;
  37625. /**
  37626. * Vignette weight or intensity of the vignette effect.
  37627. */
  37628. this.vignetteWeight = 1.5;
  37629. /**
  37630. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  37631. * if vignetteEnabled is set to true.
  37632. */
  37633. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  37634. /**
  37635. * Camera field of view used by the Vignette effect.
  37636. */
  37637. this.vignetteCameraFov = 0.5;
  37638. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  37639. this._vignetteEnabled = false;
  37640. this._applyByPostProcess = false;
  37641. this._isEnabled = true;
  37642. /**
  37643. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  37644. */
  37645. this.onUpdateParameters = new BABYLON.Observable();
  37646. }
  37647. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  37648. /**
  37649. * Gets wether the color curves effect is enabled.
  37650. */
  37651. get: function () {
  37652. return this._colorCurvesEnabled;
  37653. },
  37654. /**
  37655. * Sets wether the color curves effect is enabled.
  37656. */
  37657. set: function (value) {
  37658. if (this._colorCurvesEnabled === value) {
  37659. return;
  37660. }
  37661. this._colorCurvesEnabled = value;
  37662. this._updateParameters();
  37663. },
  37664. enumerable: true,
  37665. configurable: true
  37666. });
  37667. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  37668. /**
  37669. * Gets wether the color grading effect is enabled.
  37670. */
  37671. get: function () {
  37672. return this._colorGradingEnabled;
  37673. },
  37674. /**
  37675. * Sets wether the color grading effect is enabled.
  37676. */
  37677. set: function (value) {
  37678. if (this._colorGradingEnabled === value) {
  37679. return;
  37680. }
  37681. this._colorGradingEnabled = value;
  37682. this._updateParameters();
  37683. },
  37684. enumerable: true,
  37685. configurable: true
  37686. });
  37687. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  37688. /**
  37689. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  37690. */
  37691. get: function () {
  37692. return this._colorGradingWithGreenDepth;
  37693. },
  37694. /**
  37695. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  37696. */
  37697. set: function (value) {
  37698. if (this._colorGradingWithGreenDepth === value) {
  37699. return;
  37700. }
  37701. this._colorGradingWithGreenDepth = value;
  37702. this._updateParameters();
  37703. },
  37704. enumerable: true,
  37705. configurable: true
  37706. });
  37707. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  37708. /**
  37709. * Gets wether the color grading texture contains BGR values.
  37710. */
  37711. get: function () {
  37712. return this._colorGradingBGR;
  37713. },
  37714. /**
  37715. * Sets wether the color grading texture contains BGR values.
  37716. */
  37717. set: function (value) {
  37718. if (this._colorGradingBGR === value) {
  37719. return;
  37720. }
  37721. this._colorGradingBGR = value;
  37722. this._updateParameters();
  37723. },
  37724. enumerable: true,
  37725. configurable: true
  37726. });
  37727. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  37728. /**
  37729. * Gets the Exposure used in the effect.
  37730. */
  37731. get: function () {
  37732. return this._exposure;
  37733. },
  37734. /**
  37735. * Sets the Exposure used in the effect.
  37736. */
  37737. set: function (value) {
  37738. if (this._exposure === value) {
  37739. return;
  37740. }
  37741. this._exposure = value;
  37742. this._updateParameters();
  37743. },
  37744. enumerable: true,
  37745. configurable: true
  37746. });
  37747. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  37748. /**
  37749. * Gets wether the tone mapping effect is enabled.
  37750. */
  37751. get: function () {
  37752. return this._toneMappingEnabled;
  37753. },
  37754. /**
  37755. * Sets wether the tone mapping effect is enabled.
  37756. */
  37757. set: function (value) {
  37758. if (this._toneMappingEnabled === value) {
  37759. return;
  37760. }
  37761. this._toneMappingEnabled = value;
  37762. this._updateParameters();
  37763. },
  37764. enumerable: true,
  37765. configurable: true
  37766. });
  37767. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  37768. /**
  37769. * Gets the contrast used in the effect.
  37770. */
  37771. get: function () {
  37772. return this._contrast;
  37773. },
  37774. /**
  37775. * Sets the contrast used in the effect.
  37776. */
  37777. set: function (value) {
  37778. if (this._contrast === value) {
  37779. return;
  37780. }
  37781. this._contrast = value;
  37782. this._updateParameters();
  37783. },
  37784. enumerable: true,
  37785. configurable: true
  37786. });
  37787. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  37788. /**
  37789. * Gets the vignette blend mode allowing different kind of effect.
  37790. */
  37791. get: function () {
  37792. return this._vignetteBlendMode;
  37793. },
  37794. /**
  37795. * Sets the vignette blend mode allowing different kind of effect.
  37796. */
  37797. set: function (value) {
  37798. if (this._vignetteBlendMode === value) {
  37799. return;
  37800. }
  37801. this._vignetteBlendMode = value;
  37802. this._updateParameters();
  37803. },
  37804. enumerable: true,
  37805. configurable: true
  37806. });
  37807. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  37808. /**
  37809. * Gets wether the vignette effect is enabled.
  37810. */
  37811. get: function () {
  37812. return this._vignetteEnabled;
  37813. },
  37814. /**
  37815. * Sets wether the vignette effect is enabled.
  37816. */
  37817. set: function (value) {
  37818. if (this._vignetteEnabled === value) {
  37819. return;
  37820. }
  37821. this._vignetteEnabled = value;
  37822. this._updateParameters();
  37823. },
  37824. enumerable: true,
  37825. configurable: true
  37826. });
  37827. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  37828. /**
  37829. * Gets wether the image processing is applied through a post process or not.
  37830. */
  37831. get: function () {
  37832. return this._applyByPostProcess;
  37833. },
  37834. /**
  37835. * Sets wether the image processing is applied through a post process or not.
  37836. */
  37837. set: function (value) {
  37838. if (this._applyByPostProcess === value) {
  37839. return;
  37840. }
  37841. this._applyByPostProcess = value;
  37842. this._updateParameters();
  37843. },
  37844. enumerable: true,
  37845. configurable: true
  37846. });
  37847. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  37848. /**
  37849. * Gets wether the image processing is enabled or not.
  37850. */
  37851. get: function () {
  37852. return this._isEnabled;
  37853. },
  37854. /**
  37855. * Sets wether the image processing is enabled or not.
  37856. */
  37857. set: function (value) {
  37858. if (this._isEnabled === value) {
  37859. return;
  37860. }
  37861. this._isEnabled = value;
  37862. this._updateParameters();
  37863. },
  37864. enumerable: true,
  37865. configurable: true
  37866. });
  37867. /**
  37868. * Method called each time the image processing information changes requires to recompile the effect.
  37869. */
  37870. ImageProcessingConfiguration.prototype._updateParameters = function () {
  37871. this.onUpdateParameters.notifyObservers(this);
  37872. };
  37873. ImageProcessingConfiguration.prototype.getClassName = function () {
  37874. return "ImageProcessingConfiguration";
  37875. };
  37876. /**
  37877. * Prepare the list of uniforms associated with the Image Processing effects.
  37878. * @param uniformsList The list of uniforms used in the effect
  37879. * @param defines the list of defines currently in use
  37880. */
  37881. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  37882. if (defines.EXPOSURE) {
  37883. uniforms.push("exposureLinear");
  37884. }
  37885. if (defines.CONTRAST) {
  37886. uniforms.push("contrast");
  37887. }
  37888. if (defines.COLORGRADING) {
  37889. uniforms.push("colorTransformSettings");
  37890. }
  37891. if (defines.VIGNETTE) {
  37892. uniforms.push("vInverseScreenSize");
  37893. uniforms.push("vignetteSettings1");
  37894. uniforms.push("vignetteSettings2");
  37895. }
  37896. if (defines.COLORCURVES) {
  37897. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  37898. }
  37899. };
  37900. /**
  37901. * Prepare the list of samplers associated with the Image Processing effects.
  37902. * @param uniformsList The list of uniforms used in the effect
  37903. * @param defines the list of defines currently in use
  37904. */
  37905. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  37906. if (defines.COLORGRADING) {
  37907. samplersList.push("txColorTransform");
  37908. }
  37909. };
  37910. /**
  37911. * Prepare the list of defines associated to the shader.
  37912. * @param defines the list of defines to complete
  37913. */
  37914. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  37915. if (forPostProcess === void 0) { forPostProcess = false; }
  37916. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  37917. defines.VIGNETTE = false;
  37918. defines.TONEMAPPING = false;
  37919. defines.CONTRAST = false;
  37920. defines.EXPOSURE = false;
  37921. defines.COLORCURVES = false;
  37922. defines.COLORGRADING = false;
  37923. defines.COLORGRADING3D = false;
  37924. defines.IMAGEPROCESSING = false;
  37925. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  37926. return;
  37927. }
  37928. defines.VIGNETTE = this.vignetteEnabled;
  37929. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  37930. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  37931. defines.TONEMAPPING = this.toneMappingEnabled;
  37932. defines.CONTRAST = (this.contrast !== 1.0);
  37933. defines.EXPOSURE = (this.exposure !== 1.0);
  37934. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  37935. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  37936. if (defines.COLORGRADING) {
  37937. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  37938. }
  37939. else {
  37940. defines.COLORGRADING3D = false;
  37941. }
  37942. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  37943. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  37944. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  37945. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  37946. };
  37947. /**
  37948. * Returns true if all the image processing information are ready.
  37949. */
  37950. ImageProcessingConfiguration.prototype.isReady = function () {
  37951. // Color Grading texure can not be none blocking.
  37952. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  37953. };
  37954. /**
  37955. * Binds the image processing to the shader.
  37956. * @param effect The effect to bind to
  37957. */
  37958. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  37959. if (aspectRatio === void 0) { aspectRatio = 1; }
  37960. // Color Curves
  37961. if (this._colorCurvesEnabled && this.colorCurves) {
  37962. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  37963. }
  37964. // Vignette
  37965. if (this._vignetteEnabled) {
  37966. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  37967. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  37968. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  37969. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  37970. var vignetteScaleX = vignetteScaleY * aspectRatio;
  37971. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  37972. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  37973. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  37974. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  37975. var vignettePower = -2.0 * this.vignetteWeight;
  37976. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  37977. }
  37978. // Exposure
  37979. effect.setFloat("exposureLinear", this.exposure);
  37980. // Contrast
  37981. effect.setFloat("contrast", this.contrast);
  37982. // Color transform settings
  37983. if (this.colorGradingTexture) {
  37984. effect.setTexture("txColorTransform", this.colorGradingTexture);
  37985. var textureSize = this.colorGradingTexture.getSize().height;
  37986. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  37987. 0.5 / textureSize, // textureOffset
  37988. textureSize, // textureSize
  37989. this.colorGradingTexture.level // weight
  37990. );
  37991. }
  37992. };
  37993. /**
  37994. * Clones the current image processing instance.
  37995. * @return The cloned image processing
  37996. */
  37997. ImageProcessingConfiguration.prototype.clone = function () {
  37998. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  37999. };
  38000. /**
  38001. * Serializes the current image processing instance to a json representation.
  38002. * @return a JSON representation
  38003. */
  38004. ImageProcessingConfiguration.prototype.serialize = function () {
  38005. return BABYLON.SerializationHelper.Serialize(this);
  38006. };
  38007. /**
  38008. * Parses the image processing from a json representation.
  38009. * @param source the JSON source to parse
  38010. * @return The parsed image processing
  38011. */
  38012. ImageProcessingConfiguration.Parse = function (source) {
  38013. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  38014. };
  38015. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  38016. /**
  38017. * Used to apply the vignette as a mix with the pixel color.
  38018. */
  38019. get: function () {
  38020. return this._VIGNETTEMODE_MULTIPLY;
  38021. },
  38022. enumerable: true,
  38023. configurable: true
  38024. });
  38025. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  38026. /**
  38027. * Used to apply the vignette as a replacement of the pixel color.
  38028. */
  38029. get: function () {
  38030. return this._VIGNETTEMODE_OPAQUE;
  38031. },
  38032. enumerable: true,
  38033. configurable: true
  38034. });
  38035. // Static constants associated to the image processing.
  38036. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  38037. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  38038. __decorate([
  38039. BABYLON.serializeAsColorCurves()
  38040. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  38041. __decorate([
  38042. BABYLON.serialize()
  38043. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  38044. __decorate([
  38045. BABYLON.serializeAsTexture()
  38046. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  38047. __decorate([
  38048. BABYLON.serialize()
  38049. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  38050. __decorate([
  38051. BABYLON.serialize()
  38052. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  38053. __decorate([
  38054. BABYLON.serialize()
  38055. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  38056. __decorate([
  38057. BABYLON.serialize()
  38058. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  38059. __decorate([
  38060. BABYLON.serialize()
  38061. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  38062. __decorate([
  38063. BABYLON.serialize()
  38064. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  38065. __decorate([
  38066. BABYLON.serialize()
  38067. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  38068. __decorate([
  38069. BABYLON.serialize()
  38070. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  38071. __decorate([
  38072. BABYLON.serialize()
  38073. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  38074. __decorate([
  38075. BABYLON.serialize()
  38076. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  38077. __decorate([
  38078. BABYLON.serializeAsColor4()
  38079. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  38080. __decorate([
  38081. BABYLON.serialize()
  38082. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  38083. __decorate([
  38084. BABYLON.serialize()
  38085. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  38086. __decorate([
  38087. BABYLON.serialize()
  38088. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  38089. __decorate([
  38090. BABYLON.serialize()
  38091. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  38092. __decorate([
  38093. BABYLON.serialize()
  38094. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  38095. return ImageProcessingConfiguration;
  38096. }());
  38097. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  38098. })(BABYLON || (BABYLON = {}));
  38099. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  38100. "use strict";
  38101. var BABYLON;
  38102. (function (BABYLON) {
  38103. /**
  38104. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  38105. * It can help converting any input color in a desired output one. This can then be used to create effects
  38106. * from sepia, black and white to sixties or futuristic rendering...
  38107. *
  38108. * The only supported format is currently 3dl.
  38109. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  38110. */
  38111. var ColorGradingTexture = /** @class */ (function (_super) {
  38112. __extends(ColorGradingTexture, _super);
  38113. /**
  38114. * Instantiates a ColorGradingTexture from the following parameters.
  38115. *
  38116. * @param url The location of the color gradind data (currently only supporting 3dl)
  38117. * @param scene The scene the texture will be used in
  38118. */
  38119. function ColorGradingTexture(url, scene) {
  38120. var _this = _super.call(this, scene) || this;
  38121. if (!url) {
  38122. return _this;
  38123. }
  38124. _this._engine = scene.getEngine();
  38125. _this._textureMatrix = BABYLON.Matrix.Identity();
  38126. _this.name = url;
  38127. _this.url = url;
  38128. _this.hasAlpha = false;
  38129. _this.isCube = false;
  38130. _this.is3D = _this._engine.webGLVersion > 1;
  38131. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38132. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38133. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38134. _this.anisotropicFilteringLevel = 1;
  38135. _this._texture = _this._getFromCache(url, true);
  38136. if (!_this._texture) {
  38137. if (!scene.useDelayedTextureLoading) {
  38138. _this.loadTexture();
  38139. }
  38140. else {
  38141. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  38142. }
  38143. }
  38144. return _this;
  38145. }
  38146. /**
  38147. * Returns the texture matrix used in most of the material.
  38148. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  38149. */
  38150. ColorGradingTexture.prototype.getTextureMatrix = function () {
  38151. return this._textureMatrix;
  38152. };
  38153. /**
  38154. * Occurs when the file being loaded is a .3dl LUT file.
  38155. */
  38156. ColorGradingTexture.prototype.load3dlTexture = function () {
  38157. var engine = this._engine;
  38158. var texture;
  38159. if (engine.webGLVersion === 1) {
  38160. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38161. }
  38162. else {
  38163. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38164. }
  38165. this._texture = texture;
  38166. var callback = function (text) {
  38167. if (typeof text !== "string") {
  38168. return;
  38169. }
  38170. var data = null;
  38171. var tempData = null;
  38172. var line;
  38173. var lines = text.split('\n');
  38174. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  38175. var maxColor = 0;
  38176. for (var i = 0; i < lines.length; i++) {
  38177. line = lines[i];
  38178. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  38179. continue;
  38180. if (line.indexOf('#') === 0)
  38181. continue;
  38182. var words = line.split(" ");
  38183. if (size === 0) {
  38184. // Number of space + one
  38185. size = words.length;
  38186. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  38187. tempData = new Float32Array(size * size * size * 4);
  38188. continue;
  38189. }
  38190. if (size != 0) {
  38191. var r = Math.max(parseInt(words[0]), 0);
  38192. var g = Math.max(parseInt(words[1]), 0);
  38193. var b = Math.max(parseInt(words[2]), 0);
  38194. maxColor = Math.max(r, maxColor);
  38195. maxColor = Math.max(g, maxColor);
  38196. maxColor = Math.max(b, maxColor);
  38197. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  38198. if (tempData) {
  38199. tempData[pixelStorageIndex + 0] = r;
  38200. tempData[pixelStorageIndex + 1] = g;
  38201. tempData[pixelStorageIndex + 2] = b;
  38202. }
  38203. pixelIndexSlice++;
  38204. if (pixelIndexSlice % size == 0) {
  38205. pixelIndexH++;
  38206. pixelIndexSlice = 0;
  38207. if (pixelIndexH % size == 0) {
  38208. pixelIndexW++;
  38209. pixelIndexH = 0;
  38210. }
  38211. }
  38212. }
  38213. }
  38214. if (tempData && data) {
  38215. for (var i = 0; i < tempData.length; i++) {
  38216. if (i > 0 && (i + 1) % 4 === 0) {
  38217. data[i] = 255;
  38218. }
  38219. else {
  38220. var value = tempData[i];
  38221. data[i] = (value / maxColor * 255);
  38222. }
  38223. }
  38224. }
  38225. if (texture.is3D) {
  38226. texture.updateSize(size, size, size);
  38227. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  38228. }
  38229. else {
  38230. texture.updateSize(size * size, size);
  38231. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  38232. }
  38233. };
  38234. var scene = this.getScene();
  38235. if (scene) {
  38236. scene._loadFile(this.url, callback);
  38237. }
  38238. else {
  38239. this._engine._loadFile(this.url, callback);
  38240. }
  38241. return this._texture;
  38242. };
  38243. /**
  38244. * Starts the loading process of the texture.
  38245. */
  38246. ColorGradingTexture.prototype.loadTexture = function () {
  38247. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  38248. this.load3dlTexture();
  38249. }
  38250. };
  38251. /**
  38252. * Clones the color gradind texture.
  38253. */
  38254. ColorGradingTexture.prototype.clone = function () {
  38255. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  38256. // Base texture
  38257. newTexture.level = this.level;
  38258. return newTexture;
  38259. };
  38260. /**
  38261. * Called during delayed load for textures.
  38262. */
  38263. ColorGradingTexture.prototype.delayLoad = function () {
  38264. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  38265. return;
  38266. }
  38267. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  38268. this._texture = this._getFromCache(this.url, true);
  38269. if (!this._texture) {
  38270. this.loadTexture();
  38271. }
  38272. };
  38273. /**
  38274. * Parses a color grading texture serialized by Babylon.
  38275. * @param parsedTexture The texture information being parsedTexture
  38276. * @param scene The scene to load the texture in
  38277. * @param rootUrl The root url of the data assets to load
  38278. * @return A color gradind texture
  38279. */
  38280. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  38281. var texture = null;
  38282. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  38283. texture = new ColorGradingTexture(parsedTexture.name, scene);
  38284. texture.name = parsedTexture.name;
  38285. texture.level = parsedTexture.level;
  38286. }
  38287. return texture;
  38288. };
  38289. /**
  38290. * Serializes the LUT texture to json format.
  38291. */
  38292. ColorGradingTexture.prototype.serialize = function () {
  38293. if (!this.name) {
  38294. return null;
  38295. }
  38296. var serializationObject = {};
  38297. serializationObject.name = this.name;
  38298. serializationObject.level = this.level;
  38299. serializationObject.customType = "BABYLON.ColorGradingTexture";
  38300. return serializationObject;
  38301. };
  38302. /**
  38303. * Empty line regex stored for GC.
  38304. */
  38305. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  38306. return ColorGradingTexture;
  38307. }(BABYLON.BaseTexture));
  38308. BABYLON.ColorGradingTexture = ColorGradingTexture;
  38309. })(BABYLON || (BABYLON = {}));
  38310. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  38311. "use strict";
  38312. var BABYLON;
  38313. (function (BABYLON) {
  38314. /**
  38315. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38316. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38317. * 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;
  38318. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38319. */
  38320. var ColorCurves = /** @class */ (function () {
  38321. function ColorCurves() {
  38322. this._dirty = true;
  38323. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  38324. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  38325. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  38326. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  38327. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  38328. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  38329. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  38330. this._globalHue = 30;
  38331. this._globalDensity = 0;
  38332. this._globalSaturation = 0;
  38333. this._globalExposure = 0;
  38334. this._highlightsHue = 30;
  38335. this._highlightsDensity = 0;
  38336. this._highlightsSaturation = 0;
  38337. this._highlightsExposure = 0;
  38338. this._midtonesHue = 30;
  38339. this._midtonesDensity = 0;
  38340. this._midtonesSaturation = 0;
  38341. this._midtonesExposure = 0;
  38342. this._shadowsHue = 30;
  38343. this._shadowsDensity = 0;
  38344. this._shadowsSaturation = 0;
  38345. this._shadowsExposure = 0;
  38346. }
  38347. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  38348. /**
  38349. * Gets the global Hue value.
  38350. * 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).
  38351. */
  38352. get: function () {
  38353. return this._globalHue;
  38354. },
  38355. /**
  38356. * Sets the global Hue value.
  38357. * 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).
  38358. */
  38359. set: function (value) {
  38360. this._globalHue = value;
  38361. this._dirty = true;
  38362. },
  38363. enumerable: true,
  38364. configurable: true
  38365. });
  38366. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  38367. /**
  38368. * Gets the global Density value.
  38369. * 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.
  38370. * Values less than zero provide a filter of opposite hue.
  38371. */
  38372. get: function () {
  38373. return this._globalDensity;
  38374. },
  38375. /**
  38376. * Sets the global Density value.
  38377. * 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.
  38378. * Values less than zero provide a filter of opposite hue.
  38379. */
  38380. set: function (value) {
  38381. this._globalDensity = value;
  38382. this._dirty = true;
  38383. },
  38384. enumerable: true,
  38385. configurable: true
  38386. });
  38387. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  38388. /**
  38389. * Gets the global Saturation value.
  38390. * 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.
  38391. */
  38392. get: function () {
  38393. return this._globalSaturation;
  38394. },
  38395. /**
  38396. * Sets the global Saturation value.
  38397. * 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.
  38398. */
  38399. set: function (value) {
  38400. this._globalSaturation = value;
  38401. this._dirty = true;
  38402. },
  38403. enumerable: true,
  38404. configurable: true
  38405. });
  38406. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  38407. /**
  38408. * Gets the highlights Hue value.
  38409. * 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).
  38410. */
  38411. get: function () {
  38412. return this._highlightsHue;
  38413. },
  38414. /**
  38415. * Sets the highlights Hue value.
  38416. * 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).
  38417. */
  38418. set: function (value) {
  38419. this._highlightsHue = value;
  38420. this._dirty = true;
  38421. },
  38422. enumerable: true,
  38423. configurable: true
  38424. });
  38425. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  38426. /**
  38427. * Gets the highlights Density value.
  38428. * 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.
  38429. * Values less than zero provide a filter of opposite hue.
  38430. */
  38431. get: function () {
  38432. return this._highlightsDensity;
  38433. },
  38434. /**
  38435. * Sets the highlights Density value.
  38436. * 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.
  38437. * Values less than zero provide a filter of opposite hue.
  38438. */
  38439. set: function (value) {
  38440. this._highlightsDensity = value;
  38441. this._dirty = true;
  38442. },
  38443. enumerable: true,
  38444. configurable: true
  38445. });
  38446. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  38447. /**
  38448. * Gets the highlights Saturation value.
  38449. * 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.
  38450. */
  38451. get: function () {
  38452. return this._highlightsSaturation;
  38453. },
  38454. /**
  38455. * Sets the highlights Saturation value.
  38456. * 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.
  38457. */
  38458. set: function (value) {
  38459. this._highlightsSaturation = value;
  38460. this._dirty = true;
  38461. },
  38462. enumerable: true,
  38463. configurable: true
  38464. });
  38465. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  38466. /**
  38467. * Gets the highlights Exposure value.
  38468. * 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.
  38469. */
  38470. get: function () {
  38471. return this._highlightsExposure;
  38472. },
  38473. /**
  38474. * Sets the highlights Exposure value.
  38475. * 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.
  38476. */
  38477. set: function (value) {
  38478. this._highlightsExposure = value;
  38479. this._dirty = true;
  38480. },
  38481. enumerable: true,
  38482. configurable: true
  38483. });
  38484. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  38485. /**
  38486. * Gets the midtones Hue value.
  38487. * 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).
  38488. */
  38489. get: function () {
  38490. return this._midtonesHue;
  38491. },
  38492. /**
  38493. * Sets the midtones Hue value.
  38494. * 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).
  38495. */
  38496. set: function (value) {
  38497. this._midtonesHue = value;
  38498. this._dirty = true;
  38499. },
  38500. enumerable: true,
  38501. configurable: true
  38502. });
  38503. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  38504. /**
  38505. * Gets the midtones Density value.
  38506. * 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.
  38507. * Values less than zero provide a filter of opposite hue.
  38508. */
  38509. get: function () {
  38510. return this._midtonesDensity;
  38511. },
  38512. /**
  38513. * Sets the midtones Density value.
  38514. * 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.
  38515. * Values less than zero provide a filter of opposite hue.
  38516. */
  38517. set: function (value) {
  38518. this._midtonesDensity = value;
  38519. this._dirty = true;
  38520. },
  38521. enumerable: true,
  38522. configurable: true
  38523. });
  38524. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  38525. /**
  38526. * Gets the midtones Saturation value.
  38527. * 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.
  38528. */
  38529. get: function () {
  38530. return this._midtonesSaturation;
  38531. },
  38532. /**
  38533. * Sets the midtones Saturation value.
  38534. * 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.
  38535. */
  38536. set: function (value) {
  38537. this._midtonesSaturation = value;
  38538. this._dirty = true;
  38539. },
  38540. enumerable: true,
  38541. configurable: true
  38542. });
  38543. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  38544. /**
  38545. * Gets the midtones Exposure value.
  38546. * 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.
  38547. */
  38548. get: function () {
  38549. return this._midtonesExposure;
  38550. },
  38551. /**
  38552. * Sets the midtones Exposure value.
  38553. * 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.
  38554. */
  38555. set: function (value) {
  38556. this._midtonesExposure = value;
  38557. this._dirty = true;
  38558. },
  38559. enumerable: true,
  38560. configurable: true
  38561. });
  38562. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  38563. /**
  38564. * Gets the shadows Hue value.
  38565. * 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).
  38566. */
  38567. get: function () {
  38568. return this._shadowsHue;
  38569. },
  38570. /**
  38571. * Sets the shadows Hue value.
  38572. * 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).
  38573. */
  38574. set: function (value) {
  38575. this._shadowsHue = value;
  38576. this._dirty = true;
  38577. },
  38578. enumerable: true,
  38579. configurable: true
  38580. });
  38581. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  38582. /**
  38583. * Gets the shadows Density value.
  38584. * 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.
  38585. * Values less than zero provide a filter of opposite hue.
  38586. */
  38587. get: function () {
  38588. return this._shadowsDensity;
  38589. },
  38590. /**
  38591. * Sets the shadows Density value.
  38592. * 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.
  38593. * Values less than zero provide a filter of opposite hue.
  38594. */
  38595. set: function (value) {
  38596. this._shadowsDensity = value;
  38597. this._dirty = true;
  38598. },
  38599. enumerable: true,
  38600. configurable: true
  38601. });
  38602. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  38603. /**
  38604. * Gets the shadows Saturation value.
  38605. * 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.
  38606. */
  38607. get: function () {
  38608. return this._shadowsSaturation;
  38609. },
  38610. /**
  38611. * Sets the shadows Saturation value.
  38612. * 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.
  38613. */
  38614. set: function (value) {
  38615. this._shadowsSaturation = value;
  38616. this._dirty = true;
  38617. },
  38618. enumerable: true,
  38619. configurable: true
  38620. });
  38621. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  38622. /**
  38623. * Gets the shadows Exposure value.
  38624. * 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.
  38625. */
  38626. get: function () {
  38627. return this._shadowsExposure;
  38628. },
  38629. /**
  38630. * Sets the shadows Exposure value.
  38631. * 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.
  38632. */
  38633. set: function (value) {
  38634. this._shadowsExposure = value;
  38635. this._dirty = true;
  38636. },
  38637. enumerable: true,
  38638. configurable: true
  38639. });
  38640. ColorCurves.prototype.getClassName = function () {
  38641. return "ColorCurves";
  38642. };
  38643. /**
  38644. * Binds the color curves to the shader.
  38645. * @param colorCurves The color curve to bind
  38646. * @param effect The effect to bind to
  38647. */
  38648. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  38649. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  38650. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  38651. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  38652. if (colorCurves._dirty) {
  38653. colorCurves._dirty = false;
  38654. // Fill in global info.
  38655. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  38656. // Compute highlights info.
  38657. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  38658. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  38659. // Compute midtones info.
  38660. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  38661. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  38662. // Compute shadows info.
  38663. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  38664. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  38665. // Compute deltas (neutral is midtones).
  38666. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  38667. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  38668. }
  38669. if (effect) {
  38670. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  38671. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  38672. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  38673. }
  38674. };
  38675. /**
  38676. * Prepare the list of uniforms associated with the ColorCurves effects.
  38677. * @param uniformsList The list of uniforms used in the effect
  38678. */
  38679. ColorCurves.PrepareUniforms = function (uniformsList) {
  38680. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  38681. };
  38682. /**
  38683. * Returns color grading data based on a hue, density, saturation and exposure value.
  38684. * @param filterHue The hue of the color filter.
  38685. * @param filterDensity The density of the color filter.
  38686. * @param saturation The saturation.
  38687. * @param exposure The exposure.
  38688. * @param result The result data container.
  38689. */
  38690. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  38691. if (hue == null) {
  38692. return;
  38693. }
  38694. hue = ColorCurves.clamp(hue, 0, 360);
  38695. density = ColorCurves.clamp(density, -100, 100);
  38696. saturation = ColorCurves.clamp(saturation, -100, 100);
  38697. exposure = ColorCurves.clamp(exposure, -100, 100);
  38698. // Remap the slider/config filter density with non-linear mapping and also scale by half
  38699. // so that the maximum filter density is only 50% control. This provides fine control
  38700. // for small values and reasonable range.
  38701. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  38702. density *= 0.5;
  38703. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  38704. if (density < 0) {
  38705. density *= -1;
  38706. hue = (hue + 180) % 360;
  38707. }
  38708. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  38709. result.scaleToRef(2, result);
  38710. result.a = 1 + 0.01 * saturation;
  38711. };
  38712. /**
  38713. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  38714. * @param value The input slider value in range [-100,100].
  38715. * @returns Adjusted value.
  38716. */
  38717. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  38718. value /= 100;
  38719. var x = Math.abs(value);
  38720. x = Math.pow(x, 2);
  38721. if (value < 0) {
  38722. x *= -1;
  38723. }
  38724. x *= 100;
  38725. return x;
  38726. };
  38727. /**
  38728. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  38729. * @param hue The hue (H) input.
  38730. * @param saturation The saturation (S) input.
  38731. * @param brightness The brightness (B) input.
  38732. * @result An RGBA color represented as Vector4.
  38733. */
  38734. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  38735. var h = ColorCurves.clamp(hue, 0, 360);
  38736. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  38737. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  38738. if (s === 0) {
  38739. result.r = v;
  38740. result.g = v;
  38741. result.b = v;
  38742. }
  38743. else {
  38744. // sector 0 to 5
  38745. h /= 60;
  38746. var i = Math.floor(h);
  38747. // fractional part of h
  38748. var f = h - i;
  38749. var p = v * (1 - s);
  38750. var q = v * (1 - s * f);
  38751. var t = v * (1 - s * (1 - f));
  38752. switch (i) {
  38753. case 0:
  38754. result.r = v;
  38755. result.g = t;
  38756. result.b = p;
  38757. break;
  38758. case 1:
  38759. result.r = q;
  38760. result.g = v;
  38761. result.b = p;
  38762. break;
  38763. case 2:
  38764. result.r = p;
  38765. result.g = v;
  38766. result.b = t;
  38767. break;
  38768. case 3:
  38769. result.r = p;
  38770. result.g = q;
  38771. result.b = v;
  38772. break;
  38773. case 4:
  38774. result.r = t;
  38775. result.g = p;
  38776. result.b = v;
  38777. break;
  38778. default:// case 5:
  38779. result.r = v;
  38780. result.g = p;
  38781. result.b = q;
  38782. break;
  38783. }
  38784. }
  38785. result.a = 1;
  38786. };
  38787. /**
  38788. * Returns a value clamped between min and max
  38789. * @param value The value to clamp
  38790. * @param min The minimum of value
  38791. * @param max The maximum of value
  38792. * @returns The clamped value.
  38793. */
  38794. ColorCurves.clamp = function (value, min, max) {
  38795. return Math.min(Math.max(value, min), max);
  38796. };
  38797. /**
  38798. * Clones the current color curve instance.
  38799. * @return The cloned curves
  38800. */
  38801. ColorCurves.prototype.clone = function () {
  38802. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  38803. };
  38804. /**
  38805. * Serializes the current color curve instance to a json representation.
  38806. * @return a JSON representation
  38807. */
  38808. ColorCurves.prototype.serialize = function () {
  38809. return BABYLON.SerializationHelper.Serialize(this);
  38810. };
  38811. /**
  38812. * Parses the color curve from a json representation.
  38813. * @param source the JSON source to parse
  38814. * @return The parsed curves
  38815. */
  38816. ColorCurves.Parse = function (source) {
  38817. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  38818. };
  38819. __decorate([
  38820. BABYLON.serialize()
  38821. ], ColorCurves.prototype, "_globalHue", void 0);
  38822. __decorate([
  38823. BABYLON.serialize()
  38824. ], ColorCurves.prototype, "_globalDensity", void 0);
  38825. __decorate([
  38826. BABYLON.serialize()
  38827. ], ColorCurves.prototype, "_globalSaturation", void 0);
  38828. __decorate([
  38829. BABYLON.serialize()
  38830. ], ColorCurves.prototype, "_globalExposure", void 0);
  38831. __decorate([
  38832. BABYLON.serialize()
  38833. ], ColorCurves.prototype, "_highlightsHue", void 0);
  38834. __decorate([
  38835. BABYLON.serialize()
  38836. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  38837. __decorate([
  38838. BABYLON.serialize()
  38839. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  38840. __decorate([
  38841. BABYLON.serialize()
  38842. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  38843. __decorate([
  38844. BABYLON.serialize()
  38845. ], ColorCurves.prototype, "_midtonesHue", void 0);
  38846. __decorate([
  38847. BABYLON.serialize()
  38848. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  38849. __decorate([
  38850. BABYLON.serialize()
  38851. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  38852. __decorate([
  38853. BABYLON.serialize()
  38854. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  38855. return ColorCurves;
  38856. }());
  38857. BABYLON.ColorCurves = ColorCurves;
  38858. })(BABYLON || (BABYLON = {}));
  38859. //# sourceMappingURL=babylon.colorCurves.js.map
  38860. "use strict";
  38861. //# sourceMappingURL=babylon.behavior.js.map
  38862. "use strict";
  38863. var BABYLON;
  38864. (function (BABYLON) {
  38865. /**
  38866. * "Static Class" containing the most commonly used helper while dealing with material for
  38867. * rendering purpose.
  38868. *
  38869. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  38870. *
  38871. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  38872. */
  38873. var MaterialHelper = /** @class */ (function () {
  38874. function MaterialHelper() {
  38875. }
  38876. /**
  38877. * Bind the current view position to an effect.
  38878. * @param effect The effect to be bound
  38879. * @param scene The scene the eyes position is used from
  38880. */
  38881. MaterialHelper.BindEyePosition = function (effect, scene) {
  38882. if (scene._forcedViewPosition) {
  38883. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  38884. return;
  38885. }
  38886. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38887. };
  38888. /**
  38889. * Helps preparing the defines values about the UVs in used in the effect.
  38890. * UVs are shared as much as we can accross chanels in the shaders.
  38891. * @param texture The texture we are preparing the UVs for
  38892. * @param defines The defines to update
  38893. * @param key The chanel key "diffuse", "specular"... used in the shader
  38894. */
  38895. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  38896. defines._needUVs = true;
  38897. defines[key] = true;
  38898. if (texture.getTextureMatrix().isIdentity(true)) {
  38899. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  38900. if (texture.coordinatesIndex === 0) {
  38901. defines["MAINUV1"] = true;
  38902. }
  38903. else {
  38904. defines["MAINUV2"] = true;
  38905. }
  38906. }
  38907. else {
  38908. defines[key + "DIRECTUV"] = 0;
  38909. }
  38910. };
  38911. /**
  38912. * Binds a texture matrix value to its corrsponding uniform
  38913. * @param texture The texture to bind the matrix for
  38914. * @param uniformBuffer The uniform buffer receivin the data
  38915. * @param key The chanel key "diffuse", "specular"... used in the shader
  38916. */
  38917. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  38918. var matrix = texture.getTextureMatrix();
  38919. if (!matrix.isIdentity(true)) {
  38920. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  38921. }
  38922. };
  38923. /**
  38924. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  38925. * @param mesh defines the current mesh
  38926. * @param scene defines the current scene
  38927. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  38928. * @param pointsCloud defines if point cloud rendering has to be turned on
  38929. * @param fogEnabled defines if fog has to be turned on
  38930. * @param alphaTest defines if alpha testing has to be turned on
  38931. * @param defines defines the current list of defines
  38932. */
  38933. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  38934. if (defines._areMiscDirty) {
  38935. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  38936. defines["POINTSIZE"] = pointsCloud;
  38937. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  38938. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  38939. defines["ALPHATEST"] = alphaTest;
  38940. }
  38941. };
  38942. /**
  38943. * Helper used to prepare the list of defines associated with frame values for shader compilation
  38944. * @param scene defines the current scene
  38945. * @param engine defines the current engine
  38946. * @param defines specifies the list of active defines
  38947. * @param useInstances defines if instances have to be turned on
  38948. * @param useClipPlane defines if clip plane have to be turned on
  38949. */
  38950. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  38951. if (useClipPlane === void 0) { useClipPlane = null; }
  38952. var changed = false;
  38953. if (useClipPlane == null) {
  38954. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  38955. }
  38956. if (defines["CLIPPLANE"] !== useClipPlane) {
  38957. defines["CLIPPLANE"] = useClipPlane;
  38958. changed = true;
  38959. }
  38960. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  38961. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  38962. changed = true;
  38963. }
  38964. if (defines["INSTANCES"] !== useInstances) {
  38965. defines["INSTANCES"] = useInstances;
  38966. changed = true;
  38967. }
  38968. if (changed) {
  38969. defines.markAsUnprocessed();
  38970. }
  38971. };
  38972. /**
  38973. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  38974. * @param mesh The mesh containing the geometry data we will draw
  38975. * @param defines The defines to update
  38976. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  38977. * @param useBones Precise whether bones should be used or not (override mesh info)
  38978. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  38979. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  38980. * @returns false if defines are considered not dirty and have not been checked
  38981. */
  38982. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  38983. if (useMorphTargets === void 0) { useMorphTargets = false; }
  38984. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  38985. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  38986. return false;
  38987. }
  38988. defines._normals = defines._needNormals;
  38989. defines._uvs = defines._needUVs;
  38990. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  38991. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38992. defines["TANGENT"] = true;
  38993. }
  38994. if (defines._needUVs) {
  38995. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  38996. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  38997. }
  38998. else {
  38999. defines["UV1"] = false;
  39000. defines["UV2"] = false;
  39001. }
  39002. if (useVertexColor) {
  39003. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  39004. defines["VERTEXCOLOR"] = hasVertexColors;
  39005. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  39006. }
  39007. if (useBones) {
  39008. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  39009. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  39010. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  39011. }
  39012. else {
  39013. defines["NUM_BONE_INFLUENCERS"] = 0;
  39014. defines["BonesPerMesh"] = 0;
  39015. }
  39016. }
  39017. if (useMorphTargets) {
  39018. var manager = mesh.morphTargetManager;
  39019. if (manager) {
  39020. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  39021. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  39022. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  39023. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  39024. }
  39025. else {
  39026. defines["MORPHTARGETS_TANGENT"] = false;
  39027. defines["MORPHTARGETS_NORMAL"] = false;
  39028. defines["MORPHTARGETS"] = false;
  39029. defines["NUM_MORPH_INFLUENCERS"] = 0;
  39030. }
  39031. }
  39032. return true;
  39033. };
  39034. /**
  39035. * Prepares the defines related to the light information passed in parameter
  39036. * @param scene The scene we are intending to draw
  39037. * @param mesh The mesh the effect is compiling for
  39038. * @param defines The defines to update
  39039. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  39040. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  39041. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  39042. * @returns true if normals will be required for the rest of the effect
  39043. */
  39044. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  39045. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39046. if (disableLighting === void 0) { disableLighting = false; }
  39047. if (!defines._areLightsDirty) {
  39048. return defines._needNormals;
  39049. }
  39050. var lightIndex = 0;
  39051. var needNormals = false;
  39052. var needRebuild = false;
  39053. var lightmapMode = false;
  39054. var shadowEnabled = false;
  39055. var specularEnabled = false;
  39056. if (scene.lightsEnabled && !disableLighting) {
  39057. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  39058. var light = _a[_i];
  39059. needNormals = true;
  39060. if (defines["LIGHT" + lightIndex] === undefined) {
  39061. needRebuild = true;
  39062. }
  39063. defines["LIGHT" + lightIndex] = true;
  39064. defines["SPOTLIGHT" + lightIndex] = false;
  39065. defines["HEMILIGHT" + lightIndex] = false;
  39066. defines["POINTLIGHT" + lightIndex] = false;
  39067. defines["DIRLIGHT" + lightIndex] = false;
  39068. var type;
  39069. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  39070. type = "SPOTLIGHT" + lightIndex;
  39071. var spotLight = light;
  39072. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  39073. }
  39074. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  39075. type = "HEMILIGHT" + lightIndex;
  39076. }
  39077. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  39078. type = "POINTLIGHT" + lightIndex;
  39079. }
  39080. else {
  39081. type = "DIRLIGHT" + lightIndex;
  39082. }
  39083. defines[type] = true;
  39084. // Specular
  39085. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  39086. specularEnabled = true;
  39087. }
  39088. // Shadows
  39089. defines["SHADOW" + lightIndex] = false;
  39090. defines["SHADOWPCF" + lightIndex] = false;
  39091. defines["SHADOWPCSS" + lightIndex] = false;
  39092. defines["SHADOWPOISSON" + lightIndex] = false;
  39093. defines["SHADOWESM" + lightIndex] = false;
  39094. defines["SHADOWCUBE" + lightIndex] = false;
  39095. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  39096. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  39097. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  39098. var shadowGenerator = light.getShadowGenerator();
  39099. if (shadowGenerator) {
  39100. shadowEnabled = true;
  39101. shadowGenerator.prepareDefines(defines, lightIndex);
  39102. }
  39103. }
  39104. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  39105. lightmapMode = true;
  39106. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  39107. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  39108. }
  39109. else {
  39110. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  39111. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  39112. }
  39113. lightIndex++;
  39114. if (lightIndex === maxSimultaneousLights)
  39115. break;
  39116. }
  39117. }
  39118. defines["SPECULARTERM"] = specularEnabled;
  39119. defines["SHADOWS"] = shadowEnabled;
  39120. // Resetting all other lights if any
  39121. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  39122. if (defines["LIGHT" + index] !== undefined) {
  39123. defines["LIGHT" + index] = false;
  39124. defines["HEMILIGHT" + lightIndex] = false;
  39125. defines["POINTLIGHT" + lightIndex] = false;
  39126. defines["DIRLIGHT" + lightIndex] = false;
  39127. defines["SPOTLIGHT" + lightIndex] = false;
  39128. defines["SHADOW" + lightIndex] = false;
  39129. }
  39130. }
  39131. var caps = scene.getEngine().getCaps();
  39132. if (defines["SHADOWFLOAT"] === undefined) {
  39133. needRebuild = true;
  39134. }
  39135. defines["SHADOWFLOAT"] = shadowEnabled &&
  39136. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  39137. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  39138. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  39139. if (needRebuild) {
  39140. defines.rebuild();
  39141. }
  39142. return needNormals;
  39143. };
  39144. /**
  39145. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  39146. * that won t be acctive due to defines being turned off.
  39147. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  39148. * @param samplersList The samplers list
  39149. * @param defines The defines helping in the list generation
  39150. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  39151. */
  39152. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  39153. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39154. var uniformsList;
  39155. var uniformBuffersList = null;
  39156. if (uniformsListOrOptions.uniformsNames) {
  39157. var options = uniformsListOrOptions;
  39158. uniformsList = options.uniformsNames;
  39159. uniformBuffersList = options.uniformBuffersNames;
  39160. samplersList = options.samplers;
  39161. defines = options.defines;
  39162. maxSimultaneousLights = options.maxSimultaneousLights;
  39163. }
  39164. else {
  39165. uniformsList = uniformsListOrOptions;
  39166. if (!samplersList) {
  39167. samplersList = [];
  39168. }
  39169. }
  39170. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  39171. if (!defines["LIGHT" + lightIndex]) {
  39172. break;
  39173. }
  39174. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  39175. if (uniformBuffersList) {
  39176. uniformBuffersList.push("Light" + lightIndex);
  39177. }
  39178. samplersList.push("shadowSampler" + lightIndex);
  39179. samplersList.push("depthSampler" + lightIndex);
  39180. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  39181. samplersList.push("projectionLightSampler" + lightIndex);
  39182. uniformsList.push("textureProjectionMatrix" + lightIndex);
  39183. }
  39184. }
  39185. if (defines["NUM_MORPH_INFLUENCERS"]) {
  39186. uniformsList.push("morphTargetInfluences");
  39187. }
  39188. };
  39189. /**
  39190. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  39191. * @param defines The defines to update while falling back
  39192. * @param fallbacks The authorized effect fallbacks
  39193. * @param maxSimultaneousLights The maximum number of lights allowed
  39194. * @param rank the current rank of the Effect
  39195. * @returns The newly affected rank
  39196. */
  39197. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  39198. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39199. if (rank === void 0) { rank = 0; }
  39200. var lightFallbackRank = 0;
  39201. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  39202. if (!defines["LIGHT" + lightIndex]) {
  39203. break;
  39204. }
  39205. if (lightIndex > 0) {
  39206. lightFallbackRank = rank + lightIndex;
  39207. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  39208. }
  39209. if (!defines["SHADOWS"]) {
  39210. if (defines["SHADOW" + lightIndex]) {
  39211. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  39212. }
  39213. if (defines["SHADOWPCF" + lightIndex]) {
  39214. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  39215. }
  39216. if (defines["SHADOWPCSS" + lightIndex]) {
  39217. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  39218. }
  39219. if (defines["SHADOWPOISSON" + lightIndex]) {
  39220. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  39221. }
  39222. if (defines["SHADOWESM" + lightIndex]) {
  39223. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  39224. }
  39225. }
  39226. }
  39227. return lightFallbackRank++;
  39228. };
  39229. /**
  39230. * Prepares the list of attributes required for morph targets according to the effect defines.
  39231. * @param attribs The current list of supported attribs
  39232. * @param mesh The mesh to prepare the morph targets attributes for
  39233. * @param defines The current Defines of the effect
  39234. */
  39235. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  39236. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  39237. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  39238. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  39239. var manager = mesh.morphTargetManager;
  39240. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  39241. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  39242. for (var index = 0; index < influencers; index++) {
  39243. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  39244. if (normal) {
  39245. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  39246. }
  39247. if (tangent) {
  39248. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  39249. }
  39250. if (attribs.length > maxAttributesCount) {
  39251. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  39252. }
  39253. }
  39254. }
  39255. };
  39256. /**
  39257. * Prepares the list of attributes required for bones according to the effect defines.
  39258. * @param attribs The current list of supported attribs
  39259. * @param mesh The mesh to prepare the bones attributes for
  39260. * @param defines The current Defines of the effect
  39261. * @param fallbacks The current efffect fallback strategy
  39262. */
  39263. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  39264. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  39265. fallbacks.addCPUSkinningFallback(0, mesh);
  39266. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39267. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39268. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  39269. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39270. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  39271. }
  39272. }
  39273. };
  39274. /**
  39275. * Prepares the list of attributes required for instances according to the effect defines.
  39276. * @param attribs The current list of supported attribs
  39277. * @param defines The current Defines of the effect
  39278. */
  39279. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  39280. if (defines["INSTANCES"]) {
  39281. attribs.push("world0");
  39282. attribs.push("world1");
  39283. attribs.push("world2");
  39284. attribs.push("world3");
  39285. }
  39286. };
  39287. /**
  39288. * Binds the light shadow information to the effect for the given mesh.
  39289. * @param light The light containing the generator
  39290. * @param scene The scene the lights belongs to
  39291. * @param mesh The mesh we are binding the information to render
  39292. * @param lightIndex The light index in the effect used to render the mesh
  39293. * @param effect The effect we are binding the data to
  39294. */
  39295. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  39296. if (light.shadowEnabled && mesh.receiveShadows) {
  39297. var shadowGenerator = light.getShadowGenerator();
  39298. if (shadowGenerator) {
  39299. shadowGenerator.bindShadowLight(lightIndex, effect);
  39300. }
  39301. }
  39302. };
  39303. /**
  39304. * Binds the light information to the effect.
  39305. * @param light The light containing the generator
  39306. * @param effect The effect we are binding the data to
  39307. * @param lightIndex The light index in the effect used to render
  39308. */
  39309. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  39310. light.transferToEffect(effect, lightIndex + "");
  39311. };
  39312. /**
  39313. * Binds the lights information from the scene to the effect for the given mesh.
  39314. * @param scene The scene the lights belongs to
  39315. * @param mesh The mesh we are binding the information to render
  39316. * @param effect The effect we are binding the data to
  39317. * @param defines The generated defines for the effect
  39318. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  39319. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  39320. */
  39321. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  39322. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39323. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  39324. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  39325. for (var i = 0; i < len; i++) {
  39326. var light = mesh._lightSources[i];
  39327. var iAsString = i.toString();
  39328. var scaledIntensity = light.getScaledIntensity();
  39329. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  39330. MaterialHelper.BindLightProperties(light, effect, i);
  39331. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  39332. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  39333. if (defines["SPECULARTERM"]) {
  39334. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  39335. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  39336. }
  39337. // Shadows
  39338. if (scene.shadowsEnabled) {
  39339. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  39340. }
  39341. light._uniformBuffer.update();
  39342. }
  39343. };
  39344. /**
  39345. * Binds the fog information from the scene to the effect for the given mesh.
  39346. * @param scene The scene the lights belongs to
  39347. * @param mesh The mesh we are binding the information to render
  39348. * @param effect The effect we are binding the data to
  39349. */
  39350. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  39351. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  39352. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  39353. effect.setColor3("vFogColor", scene.fogColor);
  39354. }
  39355. };
  39356. /**
  39357. * Binds the bones information from the mesh to the effect.
  39358. * @param mesh The mesh we are binding the information to render
  39359. * @param effect The effect we are binding the data to
  39360. */
  39361. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  39362. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  39363. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  39364. if (matrices && effect) {
  39365. effect.setMatrices("mBones", matrices);
  39366. }
  39367. }
  39368. };
  39369. /**
  39370. * Binds the morph targets information from the mesh to the effect.
  39371. * @param abstractMesh The mesh we are binding the information to render
  39372. * @param effect The effect we are binding the data to
  39373. */
  39374. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  39375. var manager = abstractMesh.morphTargetManager;
  39376. if (!abstractMesh || !manager) {
  39377. return;
  39378. }
  39379. effect.setFloatArray("morphTargetInfluences", manager.influences);
  39380. };
  39381. /**
  39382. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  39383. * @param defines The generated defines used in the effect
  39384. * @param effect The effect we are binding the data to
  39385. * @param scene The scene we are willing to render with logarithmic scale for
  39386. */
  39387. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  39388. if (defines["LOGARITHMICDEPTH"]) {
  39389. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  39390. }
  39391. };
  39392. /**
  39393. * Binds the clip plane information from the scene to the effect.
  39394. * @param scene The scene the clip plane information are extracted from
  39395. * @param effect The effect we are binding the data to
  39396. */
  39397. MaterialHelper.BindClipPlane = function (effect, scene) {
  39398. if (scene.clipPlane) {
  39399. var clipPlane = scene.clipPlane;
  39400. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  39401. }
  39402. };
  39403. return MaterialHelper;
  39404. }());
  39405. BABYLON.MaterialHelper = MaterialHelper;
  39406. })(BABYLON || (BABYLON = {}));
  39407. //# sourceMappingURL=babylon.materialHelper.js.map
  39408. "use strict";
  39409. var BABYLON;
  39410. (function (BABYLON) {
  39411. var PushMaterial = /** @class */ (function (_super) {
  39412. __extends(PushMaterial, _super);
  39413. function PushMaterial(name, scene) {
  39414. var _this = _super.call(this, name, scene) || this;
  39415. _this._normalMatrix = new BABYLON.Matrix();
  39416. _this.storeEffectOnSubMeshes = true;
  39417. return _this;
  39418. }
  39419. PushMaterial.prototype.getEffect = function () {
  39420. return this._activeEffect;
  39421. };
  39422. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  39423. if (!mesh) {
  39424. return false;
  39425. }
  39426. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  39427. return true;
  39428. }
  39429. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  39430. };
  39431. /**
  39432. * Binds the given world matrix to the active effect
  39433. *
  39434. * @param world the matrix to bind
  39435. */
  39436. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  39437. this._activeEffect.setMatrix("world", world);
  39438. };
  39439. /**
  39440. * Binds the given normal matrix to the active effect
  39441. *
  39442. * @param normalMatrix the matrix to bind
  39443. */
  39444. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  39445. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  39446. };
  39447. PushMaterial.prototype.bind = function (world, mesh) {
  39448. if (!mesh) {
  39449. return;
  39450. }
  39451. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  39452. };
  39453. PushMaterial.prototype._afterBind = function (mesh, effect) {
  39454. if (effect === void 0) { effect = null; }
  39455. _super.prototype._afterBind.call(this, mesh);
  39456. this.getScene()._cachedEffect = effect;
  39457. };
  39458. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  39459. if (visibility === void 0) { visibility = 1; }
  39460. return scene.isCachedMaterialInvalid(this, effect, visibility);
  39461. };
  39462. return PushMaterial;
  39463. }(BABYLON.Material));
  39464. BABYLON.PushMaterial = PushMaterial;
  39465. })(BABYLON || (BABYLON = {}));
  39466. //# sourceMappingURL=babylon.pushMaterial.js.map
  39467. "use strict";
  39468. var BABYLON;
  39469. (function (BABYLON) {
  39470. /** @ignore */
  39471. var StandardMaterialDefines = /** @class */ (function (_super) {
  39472. __extends(StandardMaterialDefines, _super);
  39473. function StandardMaterialDefines() {
  39474. var _this = _super.call(this) || this;
  39475. _this.MAINUV1 = false;
  39476. _this.MAINUV2 = false;
  39477. _this.DIFFUSE = false;
  39478. _this.DIFFUSEDIRECTUV = 0;
  39479. _this.AMBIENT = false;
  39480. _this.AMBIENTDIRECTUV = 0;
  39481. _this.OPACITY = false;
  39482. _this.OPACITYDIRECTUV = 0;
  39483. _this.OPACITYRGB = false;
  39484. _this.REFLECTION = false;
  39485. _this.EMISSIVE = false;
  39486. _this.EMISSIVEDIRECTUV = 0;
  39487. _this.SPECULAR = false;
  39488. _this.SPECULARDIRECTUV = 0;
  39489. _this.BUMP = false;
  39490. _this.BUMPDIRECTUV = 0;
  39491. _this.PARALLAX = false;
  39492. _this.PARALLAXOCCLUSION = false;
  39493. _this.SPECULAROVERALPHA = false;
  39494. _this.CLIPPLANE = false;
  39495. _this.ALPHATEST = false;
  39496. _this.DEPTHPREPASS = false;
  39497. _this.ALPHAFROMDIFFUSE = false;
  39498. _this.POINTSIZE = false;
  39499. _this.FOG = false;
  39500. _this.SPECULARTERM = false;
  39501. _this.DIFFUSEFRESNEL = false;
  39502. _this.OPACITYFRESNEL = false;
  39503. _this.REFLECTIONFRESNEL = false;
  39504. _this.REFRACTIONFRESNEL = false;
  39505. _this.EMISSIVEFRESNEL = false;
  39506. _this.FRESNEL = false;
  39507. _this.NORMAL = false;
  39508. _this.UV1 = false;
  39509. _this.UV2 = false;
  39510. _this.VERTEXCOLOR = false;
  39511. _this.VERTEXALPHA = false;
  39512. _this.NUM_BONE_INFLUENCERS = 0;
  39513. _this.BonesPerMesh = 0;
  39514. _this.INSTANCES = false;
  39515. _this.GLOSSINESS = false;
  39516. _this.ROUGHNESS = false;
  39517. _this.EMISSIVEASILLUMINATION = false;
  39518. _this.LINKEMISSIVEWITHDIFFUSE = false;
  39519. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  39520. _this.LIGHTMAP = false;
  39521. _this.LIGHTMAPDIRECTUV = 0;
  39522. _this.OBJECTSPACE_NORMALMAP = false;
  39523. _this.USELIGHTMAPASSHADOWMAP = false;
  39524. _this.REFLECTIONMAP_3D = false;
  39525. _this.REFLECTIONMAP_SPHERICAL = false;
  39526. _this.REFLECTIONMAP_PLANAR = false;
  39527. _this.REFLECTIONMAP_CUBIC = false;
  39528. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  39529. _this.REFLECTIONMAP_PROJECTION = false;
  39530. _this.REFLECTIONMAP_SKYBOX = false;
  39531. _this.REFLECTIONMAP_EXPLICIT = false;
  39532. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  39533. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  39534. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  39535. _this.INVERTCUBICMAP = false;
  39536. _this.LOGARITHMICDEPTH = false;
  39537. _this.REFRACTION = false;
  39538. _this.REFRACTIONMAP_3D = false;
  39539. _this.REFLECTIONOVERALPHA = false;
  39540. _this.TWOSIDEDLIGHTING = false;
  39541. _this.SHADOWFLOAT = false;
  39542. _this.MORPHTARGETS = false;
  39543. _this.MORPHTARGETS_NORMAL = false;
  39544. _this.MORPHTARGETS_TANGENT = false;
  39545. _this.NUM_MORPH_INFLUENCERS = 0;
  39546. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  39547. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  39548. _this.IMAGEPROCESSING = false;
  39549. _this.VIGNETTE = false;
  39550. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  39551. _this.VIGNETTEBLENDMODEOPAQUE = false;
  39552. _this.TONEMAPPING = false;
  39553. _this.CONTRAST = false;
  39554. _this.COLORCURVES = false;
  39555. _this.COLORGRADING = false;
  39556. _this.COLORGRADING3D = false;
  39557. _this.SAMPLER3DGREENDEPTH = false;
  39558. _this.SAMPLER3DBGRMAP = false;
  39559. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  39560. _this.EXPOSURE = false;
  39561. _this.rebuild();
  39562. return _this;
  39563. }
  39564. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  39565. var modes = [
  39566. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  39567. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  39568. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  39569. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  39570. ];
  39571. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  39572. var mode = modes_1[_i];
  39573. this[mode] = (mode === modeToEnable);
  39574. }
  39575. };
  39576. return StandardMaterialDefines;
  39577. }(BABYLON.MaterialDefines));
  39578. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  39579. var StandardMaterial = /** @class */ (function (_super) {
  39580. __extends(StandardMaterial, _super);
  39581. function StandardMaterial(name, scene) {
  39582. var _this = _super.call(this, name, scene) || this;
  39583. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  39584. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  39585. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  39586. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39587. _this.specularPower = 64;
  39588. _this._useAlphaFromDiffuseTexture = false;
  39589. _this._useEmissiveAsIllumination = false;
  39590. _this._linkEmissiveWithDiffuse = false;
  39591. _this._useSpecularOverAlpha = false;
  39592. _this._useReflectionOverAlpha = false;
  39593. _this._disableLighting = false;
  39594. _this._useObjectSpaceNormalMap = false;
  39595. _this._useParallax = false;
  39596. _this._useParallaxOcclusion = false;
  39597. _this.parallaxScaleBias = 0.05;
  39598. _this._roughness = 0;
  39599. _this.indexOfRefraction = 0.98;
  39600. _this.invertRefractionY = true;
  39601. _this._useLightmapAsShadowmap = false;
  39602. _this._useReflectionFresnelFromSpecular = false;
  39603. _this._useGlossinessFromSpecularMapAlpha = false;
  39604. _this._maxSimultaneousLights = 4;
  39605. /**
  39606. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39607. */
  39608. _this._invertNormalMapX = false;
  39609. /**
  39610. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39611. */
  39612. _this._invertNormalMapY = false;
  39613. /**
  39614. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39615. */
  39616. _this._twoSidedLighting = false;
  39617. _this._renderTargets = new BABYLON.SmartArray(16);
  39618. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  39619. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  39620. // Setup the default processing configuration to the scene.
  39621. _this._attachImageProcessingConfiguration(null);
  39622. _this.getRenderTargetTextures = function () {
  39623. _this._renderTargets.reset();
  39624. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  39625. _this._renderTargets.push(_this._reflectionTexture);
  39626. }
  39627. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  39628. _this._renderTargets.push(_this._refractionTexture);
  39629. }
  39630. return _this._renderTargets;
  39631. };
  39632. return _this;
  39633. }
  39634. ;
  39635. ;
  39636. ;
  39637. ;
  39638. ;
  39639. ;
  39640. ;
  39641. ;
  39642. ;
  39643. ;
  39644. ;
  39645. ;
  39646. ;
  39647. ;
  39648. ;
  39649. ;
  39650. ;
  39651. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  39652. /**
  39653. * Gets the image processing configuration used either in this material.
  39654. */
  39655. get: function () {
  39656. return this._imageProcessingConfiguration;
  39657. },
  39658. /**
  39659. * Sets the Default image processing configuration used either in the this material.
  39660. *
  39661. * If sets to null, the scene one is in use.
  39662. */
  39663. set: function (value) {
  39664. this._attachImageProcessingConfiguration(value);
  39665. // Ensure the effect will be rebuilt.
  39666. this._markAllSubMeshesAsTexturesDirty();
  39667. },
  39668. enumerable: true,
  39669. configurable: true
  39670. });
  39671. /**
  39672. * Attaches a new image processing configuration to the Standard Material.
  39673. * @param configuration
  39674. */
  39675. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  39676. var _this = this;
  39677. if (configuration === this._imageProcessingConfiguration) {
  39678. return;
  39679. }
  39680. // Detaches observer.
  39681. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39682. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39683. }
  39684. // Pick the scene configuration if needed.
  39685. if (!configuration) {
  39686. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  39687. }
  39688. else {
  39689. this._imageProcessingConfiguration = configuration;
  39690. }
  39691. // Attaches observer.
  39692. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  39693. _this._markAllSubMeshesAsImageProcessingDirty();
  39694. });
  39695. };
  39696. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  39697. /**
  39698. * Gets wether the color curves effect is enabled.
  39699. */
  39700. get: function () {
  39701. return this.imageProcessingConfiguration.colorCurvesEnabled;
  39702. },
  39703. /**
  39704. * Sets wether the color curves effect is enabled.
  39705. */
  39706. set: function (value) {
  39707. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39708. },
  39709. enumerable: true,
  39710. configurable: true
  39711. });
  39712. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  39713. /**
  39714. * Gets wether the color grading effect is enabled.
  39715. */
  39716. get: function () {
  39717. return this.imageProcessingConfiguration.colorGradingEnabled;
  39718. },
  39719. /**
  39720. * Gets wether the color grading effect is enabled.
  39721. */
  39722. set: function (value) {
  39723. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39724. },
  39725. enumerable: true,
  39726. configurable: true
  39727. });
  39728. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  39729. /**
  39730. * Gets wether tonemapping is enabled or not.
  39731. */
  39732. get: function () {
  39733. return this._imageProcessingConfiguration.toneMappingEnabled;
  39734. },
  39735. /**
  39736. * Sets wether tonemapping is enabled or not
  39737. */
  39738. set: function (value) {
  39739. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39740. },
  39741. enumerable: true,
  39742. configurable: true
  39743. });
  39744. ;
  39745. ;
  39746. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  39747. /**
  39748. * The camera exposure used on this material.
  39749. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39750. * This corresponds to a photographic exposure.
  39751. */
  39752. get: function () {
  39753. return this._imageProcessingConfiguration.exposure;
  39754. },
  39755. /**
  39756. * The camera exposure used on this material.
  39757. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39758. * This corresponds to a photographic exposure.
  39759. */
  39760. set: function (value) {
  39761. this._imageProcessingConfiguration.exposure = value;
  39762. },
  39763. enumerable: true,
  39764. configurable: true
  39765. });
  39766. ;
  39767. ;
  39768. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  39769. /**
  39770. * Gets The camera contrast used on this material.
  39771. */
  39772. get: function () {
  39773. return this._imageProcessingConfiguration.contrast;
  39774. },
  39775. /**
  39776. * Sets The camera contrast used on this material.
  39777. */
  39778. set: function (value) {
  39779. this._imageProcessingConfiguration.contrast = value;
  39780. },
  39781. enumerable: true,
  39782. configurable: true
  39783. });
  39784. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  39785. /**
  39786. * Gets the Color Grading 2D Lookup Texture.
  39787. */
  39788. get: function () {
  39789. return this._imageProcessingConfiguration.colorGradingTexture;
  39790. },
  39791. /**
  39792. * Sets the Color Grading 2D Lookup Texture.
  39793. */
  39794. set: function (value) {
  39795. this._imageProcessingConfiguration.colorGradingTexture = value;
  39796. },
  39797. enumerable: true,
  39798. configurable: true
  39799. });
  39800. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  39801. /**
  39802. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39803. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39804. * 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;
  39805. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39806. */
  39807. get: function () {
  39808. return this._imageProcessingConfiguration.colorCurves;
  39809. },
  39810. /**
  39811. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39812. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39813. * 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;
  39814. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39815. */
  39816. set: function (value) {
  39817. this._imageProcessingConfiguration.colorCurves = value;
  39818. },
  39819. enumerable: true,
  39820. configurable: true
  39821. });
  39822. StandardMaterial.prototype.getClassName = function () {
  39823. return "StandardMaterial";
  39824. };
  39825. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  39826. get: function () {
  39827. return this._useLogarithmicDepth;
  39828. },
  39829. set: function (value) {
  39830. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39831. this._markAllSubMeshesAsMiscDirty();
  39832. },
  39833. enumerable: true,
  39834. configurable: true
  39835. });
  39836. StandardMaterial.prototype.needAlphaBlending = function () {
  39837. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  39838. };
  39839. StandardMaterial.prototype.needAlphaTesting = function () {
  39840. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  39841. };
  39842. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  39843. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  39844. };
  39845. StandardMaterial.prototype.getAlphaTestTexture = function () {
  39846. return this._diffuseTexture;
  39847. };
  39848. /**
  39849. * Child classes can use it to update shaders
  39850. */
  39851. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  39852. if (useInstances === void 0) { useInstances = false; }
  39853. if (subMesh.effect && this.isFrozen) {
  39854. if (this._wasPreviouslyReady && subMesh.effect) {
  39855. return true;
  39856. }
  39857. }
  39858. if (!subMesh._materialDefines) {
  39859. subMesh._materialDefines = new StandardMaterialDefines();
  39860. }
  39861. var scene = this.getScene();
  39862. var defines = subMesh._materialDefines;
  39863. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  39864. if (defines._renderId === scene.getRenderId()) {
  39865. return true;
  39866. }
  39867. }
  39868. var engine = scene.getEngine();
  39869. // Lights
  39870. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  39871. // Textures
  39872. if (defines._areTexturesDirty) {
  39873. defines._needUVs = false;
  39874. defines.MAINUV1 = false;
  39875. defines.MAINUV2 = false;
  39876. if (scene.texturesEnabled) {
  39877. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39878. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  39879. return false;
  39880. }
  39881. else {
  39882. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  39883. }
  39884. }
  39885. else {
  39886. defines.DIFFUSE = false;
  39887. }
  39888. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39889. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  39890. return false;
  39891. }
  39892. else {
  39893. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  39894. }
  39895. }
  39896. else {
  39897. defines.AMBIENT = false;
  39898. }
  39899. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39900. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  39901. return false;
  39902. }
  39903. else {
  39904. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  39905. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  39906. }
  39907. }
  39908. else {
  39909. defines.OPACITY = false;
  39910. }
  39911. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39912. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  39913. return false;
  39914. }
  39915. else {
  39916. defines._needNormals = true;
  39917. defines.REFLECTION = true;
  39918. defines.ROUGHNESS = (this._roughness > 0);
  39919. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  39920. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  39921. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  39922. switch (this._reflectionTexture.coordinatesMode) {
  39923. case BABYLON.Texture.CUBIC_MODE:
  39924. case BABYLON.Texture.INVCUBIC_MODE:
  39925. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  39926. break;
  39927. case BABYLON.Texture.EXPLICIT_MODE:
  39928. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  39929. break;
  39930. case BABYLON.Texture.PLANAR_MODE:
  39931. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  39932. break;
  39933. case BABYLON.Texture.PROJECTION_MODE:
  39934. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  39935. break;
  39936. case BABYLON.Texture.SKYBOX_MODE:
  39937. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  39938. break;
  39939. case BABYLON.Texture.SPHERICAL_MODE:
  39940. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  39941. break;
  39942. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  39943. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  39944. break;
  39945. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  39946. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  39947. break;
  39948. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  39949. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  39950. break;
  39951. }
  39952. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  39953. }
  39954. }
  39955. else {
  39956. defines.REFLECTION = false;
  39957. }
  39958. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39959. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  39960. return false;
  39961. }
  39962. else {
  39963. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  39964. }
  39965. }
  39966. else {
  39967. defines.EMISSIVE = false;
  39968. }
  39969. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39970. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  39971. return false;
  39972. }
  39973. else {
  39974. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  39975. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  39976. }
  39977. }
  39978. else {
  39979. defines.LIGHTMAP = false;
  39980. }
  39981. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39982. if (!this._specularTexture.isReadyOrNotBlocking()) {
  39983. return false;
  39984. }
  39985. else {
  39986. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  39987. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  39988. }
  39989. }
  39990. else {
  39991. defines.SPECULAR = false;
  39992. }
  39993. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  39994. // Bump texure can not be not blocking.
  39995. if (!this._bumpTexture.isReady()) {
  39996. return false;
  39997. }
  39998. else {
  39999. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  40000. defines.PARALLAX = this._useParallax;
  40001. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  40002. }
  40003. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  40004. }
  40005. else {
  40006. defines.BUMP = false;
  40007. }
  40008. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40009. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  40010. return false;
  40011. }
  40012. else {
  40013. defines._needUVs = true;
  40014. defines.REFRACTION = true;
  40015. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  40016. }
  40017. }
  40018. else {
  40019. defines.REFRACTION = false;
  40020. }
  40021. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  40022. }
  40023. else {
  40024. defines.DIFFUSE = false;
  40025. defines.AMBIENT = false;
  40026. defines.OPACITY = false;
  40027. defines.REFLECTION = false;
  40028. defines.EMISSIVE = false;
  40029. defines.LIGHTMAP = false;
  40030. defines.BUMP = false;
  40031. defines.REFRACTION = false;
  40032. }
  40033. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  40034. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  40035. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  40036. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  40037. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  40038. }
  40039. if (defines._areImageProcessingDirty) {
  40040. if (!this._imageProcessingConfiguration.isReady()) {
  40041. return false;
  40042. }
  40043. this._imageProcessingConfiguration.prepareDefines(defines);
  40044. }
  40045. if (defines._areFresnelDirty) {
  40046. if (StandardMaterial.FresnelEnabled) {
  40047. // Fresnel
  40048. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  40049. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  40050. this._reflectionFresnelParameters) {
  40051. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  40052. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  40053. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  40054. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  40055. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  40056. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  40057. defines._needNormals = true;
  40058. defines.FRESNEL = true;
  40059. }
  40060. }
  40061. else {
  40062. defines.FRESNEL = false;
  40063. }
  40064. }
  40065. // Misc.
  40066. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  40067. // Attribs
  40068. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  40069. // Values that need to be evaluated on every frame
  40070. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  40071. // Get correct effect
  40072. if (defines.isDirty) {
  40073. defines.markAsProcessed();
  40074. scene.resetCachedMaterial();
  40075. // Fallbacks
  40076. var fallbacks = new BABYLON.EffectFallbacks();
  40077. if (defines.REFLECTION) {
  40078. fallbacks.addFallback(0, "REFLECTION");
  40079. }
  40080. if (defines.SPECULAR) {
  40081. fallbacks.addFallback(0, "SPECULAR");
  40082. }
  40083. if (defines.BUMP) {
  40084. fallbacks.addFallback(0, "BUMP");
  40085. }
  40086. if (defines.PARALLAX) {
  40087. fallbacks.addFallback(1, "PARALLAX");
  40088. }
  40089. if (defines.PARALLAXOCCLUSION) {
  40090. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  40091. }
  40092. if (defines.SPECULAROVERALPHA) {
  40093. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  40094. }
  40095. if (defines.FOG) {
  40096. fallbacks.addFallback(1, "FOG");
  40097. }
  40098. if (defines.POINTSIZE) {
  40099. fallbacks.addFallback(0, "POINTSIZE");
  40100. }
  40101. if (defines.LOGARITHMICDEPTH) {
  40102. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  40103. }
  40104. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  40105. if (defines.SPECULARTERM) {
  40106. fallbacks.addFallback(0, "SPECULARTERM");
  40107. }
  40108. if (defines.DIFFUSEFRESNEL) {
  40109. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  40110. }
  40111. if (defines.OPACITYFRESNEL) {
  40112. fallbacks.addFallback(2, "OPACITYFRESNEL");
  40113. }
  40114. if (defines.REFLECTIONFRESNEL) {
  40115. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  40116. }
  40117. if (defines.EMISSIVEFRESNEL) {
  40118. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  40119. }
  40120. if (defines.FRESNEL) {
  40121. fallbacks.addFallback(4, "FRESNEL");
  40122. }
  40123. //Attributes
  40124. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40125. if (defines.NORMAL) {
  40126. attribs.push(BABYLON.VertexBuffer.NormalKind);
  40127. }
  40128. if (defines.UV1) {
  40129. attribs.push(BABYLON.VertexBuffer.UVKind);
  40130. }
  40131. if (defines.UV2) {
  40132. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40133. }
  40134. if (defines.VERTEXCOLOR) {
  40135. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40136. }
  40137. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  40138. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  40139. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  40140. var shaderName = "default";
  40141. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  40142. "vFogInfos", "vFogColor", "pointSize",
  40143. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  40144. "mBones",
  40145. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  40146. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  40147. "vReflectionPosition", "vReflectionSize",
  40148. "logarithmicDepthConstant", "vTangentSpaceParams"
  40149. ];
  40150. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  40151. var uniformBuffers = ["Material", "Scene"];
  40152. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  40153. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  40154. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  40155. uniformsNames: uniforms,
  40156. uniformBuffersNames: uniformBuffers,
  40157. samplers: samplers,
  40158. defines: defines,
  40159. maxSimultaneousLights: this._maxSimultaneousLights
  40160. });
  40161. if (this.customShaderNameResolve) {
  40162. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  40163. }
  40164. var join = defines.toString();
  40165. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  40166. attributes: attribs,
  40167. uniformsNames: uniforms,
  40168. uniformBuffersNames: uniformBuffers,
  40169. samplers: samplers,
  40170. defines: join,
  40171. fallbacks: fallbacks,
  40172. onCompiled: this.onCompiled,
  40173. onError: this.onError,
  40174. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  40175. }, engine), defines);
  40176. this.buildUniformLayout();
  40177. }
  40178. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40179. return false;
  40180. }
  40181. defines._renderId = scene.getRenderId();
  40182. this._wasPreviouslyReady = true;
  40183. return true;
  40184. };
  40185. StandardMaterial.prototype.buildUniformLayout = function () {
  40186. // Order is important !
  40187. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  40188. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  40189. this._uniformBuffer.addUniform("opacityParts", 4);
  40190. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  40191. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  40192. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  40193. this._uniformBuffer.addUniform("refractionRightColor", 4);
  40194. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  40195. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  40196. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  40197. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  40198. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  40199. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  40200. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  40201. this._uniformBuffer.addUniform("vReflectionSize", 3);
  40202. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  40203. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  40204. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  40205. this._uniformBuffer.addUniform("vBumpInfos", 3);
  40206. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  40207. this._uniformBuffer.addUniform("ambientMatrix", 16);
  40208. this._uniformBuffer.addUniform("opacityMatrix", 16);
  40209. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  40210. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  40211. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  40212. this._uniformBuffer.addUniform("specularMatrix", 16);
  40213. this._uniformBuffer.addUniform("bumpMatrix", 16);
  40214. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  40215. this._uniformBuffer.addUniform("refractionMatrix", 16);
  40216. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  40217. this._uniformBuffer.addUniform("vSpecularColor", 4);
  40218. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  40219. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  40220. this._uniformBuffer.addUniform("pointSize", 1);
  40221. this._uniformBuffer.create();
  40222. };
  40223. StandardMaterial.prototype.unbind = function () {
  40224. if (this._activeEffect) {
  40225. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  40226. this._activeEffect.setTexture("reflection2DSampler", null);
  40227. }
  40228. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  40229. this._activeEffect.setTexture("refraction2DSampler", null);
  40230. }
  40231. }
  40232. _super.prototype.unbind.call(this);
  40233. };
  40234. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  40235. var scene = this.getScene();
  40236. var defines = subMesh._materialDefines;
  40237. if (!defines) {
  40238. return;
  40239. }
  40240. var effect = subMesh.effect;
  40241. if (!effect) {
  40242. return;
  40243. }
  40244. this._activeEffect = effect;
  40245. // Matrices
  40246. this.bindOnlyWorldMatrix(world);
  40247. // Normal Matrix
  40248. if (defines.OBJECTSPACE_NORMALMAP) {
  40249. world.toNormalMatrix(this._normalMatrix);
  40250. this.bindOnlyNormalMatrix(this._normalMatrix);
  40251. }
  40252. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  40253. // Bones
  40254. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  40255. if (mustRebind) {
  40256. this._uniformBuffer.bindToEffect(effect, "Material");
  40257. this.bindViewProjection(effect);
  40258. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  40259. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  40260. // Fresnel
  40261. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  40262. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  40263. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  40264. }
  40265. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  40266. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  40267. }
  40268. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  40269. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  40270. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  40271. }
  40272. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  40273. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  40274. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  40275. }
  40276. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  40277. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  40278. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  40279. }
  40280. }
  40281. // Textures
  40282. if (scene.texturesEnabled) {
  40283. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  40284. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  40285. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  40286. }
  40287. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  40288. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  40289. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  40290. }
  40291. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  40292. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  40293. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  40294. }
  40295. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  40296. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  40297. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  40298. if (this._reflectionTexture.boundingBoxSize) {
  40299. var cubeTexture = this._reflectionTexture;
  40300. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  40301. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  40302. }
  40303. }
  40304. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  40305. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  40306. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  40307. }
  40308. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  40309. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  40310. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  40311. }
  40312. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  40313. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  40314. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  40315. }
  40316. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  40317. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  40318. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  40319. if (scene._mirroredCameraPosition) {
  40320. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  40321. }
  40322. else {
  40323. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  40324. }
  40325. }
  40326. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40327. var depth = 1.0;
  40328. if (!this._refractionTexture.isCube) {
  40329. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  40330. if (this._refractionTexture.depth) {
  40331. depth = this._refractionTexture.depth;
  40332. }
  40333. }
  40334. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  40335. }
  40336. }
  40337. // Point size
  40338. if (this.pointsCloud) {
  40339. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  40340. }
  40341. if (defines.SPECULARTERM) {
  40342. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  40343. }
  40344. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  40345. // Diffuse
  40346. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  40347. }
  40348. // Textures
  40349. if (scene.texturesEnabled) {
  40350. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  40351. effect.setTexture("diffuseSampler", this._diffuseTexture);
  40352. }
  40353. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  40354. effect.setTexture("ambientSampler", this._ambientTexture);
  40355. }
  40356. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  40357. effect.setTexture("opacitySampler", this._opacityTexture);
  40358. }
  40359. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  40360. if (this._reflectionTexture.isCube) {
  40361. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  40362. }
  40363. else {
  40364. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  40365. }
  40366. }
  40367. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  40368. effect.setTexture("emissiveSampler", this._emissiveTexture);
  40369. }
  40370. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  40371. effect.setTexture("lightmapSampler", this._lightmapTexture);
  40372. }
  40373. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  40374. effect.setTexture("specularSampler", this._specularTexture);
  40375. }
  40376. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  40377. effect.setTexture("bumpSampler", this._bumpTexture);
  40378. }
  40379. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40380. var depth = 1.0;
  40381. if (this._refractionTexture.isCube) {
  40382. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  40383. }
  40384. else {
  40385. effect.setTexture("refraction2DSampler", this._refractionTexture);
  40386. }
  40387. }
  40388. }
  40389. // Clip plane
  40390. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  40391. // Colors
  40392. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  40393. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  40394. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  40395. }
  40396. if (mustRebind || !this.isFrozen) {
  40397. // Lights
  40398. if (scene.lightsEnabled && !this._disableLighting) {
  40399. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  40400. }
  40401. // View
  40402. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  40403. this.bindView(effect);
  40404. }
  40405. // Fog
  40406. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  40407. // Morph targets
  40408. if (defines.NUM_MORPH_INFLUENCERS) {
  40409. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  40410. }
  40411. // Log. depth
  40412. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  40413. // image processing
  40414. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  40415. this._imageProcessingConfiguration.bind(this._activeEffect);
  40416. }
  40417. }
  40418. this._uniformBuffer.update();
  40419. this._afterBind(mesh, this._activeEffect);
  40420. };
  40421. StandardMaterial.prototype.getAnimatables = function () {
  40422. var results = [];
  40423. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  40424. results.push(this._diffuseTexture);
  40425. }
  40426. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  40427. results.push(this._ambientTexture);
  40428. }
  40429. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  40430. results.push(this._opacityTexture);
  40431. }
  40432. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  40433. results.push(this._reflectionTexture);
  40434. }
  40435. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  40436. results.push(this._emissiveTexture);
  40437. }
  40438. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  40439. results.push(this._specularTexture);
  40440. }
  40441. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  40442. results.push(this._bumpTexture);
  40443. }
  40444. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  40445. results.push(this._lightmapTexture);
  40446. }
  40447. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  40448. results.push(this._refractionTexture);
  40449. }
  40450. return results;
  40451. };
  40452. StandardMaterial.prototype.getActiveTextures = function () {
  40453. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40454. if (this._diffuseTexture) {
  40455. activeTextures.push(this._diffuseTexture);
  40456. }
  40457. if (this._ambientTexture) {
  40458. activeTextures.push(this._ambientTexture);
  40459. }
  40460. if (this._opacityTexture) {
  40461. activeTextures.push(this._opacityTexture);
  40462. }
  40463. if (this._reflectionTexture) {
  40464. activeTextures.push(this._reflectionTexture);
  40465. }
  40466. if (this._emissiveTexture) {
  40467. activeTextures.push(this._emissiveTexture);
  40468. }
  40469. if (this._specularTexture) {
  40470. activeTextures.push(this._specularTexture);
  40471. }
  40472. if (this._bumpTexture) {
  40473. activeTextures.push(this._bumpTexture);
  40474. }
  40475. if (this._lightmapTexture) {
  40476. activeTextures.push(this._lightmapTexture);
  40477. }
  40478. if (this._refractionTexture) {
  40479. activeTextures.push(this._refractionTexture);
  40480. }
  40481. return activeTextures;
  40482. };
  40483. StandardMaterial.prototype.hasTexture = function (texture) {
  40484. if (_super.prototype.hasTexture.call(this, texture)) {
  40485. return true;
  40486. }
  40487. if (this._diffuseTexture === texture) {
  40488. return true;
  40489. }
  40490. if (this._ambientTexture === texture) {
  40491. return true;
  40492. }
  40493. if (this._opacityTexture === texture) {
  40494. return true;
  40495. }
  40496. if (this._reflectionTexture === texture) {
  40497. return true;
  40498. }
  40499. if (this._emissiveTexture === texture) {
  40500. return true;
  40501. }
  40502. if (this._specularTexture === texture) {
  40503. return true;
  40504. }
  40505. if (this._bumpTexture === texture) {
  40506. return true;
  40507. }
  40508. if (this._lightmapTexture === texture) {
  40509. return true;
  40510. }
  40511. if (this._refractionTexture === texture) {
  40512. return true;
  40513. }
  40514. return false;
  40515. };
  40516. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40517. if (forceDisposeTextures) {
  40518. if (this._diffuseTexture) {
  40519. this._diffuseTexture.dispose();
  40520. }
  40521. if (this._ambientTexture) {
  40522. this._ambientTexture.dispose();
  40523. }
  40524. if (this._opacityTexture) {
  40525. this._opacityTexture.dispose();
  40526. }
  40527. if (this._reflectionTexture) {
  40528. this._reflectionTexture.dispose();
  40529. }
  40530. if (this._emissiveTexture) {
  40531. this._emissiveTexture.dispose();
  40532. }
  40533. if (this._specularTexture) {
  40534. this._specularTexture.dispose();
  40535. }
  40536. if (this._bumpTexture) {
  40537. this._bumpTexture.dispose();
  40538. }
  40539. if (this._lightmapTexture) {
  40540. this._lightmapTexture.dispose();
  40541. }
  40542. if (this._refractionTexture) {
  40543. this._refractionTexture.dispose();
  40544. }
  40545. }
  40546. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40547. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40548. }
  40549. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40550. };
  40551. StandardMaterial.prototype.clone = function (name) {
  40552. var _this = this;
  40553. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  40554. result.name = name;
  40555. result.id = name;
  40556. return result;
  40557. };
  40558. StandardMaterial.prototype.serialize = function () {
  40559. return BABYLON.SerializationHelper.Serialize(this);
  40560. };
  40561. // Statics
  40562. StandardMaterial.Parse = function (source, scene, rootUrl) {
  40563. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  40564. };
  40565. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  40566. get: function () {
  40567. return StandardMaterial._DiffuseTextureEnabled;
  40568. },
  40569. set: function (value) {
  40570. if (StandardMaterial._DiffuseTextureEnabled === value) {
  40571. return;
  40572. }
  40573. StandardMaterial._DiffuseTextureEnabled = value;
  40574. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40575. },
  40576. enumerable: true,
  40577. configurable: true
  40578. });
  40579. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  40580. get: function () {
  40581. return StandardMaterial._AmbientTextureEnabled;
  40582. },
  40583. set: function (value) {
  40584. if (StandardMaterial._AmbientTextureEnabled === value) {
  40585. return;
  40586. }
  40587. StandardMaterial._AmbientTextureEnabled = value;
  40588. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40589. },
  40590. enumerable: true,
  40591. configurable: true
  40592. });
  40593. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  40594. get: function () {
  40595. return StandardMaterial._OpacityTextureEnabled;
  40596. },
  40597. set: function (value) {
  40598. if (StandardMaterial._OpacityTextureEnabled === value) {
  40599. return;
  40600. }
  40601. StandardMaterial._OpacityTextureEnabled = value;
  40602. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40603. },
  40604. enumerable: true,
  40605. configurable: true
  40606. });
  40607. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  40608. get: function () {
  40609. return StandardMaterial._ReflectionTextureEnabled;
  40610. },
  40611. set: function (value) {
  40612. if (StandardMaterial._ReflectionTextureEnabled === value) {
  40613. return;
  40614. }
  40615. StandardMaterial._ReflectionTextureEnabled = value;
  40616. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40617. },
  40618. enumerable: true,
  40619. configurable: true
  40620. });
  40621. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  40622. get: function () {
  40623. return StandardMaterial._EmissiveTextureEnabled;
  40624. },
  40625. set: function (value) {
  40626. if (StandardMaterial._EmissiveTextureEnabled === value) {
  40627. return;
  40628. }
  40629. StandardMaterial._EmissiveTextureEnabled = value;
  40630. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40631. },
  40632. enumerable: true,
  40633. configurable: true
  40634. });
  40635. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  40636. get: function () {
  40637. return StandardMaterial._SpecularTextureEnabled;
  40638. },
  40639. set: function (value) {
  40640. if (StandardMaterial._SpecularTextureEnabled === value) {
  40641. return;
  40642. }
  40643. StandardMaterial._SpecularTextureEnabled = value;
  40644. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40645. },
  40646. enumerable: true,
  40647. configurable: true
  40648. });
  40649. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  40650. get: function () {
  40651. return StandardMaterial._BumpTextureEnabled;
  40652. },
  40653. set: function (value) {
  40654. if (StandardMaterial._BumpTextureEnabled === value) {
  40655. return;
  40656. }
  40657. StandardMaterial._BumpTextureEnabled = value;
  40658. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40659. },
  40660. enumerable: true,
  40661. configurable: true
  40662. });
  40663. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  40664. get: function () {
  40665. return StandardMaterial._LightmapTextureEnabled;
  40666. },
  40667. set: function (value) {
  40668. if (StandardMaterial._LightmapTextureEnabled === value) {
  40669. return;
  40670. }
  40671. StandardMaterial._LightmapTextureEnabled = value;
  40672. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40673. },
  40674. enumerable: true,
  40675. configurable: true
  40676. });
  40677. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  40678. get: function () {
  40679. return StandardMaterial._RefractionTextureEnabled;
  40680. },
  40681. set: function (value) {
  40682. if (StandardMaterial._RefractionTextureEnabled === value) {
  40683. return;
  40684. }
  40685. StandardMaterial._RefractionTextureEnabled = value;
  40686. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40687. },
  40688. enumerable: true,
  40689. configurable: true
  40690. });
  40691. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  40692. get: function () {
  40693. return StandardMaterial._ColorGradingTextureEnabled;
  40694. },
  40695. set: function (value) {
  40696. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  40697. return;
  40698. }
  40699. StandardMaterial._ColorGradingTextureEnabled = value;
  40700. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40701. },
  40702. enumerable: true,
  40703. configurable: true
  40704. });
  40705. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  40706. get: function () {
  40707. return StandardMaterial._FresnelEnabled;
  40708. },
  40709. set: function (value) {
  40710. if (StandardMaterial._FresnelEnabled === value) {
  40711. return;
  40712. }
  40713. StandardMaterial._FresnelEnabled = value;
  40714. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  40715. },
  40716. enumerable: true,
  40717. configurable: true
  40718. });
  40719. // Flags used to enable or disable a type of texture for all Standard Materials
  40720. StandardMaterial._DiffuseTextureEnabled = true;
  40721. StandardMaterial._AmbientTextureEnabled = true;
  40722. StandardMaterial._OpacityTextureEnabled = true;
  40723. StandardMaterial._ReflectionTextureEnabled = true;
  40724. StandardMaterial._EmissiveTextureEnabled = true;
  40725. StandardMaterial._SpecularTextureEnabled = true;
  40726. StandardMaterial._BumpTextureEnabled = true;
  40727. StandardMaterial._LightmapTextureEnabled = true;
  40728. StandardMaterial._RefractionTextureEnabled = true;
  40729. StandardMaterial._ColorGradingTextureEnabled = true;
  40730. StandardMaterial._FresnelEnabled = true;
  40731. __decorate([
  40732. BABYLON.serializeAsTexture("diffuseTexture")
  40733. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  40734. __decorate([
  40735. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40736. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  40737. __decorate([
  40738. BABYLON.serializeAsTexture("ambientTexture")
  40739. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  40740. __decorate([
  40741. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40742. ], StandardMaterial.prototype, "ambientTexture", void 0);
  40743. __decorate([
  40744. BABYLON.serializeAsTexture("opacityTexture")
  40745. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  40746. __decorate([
  40747. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40748. ], StandardMaterial.prototype, "opacityTexture", void 0);
  40749. __decorate([
  40750. BABYLON.serializeAsTexture("reflectionTexture")
  40751. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  40752. __decorate([
  40753. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40754. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  40755. __decorate([
  40756. BABYLON.serializeAsTexture("emissiveTexture")
  40757. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  40758. __decorate([
  40759. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40760. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  40761. __decorate([
  40762. BABYLON.serializeAsTexture("specularTexture")
  40763. ], StandardMaterial.prototype, "_specularTexture", void 0);
  40764. __decorate([
  40765. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40766. ], StandardMaterial.prototype, "specularTexture", void 0);
  40767. __decorate([
  40768. BABYLON.serializeAsTexture("bumpTexture")
  40769. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  40770. __decorate([
  40771. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40772. ], StandardMaterial.prototype, "bumpTexture", void 0);
  40773. __decorate([
  40774. BABYLON.serializeAsTexture("lightmapTexture")
  40775. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  40776. __decorate([
  40777. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40778. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  40779. __decorate([
  40780. BABYLON.serializeAsTexture("refractionTexture")
  40781. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  40782. __decorate([
  40783. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40784. ], StandardMaterial.prototype, "refractionTexture", void 0);
  40785. __decorate([
  40786. BABYLON.serializeAsColor3("ambient")
  40787. ], StandardMaterial.prototype, "ambientColor", void 0);
  40788. __decorate([
  40789. BABYLON.serializeAsColor3("diffuse")
  40790. ], StandardMaterial.prototype, "diffuseColor", void 0);
  40791. __decorate([
  40792. BABYLON.serializeAsColor3("specular")
  40793. ], StandardMaterial.prototype, "specularColor", void 0);
  40794. __decorate([
  40795. BABYLON.serializeAsColor3("emissive")
  40796. ], StandardMaterial.prototype, "emissiveColor", void 0);
  40797. __decorate([
  40798. BABYLON.serialize()
  40799. ], StandardMaterial.prototype, "specularPower", void 0);
  40800. __decorate([
  40801. BABYLON.serialize("useAlphaFromDiffuseTexture")
  40802. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  40803. __decorate([
  40804. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40805. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  40806. __decorate([
  40807. BABYLON.serialize("useEmissiveAsIllumination")
  40808. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  40809. __decorate([
  40810. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40811. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  40812. __decorate([
  40813. BABYLON.serialize("linkEmissiveWithDiffuse")
  40814. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  40815. __decorate([
  40816. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40817. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  40818. __decorate([
  40819. BABYLON.serialize("useSpecularOverAlpha")
  40820. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  40821. __decorate([
  40822. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40823. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  40824. __decorate([
  40825. BABYLON.serialize("useReflectionOverAlpha")
  40826. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  40827. __decorate([
  40828. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40829. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  40830. __decorate([
  40831. BABYLON.serialize("disableLighting")
  40832. ], StandardMaterial.prototype, "_disableLighting", void 0);
  40833. __decorate([
  40834. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40835. ], StandardMaterial.prototype, "disableLighting", void 0);
  40836. __decorate([
  40837. BABYLON.serialize("useObjectSpaceNormalMap")
  40838. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  40839. __decorate([
  40840. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40841. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  40842. __decorate([
  40843. BABYLON.serialize("useParallax")
  40844. ], StandardMaterial.prototype, "_useParallax", void 0);
  40845. __decorate([
  40846. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40847. ], StandardMaterial.prototype, "useParallax", void 0);
  40848. __decorate([
  40849. BABYLON.serialize("useParallaxOcclusion")
  40850. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  40851. __decorate([
  40852. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40853. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  40854. __decorate([
  40855. BABYLON.serialize()
  40856. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  40857. __decorate([
  40858. BABYLON.serialize("roughness")
  40859. ], StandardMaterial.prototype, "_roughness", void 0);
  40860. __decorate([
  40861. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40862. ], StandardMaterial.prototype, "roughness", void 0);
  40863. __decorate([
  40864. BABYLON.serialize()
  40865. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  40866. __decorate([
  40867. BABYLON.serialize()
  40868. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  40869. __decorate([
  40870. BABYLON.serialize("useLightmapAsShadowmap")
  40871. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  40872. __decorate([
  40873. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40874. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40875. __decorate([
  40876. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  40877. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  40878. __decorate([
  40879. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40880. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  40881. __decorate([
  40882. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  40883. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  40884. __decorate([
  40885. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  40886. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  40887. __decorate([
  40888. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  40889. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  40890. __decorate([
  40891. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40892. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  40893. __decorate([
  40894. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  40895. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  40896. __decorate([
  40897. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40898. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  40899. __decorate([
  40900. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  40901. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  40902. __decorate([
  40903. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40904. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  40905. __decorate([
  40906. BABYLON.serialize("useReflectionFresnelFromSpecular")
  40907. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  40908. __decorate([
  40909. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40910. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  40911. __decorate([
  40912. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  40913. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  40914. __decorate([
  40915. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40916. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  40917. __decorate([
  40918. BABYLON.serialize("maxSimultaneousLights")
  40919. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  40920. __decorate([
  40921. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40922. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  40923. __decorate([
  40924. BABYLON.serialize("invertNormalMapX")
  40925. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  40926. __decorate([
  40927. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40928. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  40929. __decorate([
  40930. BABYLON.serialize("invertNormalMapY")
  40931. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  40932. __decorate([
  40933. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40934. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  40935. __decorate([
  40936. BABYLON.serialize("twoSidedLighting")
  40937. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  40938. __decorate([
  40939. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40940. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  40941. __decorate([
  40942. BABYLON.serialize()
  40943. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  40944. return StandardMaterial;
  40945. }(BABYLON.PushMaterial));
  40946. BABYLON.StandardMaterial = StandardMaterial;
  40947. })(BABYLON || (BABYLON = {}));
  40948. //# sourceMappingURL=babylon.standardMaterial.js.map
  40949. "use strict";
  40950. var BABYLON;
  40951. (function (BABYLON) {
  40952. /**
  40953. * Manages the defines for the PBR Material.
  40954. */
  40955. var PBRMaterialDefines = /** @class */ (function (_super) {
  40956. __extends(PBRMaterialDefines, _super);
  40957. /**
  40958. * Initializes the PBR Material defines.
  40959. */
  40960. function PBRMaterialDefines() {
  40961. var _this = _super.call(this) || this;
  40962. _this.PBR = true;
  40963. _this.MAINUV1 = false;
  40964. _this.MAINUV2 = false;
  40965. _this.UV1 = false;
  40966. _this.UV2 = false;
  40967. _this.ALBEDO = false;
  40968. _this.ALBEDODIRECTUV = 0;
  40969. _this.VERTEXCOLOR = false;
  40970. _this.AMBIENT = false;
  40971. _this.AMBIENTDIRECTUV = 0;
  40972. _this.AMBIENTINGRAYSCALE = false;
  40973. _this.OPACITY = false;
  40974. _this.VERTEXALPHA = false;
  40975. _this.OPACITYDIRECTUV = 0;
  40976. _this.OPACITYRGB = false;
  40977. _this.ALPHATEST = false;
  40978. _this.DEPTHPREPASS = false;
  40979. _this.ALPHABLEND = false;
  40980. _this.ALPHAFROMALBEDO = false;
  40981. _this.ALPHATESTVALUE = "0.5";
  40982. _this.SPECULAROVERALPHA = false;
  40983. _this.RADIANCEOVERALPHA = false;
  40984. _this.ALPHAFRESNEL = false;
  40985. _this.LINEARALPHAFRESNEL = false;
  40986. _this.PREMULTIPLYALPHA = false;
  40987. _this.EMISSIVE = false;
  40988. _this.EMISSIVEDIRECTUV = 0;
  40989. _this.REFLECTIVITY = false;
  40990. _this.REFLECTIVITYDIRECTUV = 0;
  40991. _this.SPECULARTERM = false;
  40992. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  40993. _this.MICROSURFACEAUTOMATIC = false;
  40994. _this.LODBASEDMICROSFURACE = false;
  40995. _this.MICROSURFACEMAP = false;
  40996. _this.MICROSURFACEMAPDIRECTUV = 0;
  40997. _this.METALLICWORKFLOW = false;
  40998. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  40999. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  41000. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  41001. _this.AOSTOREINMETALMAPRED = false;
  41002. _this.ENVIRONMENTBRDF = false;
  41003. _this.NORMAL = false;
  41004. _this.TANGENT = false;
  41005. _this.BUMP = false;
  41006. _this.BUMPDIRECTUV = 0;
  41007. _this.OBJECTSPACE_NORMALMAP = false;
  41008. _this.PARALLAX = false;
  41009. _this.PARALLAXOCCLUSION = false;
  41010. _this.NORMALXYSCALE = true;
  41011. _this.LIGHTMAP = false;
  41012. _this.LIGHTMAPDIRECTUV = 0;
  41013. _this.USELIGHTMAPASSHADOWMAP = false;
  41014. _this.GAMMALIGHTMAP = false;
  41015. _this.REFLECTION = false;
  41016. _this.REFLECTIONMAP_3D = false;
  41017. _this.REFLECTIONMAP_SPHERICAL = false;
  41018. _this.REFLECTIONMAP_PLANAR = false;
  41019. _this.REFLECTIONMAP_CUBIC = false;
  41020. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41021. _this.REFLECTIONMAP_PROJECTION = false;
  41022. _this.REFLECTIONMAP_SKYBOX = false;
  41023. _this.REFLECTIONMAP_EXPLICIT = false;
  41024. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41025. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41026. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41027. _this.INVERTCUBICMAP = false;
  41028. _this.USESPHERICALFROMREFLECTIONMAP = false;
  41029. _this.USESPHERICALINVERTEX = false;
  41030. _this.REFLECTIONMAP_OPPOSITEZ = false;
  41031. _this.LODINREFLECTIONALPHA = false;
  41032. _this.GAMMAREFLECTION = false;
  41033. _this.RADIANCEOCCLUSION = false;
  41034. _this.HORIZONOCCLUSION = false;
  41035. _this.REFRACTION = false;
  41036. _this.REFRACTIONMAP_3D = false;
  41037. _this.REFRACTIONMAP_OPPOSITEZ = false;
  41038. _this.LODINREFRACTIONALPHA = false;
  41039. _this.GAMMAREFRACTION = false;
  41040. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  41041. _this.INSTANCES = false;
  41042. _this.NUM_BONE_INFLUENCERS = 0;
  41043. _this.BonesPerMesh = 0;
  41044. _this.NONUNIFORMSCALING = false;
  41045. _this.MORPHTARGETS = false;
  41046. _this.MORPHTARGETS_NORMAL = false;
  41047. _this.MORPHTARGETS_TANGENT = false;
  41048. _this.NUM_MORPH_INFLUENCERS = 0;
  41049. _this.IMAGEPROCESSING = false;
  41050. _this.VIGNETTE = false;
  41051. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41052. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41053. _this.TONEMAPPING = false;
  41054. _this.CONTRAST = false;
  41055. _this.COLORCURVES = false;
  41056. _this.COLORGRADING = false;
  41057. _this.COLORGRADING3D = false;
  41058. _this.SAMPLER3DGREENDEPTH = false;
  41059. _this.SAMPLER3DBGRMAP = false;
  41060. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41061. _this.EXPOSURE = false;
  41062. _this.USEPHYSICALLIGHTFALLOFF = false;
  41063. _this.TWOSIDEDLIGHTING = false;
  41064. _this.SHADOWFLOAT = false;
  41065. _this.CLIPPLANE = false;
  41066. _this.POINTSIZE = false;
  41067. _this.FOG = false;
  41068. _this.LOGARITHMICDEPTH = false;
  41069. _this.FORCENORMALFORWARD = false;
  41070. _this.UNLIT = false;
  41071. _this.rebuild();
  41072. return _this;
  41073. }
  41074. /**
  41075. * Resets the PBR Material defines.
  41076. */
  41077. PBRMaterialDefines.prototype.reset = function () {
  41078. _super.prototype.reset.call(this);
  41079. this.ALPHATESTVALUE = "0.5";
  41080. this.PBR = true;
  41081. };
  41082. return PBRMaterialDefines;
  41083. }(BABYLON.MaterialDefines));
  41084. /**
  41085. * The Physically based material base class of BJS.
  41086. *
  41087. * This offers the main features of a standard PBR material.
  41088. * For more information, please refer to the documentation :
  41089. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41090. */
  41091. var PBRBaseMaterial = /** @class */ (function (_super) {
  41092. __extends(PBRBaseMaterial, _super);
  41093. /**
  41094. * Instantiates a new PBRMaterial instance.
  41095. *
  41096. * @param name The material name
  41097. * @param scene The scene the material will be use in.
  41098. */
  41099. function PBRBaseMaterial(name, scene) {
  41100. var _this = _super.call(this, name, scene) || this;
  41101. /**
  41102. * Intensity of the direct lights e.g. the four lights available in your scene.
  41103. * This impacts both the direct diffuse and specular highlights.
  41104. */
  41105. _this._directIntensity = 1.0;
  41106. /**
  41107. * Intensity of the emissive part of the material.
  41108. * This helps controlling the emissive effect without modifying the emissive color.
  41109. */
  41110. _this._emissiveIntensity = 1.0;
  41111. /**
  41112. * Intensity of the environment e.g. how much the environment will light the object
  41113. * either through harmonics for rough material or through the refelction for shiny ones.
  41114. */
  41115. _this._environmentIntensity = 1.0;
  41116. /**
  41117. * This is a special control allowing the reduction of the specular highlights coming from the
  41118. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  41119. */
  41120. _this._specularIntensity = 1.0;
  41121. /**
  41122. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  41123. */
  41124. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  41125. /**
  41126. * Debug Control allowing disabling the bump map on this material.
  41127. */
  41128. _this._disableBumpMap = false;
  41129. /**
  41130. * AKA Occlusion Texture Intensity in other nomenclature.
  41131. */
  41132. _this._ambientTextureStrength = 1.0;
  41133. /**
  41134. * The color of a material in ambient lighting.
  41135. */
  41136. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  41137. /**
  41138. * AKA Diffuse Color in other nomenclature.
  41139. */
  41140. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  41141. /**
  41142. * AKA Specular Color in other nomenclature.
  41143. */
  41144. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  41145. /**
  41146. * The color applied when light is reflected from a material.
  41147. */
  41148. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  41149. /**
  41150. * The color applied when light is emitted from a material.
  41151. */
  41152. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  41153. /**
  41154. * AKA Glossiness in other nomenclature.
  41155. */
  41156. _this._microSurface = 0.9;
  41157. /**
  41158. * source material index of refraction (IOR)' / 'destination material IOR.
  41159. */
  41160. _this._indexOfRefraction = 0.66;
  41161. /**
  41162. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  41163. */
  41164. _this._invertRefractionY = false;
  41165. /**
  41166. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  41167. * Materials half opaque for instance using refraction could benefit from this control.
  41168. */
  41169. _this._linkRefractionWithTransparency = false;
  41170. /**
  41171. * Specifies that the material will use the light map as a show map.
  41172. */
  41173. _this._useLightmapAsShadowmap = false;
  41174. /**
  41175. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  41176. * makes the reflect vector face the model (under horizon).
  41177. */
  41178. _this._useHorizonOcclusion = true;
  41179. /**
  41180. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  41181. * too much the area relying on ambient texture to define their ambient occlusion.
  41182. */
  41183. _this._useRadianceOcclusion = true;
  41184. /**
  41185. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  41186. */
  41187. _this._useAlphaFromAlbedoTexture = false;
  41188. /**
  41189. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  41190. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  41191. */
  41192. _this._useSpecularOverAlpha = true;
  41193. /**
  41194. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  41195. */
  41196. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  41197. /**
  41198. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  41199. */
  41200. _this._useRoughnessFromMetallicTextureAlpha = true;
  41201. /**
  41202. * Specifies if the metallic texture contains the roughness information in its green channel.
  41203. */
  41204. _this._useRoughnessFromMetallicTextureGreen = false;
  41205. /**
  41206. * Specifies if the metallic texture contains the metallness information in its blue channel.
  41207. */
  41208. _this._useMetallnessFromMetallicTextureBlue = false;
  41209. /**
  41210. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  41211. */
  41212. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  41213. /**
  41214. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  41215. */
  41216. _this._useAmbientInGrayScale = false;
  41217. /**
  41218. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  41219. * The material will try to infer what glossiness each pixel should be.
  41220. */
  41221. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  41222. /**
  41223. * BJS is using an harcoded light falloff based on a manually sets up range.
  41224. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  41225. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  41226. */
  41227. _this._usePhysicalLightFalloff = true;
  41228. /**
  41229. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  41230. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  41231. */
  41232. _this._useRadianceOverAlpha = true;
  41233. /**
  41234. * Allows using an object space normal map (instead of tangent space).
  41235. */
  41236. _this._useObjectSpaceNormalMap = false;
  41237. /**
  41238. * Allows using the bump map in parallax mode.
  41239. */
  41240. _this._useParallax = false;
  41241. /**
  41242. * Allows using the bump map in parallax occlusion mode.
  41243. */
  41244. _this._useParallaxOcclusion = false;
  41245. /**
  41246. * Controls the scale bias of the parallax mode.
  41247. */
  41248. _this._parallaxScaleBias = 0.05;
  41249. /**
  41250. * If sets to true, disables all the lights affecting the material.
  41251. */
  41252. _this._disableLighting = false;
  41253. /**
  41254. * Number of Simultaneous lights allowed on the material.
  41255. */
  41256. _this._maxSimultaneousLights = 4;
  41257. /**
  41258. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  41259. */
  41260. _this._invertNormalMapX = false;
  41261. /**
  41262. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  41263. */
  41264. _this._invertNormalMapY = false;
  41265. /**
  41266. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41267. */
  41268. _this._twoSidedLighting = false;
  41269. /**
  41270. * Defines the alpha limits in alpha test mode.
  41271. */
  41272. _this._alphaCutOff = 0.4;
  41273. /**
  41274. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  41275. */
  41276. _this._forceAlphaTest = false;
  41277. /**
  41278. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41279. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  41280. */
  41281. _this._useAlphaFresnel = false;
  41282. /**
  41283. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41284. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  41285. */
  41286. _this._useLinearAlphaFresnel = false;
  41287. /**
  41288. * The transparency mode of the material.
  41289. */
  41290. _this._transparencyMode = null;
  41291. /**
  41292. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  41293. * from cos thetav and roughness:
  41294. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  41295. */
  41296. _this._environmentBRDFTexture = null;
  41297. /**
  41298. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  41299. */
  41300. _this._forceIrradianceInFragment = false;
  41301. /**
  41302. * Force normal to face away from face.
  41303. */
  41304. _this._forceNormalForward = false;
  41305. /**
  41306. * Stores the available render targets.
  41307. */
  41308. _this._renderTargets = new BABYLON.SmartArray(16);
  41309. /**
  41310. * Sets the global ambient color for the material used in lighting calculations.
  41311. */
  41312. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41313. /**
  41314. * If set to true, no lighting calculations will be applied.
  41315. */
  41316. _this._unlit = false;
  41317. // Setup the default processing configuration to the scene.
  41318. _this._attachImageProcessingConfiguration(null);
  41319. _this.getRenderTargetTextures = function () {
  41320. _this._renderTargets.reset();
  41321. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41322. _this._renderTargets.push(_this._reflectionTexture);
  41323. }
  41324. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41325. _this._renderTargets.push(_this._refractionTexture);
  41326. }
  41327. return _this._renderTargets;
  41328. };
  41329. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  41330. return _this;
  41331. }
  41332. /**
  41333. * Attaches a new image processing configuration to the PBR Material.
  41334. * @param configuration
  41335. */
  41336. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41337. var _this = this;
  41338. if (configuration === this._imageProcessingConfiguration) {
  41339. return;
  41340. }
  41341. // Detaches observer.
  41342. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41343. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41344. }
  41345. // Pick the scene configuration if needed.
  41346. if (!configuration) {
  41347. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41348. }
  41349. else {
  41350. this._imageProcessingConfiguration = configuration;
  41351. }
  41352. // Attaches observer.
  41353. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41354. _this._markAllSubMeshesAsImageProcessingDirty();
  41355. });
  41356. };
  41357. /**
  41358. * Gets the name of the material class.
  41359. */
  41360. PBRBaseMaterial.prototype.getClassName = function () {
  41361. return "PBRBaseMaterial";
  41362. };
  41363. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  41364. /**
  41365. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  41366. */
  41367. get: function () {
  41368. return this._useLogarithmicDepth;
  41369. },
  41370. /**
  41371. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  41372. */
  41373. set: function (value) {
  41374. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41375. },
  41376. enumerable: true,
  41377. configurable: true
  41378. });
  41379. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  41380. /**
  41381. * Gets the current transparency mode.
  41382. */
  41383. get: function () {
  41384. return this._transparencyMode;
  41385. },
  41386. /**
  41387. * Sets the transparency mode of the material.
  41388. */
  41389. set: function (value) {
  41390. if (this._transparencyMode === value) {
  41391. return;
  41392. }
  41393. this._transparencyMode = value;
  41394. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  41395. this._markAllSubMeshesAsTexturesAndMiscDirty();
  41396. },
  41397. enumerable: true,
  41398. configurable: true
  41399. });
  41400. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  41401. /**
  41402. * Returns true if alpha blending should be disabled.
  41403. */
  41404. get: function () {
  41405. return (this._linkRefractionWithTransparency ||
  41406. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  41407. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  41408. },
  41409. enumerable: true,
  41410. configurable: true
  41411. });
  41412. /**
  41413. * Specifies whether or not this material should be rendered in alpha blend mode.
  41414. */
  41415. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  41416. if (this._disableAlphaBlending) {
  41417. return false;
  41418. }
  41419. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  41420. };
  41421. /**
  41422. * Specifies if the mesh will require alpha blending.
  41423. * @param mesh - BJS mesh.
  41424. */
  41425. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  41426. if (this._disableAlphaBlending) {
  41427. return false;
  41428. }
  41429. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  41430. };
  41431. /**
  41432. * Specifies whether or not this material should be rendered in alpha test mode.
  41433. */
  41434. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  41435. if (this._forceAlphaTest) {
  41436. return true;
  41437. }
  41438. if (this._linkRefractionWithTransparency) {
  41439. return false;
  41440. }
  41441. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  41442. };
  41443. /**
  41444. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  41445. */
  41446. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  41447. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  41448. };
  41449. /**
  41450. * Gets the texture used for the alpha test.
  41451. */
  41452. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  41453. return this._albedoTexture;
  41454. };
  41455. /**
  41456. * Specifies that the submesh is ready to be used.
  41457. * @param mesh - BJS mesh.
  41458. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  41459. * @param useInstances - Specifies that instances should be used.
  41460. * @returns - boolean indicating that the submesh is ready or not.
  41461. */
  41462. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41463. if (subMesh.effect && this.isFrozen) {
  41464. if (this._wasPreviouslyReady) {
  41465. return true;
  41466. }
  41467. }
  41468. if (!subMesh._materialDefines) {
  41469. subMesh._materialDefines = new PBRMaterialDefines();
  41470. }
  41471. var defines = subMesh._materialDefines;
  41472. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41473. if (defines._renderId === this.getScene().getRenderId()) {
  41474. return true;
  41475. }
  41476. }
  41477. var scene = this.getScene();
  41478. var engine = scene.getEngine();
  41479. if (defines._areTexturesDirty) {
  41480. if (scene.texturesEnabled) {
  41481. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41482. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  41483. return false;
  41484. }
  41485. }
  41486. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41487. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41488. return false;
  41489. }
  41490. }
  41491. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41492. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41493. return false;
  41494. }
  41495. }
  41496. var reflectionTexture = this._getReflectionTexture();
  41497. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41498. if (!reflectionTexture.isReadyOrNotBlocking()) {
  41499. return false;
  41500. }
  41501. }
  41502. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41503. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41504. return false;
  41505. }
  41506. }
  41507. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41508. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41509. return false;
  41510. }
  41511. }
  41512. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41513. if (this._metallicTexture) {
  41514. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  41515. return false;
  41516. }
  41517. }
  41518. else if (this._reflectivityTexture) {
  41519. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  41520. return false;
  41521. }
  41522. }
  41523. if (this._microSurfaceTexture) {
  41524. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  41525. return false;
  41526. }
  41527. }
  41528. }
  41529. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41530. // Bump texture cannot be not blocking.
  41531. if (!this._bumpTexture.isReady()) {
  41532. return false;
  41533. }
  41534. }
  41535. var refractionTexture = this._getRefractionTexture();
  41536. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41537. if (!refractionTexture.isReadyOrNotBlocking()) {
  41538. return false;
  41539. }
  41540. }
  41541. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41542. // This is blocking.
  41543. if (!this._environmentBRDFTexture.isReady()) {
  41544. return false;
  41545. }
  41546. }
  41547. }
  41548. }
  41549. if (defines._areImageProcessingDirty) {
  41550. if (!this._imageProcessingConfiguration.isReady()) {
  41551. return false;
  41552. }
  41553. }
  41554. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41555. mesh.createNormals(true);
  41556. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  41557. }
  41558. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  41559. if (effect) {
  41560. scene.resetCachedMaterial();
  41561. subMesh.setEffect(effect, defines);
  41562. this.buildUniformLayout();
  41563. }
  41564. if (!subMesh.effect || !subMesh.effect.isReady()) {
  41565. return false;
  41566. }
  41567. defines._renderId = scene.getRenderId();
  41568. this._wasPreviouslyReady = true;
  41569. return true;
  41570. };
  41571. /**
  41572. * Specifies if the material uses metallic roughness workflow.
  41573. * @returns boolean specifiying if the material uses metallic roughness workflow.
  41574. */
  41575. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  41576. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  41577. return true;
  41578. }
  41579. return false;
  41580. };
  41581. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  41582. if (onCompiled === void 0) { onCompiled = null; }
  41583. if (onError === void 0) { onError = null; }
  41584. if (useInstances === void 0) { useInstances = null; }
  41585. if (useClipPlane === void 0) { useClipPlane = null; }
  41586. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  41587. if (!defines.isDirty) {
  41588. return null;
  41589. }
  41590. defines.markAsProcessed();
  41591. var scene = this.getScene();
  41592. var engine = scene.getEngine();
  41593. // Fallbacks
  41594. var fallbacks = new BABYLON.EffectFallbacks();
  41595. var fallbackRank = 0;
  41596. if (defines.USESPHERICALINVERTEX) {
  41597. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  41598. }
  41599. if (defines.FOG) {
  41600. fallbacks.addFallback(fallbackRank, "FOG");
  41601. }
  41602. if (defines.POINTSIZE) {
  41603. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  41604. }
  41605. if (defines.LOGARITHMICDEPTH) {
  41606. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  41607. }
  41608. if (defines.PARALLAX) {
  41609. fallbacks.addFallback(fallbackRank, "PARALLAX");
  41610. }
  41611. if (defines.PARALLAXOCCLUSION) {
  41612. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  41613. }
  41614. if (defines.ENVIRONMENTBRDF) {
  41615. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  41616. }
  41617. if (defines.TANGENT) {
  41618. fallbacks.addFallback(fallbackRank++, "TANGENT");
  41619. }
  41620. if (defines.BUMP) {
  41621. fallbacks.addFallback(fallbackRank++, "BUMP");
  41622. }
  41623. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  41624. if (defines.SPECULARTERM) {
  41625. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  41626. }
  41627. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  41628. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  41629. }
  41630. if (defines.LIGHTMAP) {
  41631. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  41632. }
  41633. if (defines.NORMAL) {
  41634. fallbacks.addFallback(fallbackRank++, "NORMAL");
  41635. }
  41636. if (defines.AMBIENT) {
  41637. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  41638. }
  41639. if (defines.EMISSIVE) {
  41640. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  41641. }
  41642. if (defines.VERTEXCOLOR) {
  41643. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  41644. }
  41645. if (defines.NUM_BONE_INFLUENCERS > 0) {
  41646. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  41647. }
  41648. if (defines.MORPHTARGETS) {
  41649. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  41650. }
  41651. //Attributes
  41652. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41653. if (defines.NORMAL) {
  41654. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41655. }
  41656. if (defines.TANGENT) {
  41657. attribs.push(BABYLON.VertexBuffer.TangentKind);
  41658. }
  41659. if (defines.UV1) {
  41660. attribs.push(BABYLON.VertexBuffer.UVKind);
  41661. }
  41662. if (defines.UV2) {
  41663. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41664. }
  41665. if (defines.VERTEXCOLOR) {
  41666. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41667. }
  41668. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41669. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41670. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41671. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  41672. "vFogInfos", "vFogColor", "pointSize",
  41673. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  41674. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41675. "mBones",
  41676. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  41677. "vLightingIntensity",
  41678. "logarithmicDepthConstant",
  41679. "vSphericalX", "vSphericalY", "vSphericalZ",
  41680. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  41681. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  41682. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  41683. "vTangentSpaceParams"
  41684. ];
  41685. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  41686. "bumpSampler", "lightmapSampler", "opacitySampler",
  41687. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  41688. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  41689. "microSurfaceSampler", "environmentBrdfSampler"];
  41690. var uniformBuffers = ["Material", "Scene"];
  41691. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41692. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41693. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41694. uniformsNames: uniforms,
  41695. uniformBuffersNames: uniformBuffers,
  41696. samplers: samplers,
  41697. defines: defines,
  41698. maxSimultaneousLights: this._maxSimultaneousLights
  41699. });
  41700. var join = defines.toString();
  41701. return engine.createEffect("pbr", {
  41702. attributes: attribs,
  41703. uniformsNames: uniforms,
  41704. uniformBuffersNames: uniformBuffers,
  41705. samplers: samplers,
  41706. defines: join,
  41707. fallbacks: fallbacks,
  41708. onCompiled: onCompiled,
  41709. onError: onError,
  41710. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41711. }, engine);
  41712. };
  41713. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  41714. if (useInstances === void 0) { useInstances = null; }
  41715. if (useClipPlane === void 0) { useClipPlane = null; }
  41716. var scene = this.getScene();
  41717. var engine = scene.getEngine();
  41718. // Lights
  41719. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41720. defines._needNormals = true;
  41721. // Textures
  41722. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  41723. if (defines._areTexturesDirty) {
  41724. defines._needUVs = false;
  41725. if (scene.texturesEnabled) {
  41726. if (scene.getEngine().getCaps().textureLOD) {
  41727. defines.LODBASEDMICROSFURACE = true;
  41728. }
  41729. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41730. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  41731. }
  41732. else {
  41733. defines.ALBEDO = false;
  41734. }
  41735. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41736. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41737. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  41738. }
  41739. else {
  41740. defines.AMBIENT = false;
  41741. }
  41742. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41743. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41744. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41745. }
  41746. else {
  41747. defines.OPACITY = false;
  41748. }
  41749. var reflectionTexture = this._getReflectionTexture();
  41750. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41751. defines.REFLECTION = true;
  41752. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  41753. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  41754. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  41755. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  41756. defines.INVERTCUBICMAP = true;
  41757. }
  41758. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  41759. switch (reflectionTexture.coordinatesMode) {
  41760. case BABYLON.Texture.CUBIC_MODE:
  41761. case BABYLON.Texture.INVCUBIC_MODE:
  41762. defines.REFLECTIONMAP_CUBIC = true;
  41763. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  41764. break;
  41765. case BABYLON.Texture.EXPLICIT_MODE:
  41766. defines.REFLECTIONMAP_EXPLICIT = true;
  41767. break;
  41768. case BABYLON.Texture.PLANAR_MODE:
  41769. defines.REFLECTIONMAP_PLANAR = true;
  41770. break;
  41771. case BABYLON.Texture.PROJECTION_MODE:
  41772. defines.REFLECTIONMAP_PROJECTION = true;
  41773. break;
  41774. case BABYLON.Texture.SKYBOX_MODE:
  41775. defines.REFLECTIONMAP_SKYBOX = true;
  41776. break;
  41777. case BABYLON.Texture.SPHERICAL_MODE:
  41778. defines.REFLECTIONMAP_SPHERICAL = true;
  41779. break;
  41780. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41781. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  41782. break;
  41783. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41784. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  41785. break;
  41786. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41787. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  41788. break;
  41789. }
  41790. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  41791. if (reflectionTexture.sphericalPolynomial) {
  41792. defines.USESPHERICALFROMREFLECTIONMAP = true;
  41793. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  41794. defines.USESPHERICALINVERTEX = false;
  41795. }
  41796. else {
  41797. defines.USESPHERICALINVERTEX = true;
  41798. }
  41799. }
  41800. }
  41801. }
  41802. else {
  41803. defines.REFLECTION = false;
  41804. defines.REFLECTIONMAP_3D = false;
  41805. defines.REFLECTIONMAP_SPHERICAL = false;
  41806. defines.REFLECTIONMAP_PLANAR = false;
  41807. defines.REFLECTIONMAP_CUBIC = false;
  41808. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41809. defines.REFLECTIONMAP_PROJECTION = false;
  41810. defines.REFLECTIONMAP_SKYBOX = false;
  41811. defines.REFLECTIONMAP_EXPLICIT = false;
  41812. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41813. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41814. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41815. defines.INVERTCUBICMAP = false;
  41816. defines.USESPHERICALFROMREFLECTIONMAP = false;
  41817. defines.USESPHERICALINVERTEX = false;
  41818. defines.REFLECTIONMAP_OPPOSITEZ = false;
  41819. defines.LODINREFLECTIONALPHA = false;
  41820. defines.GAMMAREFLECTION = false;
  41821. }
  41822. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41823. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41824. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41825. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  41826. }
  41827. else {
  41828. defines.LIGHTMAP = false;
  41829. }
  41830. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41831. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41832. }
  41833. else {
  41834. defines.EMISSIVE = false;
  41835. }
  41836. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41837. if (this._metallicTexture) {
  41838. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  41839. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  41840. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  41841. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  41842. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  41843. }
  41844. else if (this._reflectivityTexture) {
  41845. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  41846. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  41847. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  41848. }
  41849. else {
  41850. defines.REFLECTIVITY = false;
  41851. }
  41852. if (this._microSurfaceTexture) {
  41853. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  41854. }
  41855. else {
  41856. defines.MICROSURFACEMAP = false;
  41857. }
  41858. }
  41859. else {
  41860. defines.REFLECTIVITY = false;
  41861. defines.MICROSURFACEMAP = false;
  41862. }
  41863. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41864. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41865. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41866. defines.PARALLAX = true;
  41867. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  41868. }
  41869. else {
  41870. defines.PARALLAX = false;
  41871. }
  41872. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41873. }
  41874. else {
  41875. defines.BUMP = false;
  41876. }
  41877. var refractionTexture = this._getRefractionTexture();
  41878. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41879. defines.REFRACTION = true;
  41880. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  41881. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  41882. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  41883. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  41884. if (this._linkRefractionWithTransparency) {
  41885. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  41886. }
  41887. }
  41888. else {
  41889. defines.REFRACTION = false;
  41890. }
  41891. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41892. defines.ENVIRONMENTBRDF = true;
  41893. }
  41894. else {
  41895. defines.ENVIRONMENTBRDF = false;
  41896. }
  41897. if (this._shouldUseAlphaFromAlbedoTexture()) {
  41898. defines.ALPHAFROMALBEDO = true;
  41899. }
  41900. else {
  41901. defines.ALPHAFROMALBEDO = false;
  41902. }
  41903. }
  41904. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41905. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  41906. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  41907. if (!this.backFaceCulling && this._twoSidedLighting) {
  41908. defines.TWOSIDEDLIGHTING = true;
  41909. }
  41910. else {
  41911. defines.TWOSIDEDLIGHTING = false;
  41912. }
  41913. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  41914. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41915. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  41916. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  41917. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  41918. }
  41919. if (defines._areImageProcessingDirty) {
  41920. this._imageProcessingConfiguration.prepareDefines(defines);
  41921. }
  41922. defines.FORCENORMALFORWARD = this._forceNormalForward;
  41923. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  41924. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  41925. // Misc.
  41926. if (defines._areMiscDirty) {
  41927. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  41928. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41929. }
  41930. // Values that need to be evaluated on every frame
  41931. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  41932. // Attribs
  41933. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  41934. };
  41935. /**
  41936. * Force shader compilation
  41937. */
  41938. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  41939. var _this = this;
  41940. var localOptions = __assign({ clipPlane: false }, options);
  41941. var defines = new PBRMaterialDefines();
  41942. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  41943. if (effect.isReady()) {
  41944. if (onCompiled) {
  41945. onCompiled(this);
  41946. }
  41947. }
  41948. else {
  41949. effect.onCompileObservable.add(function () {
  41950. if (onCompiled) {
  41951. onCompiled(_this);
  41952. }
  41953. });
  41954. }
  41955. };
  41956. /**
  41957. * Initializes the uniform buffer layout for the shader.
  41958. */
  41959. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  41960. // Order is important !
  41961. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  41962. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  41963. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41964. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41965. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41966. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  41967. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  41968. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41969. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41970. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41971. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41972. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41973. this._uniformBuffer.addUniform("albedoMatrix", 16);
  41974. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41975. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41976. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41977. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41978. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  41979. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  41980. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41981. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41982. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41983. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41984. this._uniformBuffer.addUniform("vReflectionColor", 3);
  41985. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  41986. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  41987. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  41988. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  41989. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  41990. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41991. this._uniformBuffer.addUniform("pointSize", 1);
  41992. this._uniformBuffer.create();
  41993. };
  41994. /**
  41995. * Unbinds the textures.
  41996. */
  41997. PBRBaseMaterial.prototype.unbind = function () {
  41998. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41999. this._uniformBuffer.setTexture("reflectionSampler", null);
  42000. }
  42001. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42002. this._uniformBuffer.setTexture("refractionSampler", null);
  42003. }
  42004. _super.prototype.unbind.call(this);
  42005. };
  42006. /**
  42007. * Binds the submesh data.
  42008. * @param world - The world matrix.
  42009. * @param mesh - The BJS mesh.
  42010. * @param subMesh - A submesh of the BJS mesh.
  42011. */
  42012. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42013. var scene = this.getScene();
  42014. var defines = subMesh._materialDefines;
  42015. if (!defines) {
  42016. return;
  42017. }
  42018. var effect = subMesh.effect;
  42019. if (!effect) {
  42020. return;
  42021. }
  42022. this._activeEffect = effect;
  42023. // Matrices
  42024. this.bindOnlyWorldMatrix(world);
  42025. // Normal Matrix
  42026. if (defines.OBJECTSPACE_NORMALMAP) {
  42027. world.toNormalMatrix(this._normalMatrix);
  42028. this.bindOnlyNormalMatrix(this._normalMatrix);
  42029. }
  42030. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42031. // Bones
  42032. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  42033. var reflectionTexture = null;
  42034. if (mustRebind) {
  42035. this._uniformBuffer.bindToEffect(effect, "Material");
  42036. this.bindViewProjection(effect);
  42037. reflectionTexture = this._getReflectionTexture();
  42038. var refractionTexture = this._getRefractionTexture();
  42039. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42040. // Texture uniforms
  42041. if (scene.texturesEnabled) {
  42042. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  42043. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  42044. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  42045. }
  42046. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  42047. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  42048. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42049. }
  42050. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  42051. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42052. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42053. }
  42054. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  42055. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  42056. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  42057. if (reflectionTexture.boundingBoxSize) {
  42058. var cubeTexture = reflectionTexture;
  42059. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42060. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42061. }
  42062. var polynomials = reflectionTexture.sphericalPolynomial;
  42063. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  42064. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  42065. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  42066. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  42067. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  42068. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  42069. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  42070. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  42071. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  42072. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  42073. }
  42074. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  42075. }
  42076. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  42077. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42078. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42079. }
  42080. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  42081. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42082. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42083. }
  42084. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  42085. if (this._metallicTexture) {
  42086. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  42087. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  42088. }
  42089. else if (this._reflectivityTexture) {
  42090. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  42091. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  42092. }
  42093. if (this._microSurfaceTexture) {
  42094. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  42095. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  42096. }
  42097. }
  42098. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  42099. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  42100. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42101. if (scene._mirroredCameraPosition) {
  42102. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42103. }
  42104. else {
  42105. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42106. }
  42107. }
  42108. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  42109. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  42110. var depth = 1.0;
  42111. if (!refractionTexture.isCube) {
  42112. if (refractionTexture.depth) {
  42113. depth = refractionTexture.depth;
  42114. }
  42115. }
  42116. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  42117. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  42118. }
  42119. }
  42120. // Point size
  42121. if (this.pointsCloud) {
  42122. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42123. }
  42124. // Colors
  42125. if (defines.METALLICWORKFLOW) {
  42126. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  42127. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  42128. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  42129. }
  42130. else {
  42131. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  42132. }
  42133. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  42134. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  42135. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  42136. // Misc
  42137. this._lightingInfos.x = this._directIntensity;
  42138. this._lightingInfos.y = this._emissiveIntensity;
  42139. this._lightingInfos.z = this._environmentIntensity;
  42140. this._lightingInfos.w = this._specularIntensity;
  42141. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  42142. }
  42143. // Textures
  42144. if (scene.texturesEnabled) {
  42145. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  42146. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  42147. }
  42148. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  42149. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  42150. }
  42151. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  42152. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  42153. }
  42154. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  42155. if (defines.LODBASEDMICROSFURACE) {
  42156. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  42157. }
  42158. else {
  42159. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  42160. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  42161. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  42162. }
  42163. }
  42164. if (defines.ENVIRONMENTBRDF) {
  42165. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  42166. }
  42167. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  42168. if (defines.LODBASEDMICROSFURACE) {
  42169. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  42170. }
  42171. else {
  42172. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  42173. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  42174. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  42175. }
  42176. }
  42177. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  42178. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  42179. }
  42180. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  42181. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  42182. }
  42183. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  42184. if (this._metallicTexture) {
  42185. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  42186. }
  42187. else if (this._reflectivityTexture) {
  42188. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  42189. }
  42190. if (this._microSurfaceTexture) {
  42191. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  42192. }
  42193. }
  42194. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  42195. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  42196. }
  42197. }
  42198. // Clip plane
  42199. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  42200. // Colors
  42201. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  42202. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42203. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  42204. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  42205. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42206. }
  42207. if (mustRebind || !this.isFrozen) {
  42208. // Lights
  42209. if (scene.lightsEnabled && !this._disableLighting) {
  42210. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  42211. }
  42212. // View
  42213. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  42214. this.bindView(effect);
  42215. }
  42216. // Fog
  42217. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  42218. // Morph targets
  42219. if (defines.NUM_MORPH_INFLUENCERS) {
  42220. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  42221. }
  42222. // image processing
  42223. this._imageProcessingConfiguration.bind(this._activeEffect);
  42224. // Log. depth
  42225. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  42226. }
  42227. this._uniformBuffer.update();
  42228. this._afterBind(mesh);
  42229. };
  42230. /**
  42231. * Returns the animatable textures.
  42232. * @returns - Array of animatable textures.
  42233. */
  42234. PBRBaseMaterial.prototype.getAnimatables = function () {
  42235. var results = [];
  42236. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  42237. results.push(this._albedoTexture);
  42238. }
  42239. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42240. results.push(this._ambientTexture);
  42241. }
  42242. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42243. results.push(this._opacityTexture);
  42244. }
  42245. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42246. results.push(this._reflectionTexture);
  42247. }
  42248. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42249. results.push(this._emissiveTexture);
  42250. }
  42251. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  42252. results.push(this._metallicTexture);
  42253. }
  42254. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  42255. results.push(this._reflectivityTexture);
  42256. }
  42257. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42258. results.push(this._bumpTexture);
  42259. }
  42260. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42261. results.push(this._lightmapTexture);
  42262. }
  42263. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42264. results.push(this._refractionTexture);
  42265. }
  42266. return results;
  42267. };
  42268. /**
  42269. * Returns the texture used for reflections.
  42270. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  42271. */
  42272. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  42273. if (this._reflectionTexture) {
  42274. return this._reflectionTexture;
  42275. }
  42276. return this.getScene().environmentTexture;
  42277. };
  42278. /**
  42279. * Returns the texture used for refraction or null if none is used.
  42280. * @returns - Refection texture if present. If no refraction texture and refraction
  42281. * is linked with transparency, returns environment texture. Otherwise, returns null.
  42282. */
  42283. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  42284. if (this._refractionTexture) {
  42285. return this._refractionTexture;
  42286. }
  42287. if (this._linkRefractionWithTransparency) {
  42288. return this.getScene().environmentTexture;
  42289. }
  42290. return null;
  42291. };
  42292. /**
  42293. * Disposes the resources of the material.
  42294. * @param forceDisposeEffect - Forces the disposal of effects.
  42295. * @param forceDisposeTextures - Forces the disposal of all textures.
  42296. */
  42297. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42298. if (forceDisposeTextures) {
  42299. if (this._albedoTexture) {
  42300. this._albedoTexture.dispose();
  42301. }
  42302. if (this._ambientTexture) {
  42303. this._ambientTexture.dispose();
  42304. }
  42305. if (this._opacityTexture) {
  42306. this._opacityTexture.dispose();
  42307. }
  42308. if (this._reflectionTexture) {
  42309. this._reflectionTexture.dispose();
  42310. }
  42311. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  42312. this._environmentBRDFTexture.dispose();
  42313. }
  42314. if (this._emissiveTexture) {
  42315. this._emissiveTexture.dispose();
  42316. }
  42317. if (this._metallicTexture) {
  42318. this._metallicTexture.dispose();
  42319. }
  42320. if (this._reflectivityTexture) {
  42321. this._reflectivityTexture.dispose();
  42322. }
  42323. if (this._bumpTexture) {
  42324. this._bumpTexture.dispose();
  42325. }
  42326. if (this._lightmapTexture) {
  42327. this._lightmapTexture.dispose();
  42328. }
  42329. if (this._refractionTexture) {
  42330. this._refractionTexture.dispose();
  42331. }
  42332. }
  42333. this._renderTargets.dispose();
  42334. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42335. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42336. }
  42337. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42338. };
  42339. /**
  42340. * Stores the reflectivity values based on metallic roughness workflow.
  42341. */
  42342. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  42343. __decorate([
  42344. BABYLON.serializeAsImageProcessingConfiguration()
  42345. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  42346. __decorate([
  42347. BABYLON.serialize()
  42348. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  42349. __decorate([
  42350. BABYLON.serialize()
  42351. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  42352. return PBRBaseMaterial;
  42353. }(BABYLON.PushMaterial));
  42354. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  42355. })(BABYLON || (BABYLON = {}));
  42356. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  42357. "use strict";
  42358. var BABYLON;
  42359. (function (BABYLON) {
  42360. /**
  42361. * The Physically based simple base material of BJS.
  42362. *
  42363. * This enables better naming and convention enforcements on top of the pbrMaterial.
  42364. * It is used as the base class for both the specGloss and metalRough conventions.
  42365. */
  42366. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  42367. __extends(PBRBaseSimpleMaterial, _super);
  42368. /**
  42369. * Instantiates a new PBRMaterial instance.
  42370. *
  42371. * @param name The material name
  42372. * @param scene The scene the material will be use in.
  42373. */
  42374. function PBRBaseSimpleMaterial(name, scene) {
  42375. var _this = _super.call(this, name, scene) || this;
  42376. /**
  42377. * Number of Simultaneous lights allowed on the material.
  42378. */
  42379. _this.maxSimultaneousLights = 4;
  42380. /**
  42381. * If sets to true, disables all the lights affecting the material.
  42382. */
  42383. _this.disableLighting = false;
  42384. /**
  42385. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42386. */
  42387. _this.invertNormalMapX = false;
  42388. /**
  42389. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42390. */
  42391. _this.invertNormalMapY = false;
  42392. /**
  42393. * Emissivie color used to self-illuminate the model.
  42394. */
  42395. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42396. /**
  42397. * Occlusion Channel Strenght.
  42398. */
  42399. _this.occlusionStrength = 1.0;
  42400. _this.useLightmapAsShadowmap = false;
  42401. _this._useAlphaFromAlbedoTexture = true;
  42402. _this._useAmbientInGrayScale = true;
  42403. return _this;
  42404. }
  42405. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  42406. /**
  42407. * Gets the current double sided mode.
  42408. */
  42409. get: function () {
  42410. return this._twoSidedLighting;
  42411. },
  42412. /**
  42413. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42414. */
  42415. set: function (value) {
  42416. if (this._twoSidedLighting === value) {
  42417. return;
  42418. }
  42419. this._twoSidedLighting = value;
  42420. this.backFaceCulling = !value;
  42421. this._markAllSubMeshesAsTexturesDirty();
  42422. },
  42423. enumerable: true,
  42424. configurable: true
  42425. });
  42426. /**
  42427. * Return the active textures of the material.
  42428. */
  42429. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  42430. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42431. if (this.environmentTexture) {
  42432. activeTextures.push(this.environmentTexture);
  42433. }
  42434. if (this.normalTexture) {
  42435. activeTextures.push(this.normalTexture);
  42436. }
  42437. if (this.emissiveTexture) {
  42438. activeTextures.push(this.emissiveTexture);
  42439. }
  42440. if (this.occlusionTexture) {
  42441. activeTextures.push(this.occlusionTexture);
  42442. }
  42443. if (this.lightmapTexture) {
  42444. activeTextures.push(this.lightmapTexture);
  42445. }
  42446. return activeTextures;
  42447. };
  42448. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  42449. if (_super.prototype.hasTexture.call(this, texture)) {
  42450. return true;
  42451. }
  42452. if (this.lightmapTexture === texture) {
  42453. return true;
  42454. }
  42455. return false;
  42456. };
  42457. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  42458. return "PBRBaseSimpleMaterial";
  42459. };
  42460. __decorate([
  42461. BABYLON.serialize(),
  42462. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42463. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  42464. __decorate([
  42465. BABYLON.serialize(),
  42466. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42467. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  42468. __decorate([
  42469. BABYLON.serializeAsTexture(),
  42470. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  42471. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  42472. __decorate([
  42473. BABYLON.serialize(),
  42474. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42475. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  42476. __decorate([
  42477. BABYLON.serialize(),
  42478. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42479. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  42480. __decorate([
  42481. BABYLON.serializeAsTexture(),
  42482. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  42483. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  42484. __decorate([
  42485. BABYLON.serializeAsColor3("emissive"),
  42486. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42487. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  42488. __decorate([
  42489. BABYLON.serializeAsTexture(),
  42490. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42491. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  42492. __decorate([
  42493. BABYLON.serialize(),
  42494. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  42495. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  42496. __decorate([
  42497. BABYLON.serializeAsTexture(),
  42498. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  42499. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  42500. __decorate([
  42501. BABYLON.serialize(),
  42502. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  42503. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  42504. __decorate([
  42505. BABYLON.serialize()
  42506. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  42507. __decorate([
  42508. BABYLON.serializeAsTexture(),
  42509. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42510. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  42511. __decorate([
  42512. BABYLON.serialize(),
  42513. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42514. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42515. return PBRBaseSimpleMaterial;
  42516. }(BABYLON.PBRBaseMaterial));
  42517. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  42518. })(BABYLON || (BABYLON = {}));
  42519. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  42520. "use strict";
  42521. var BABYLON;
  42522. (function (BABYLON) {
  42523. /**
  42524. * The Physically based material of BJS.
  42525. *
  42526. * This offers the main features of a standard PBR material.
  42527. * For more information, please refer to the documentation :
  42528. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  42529. */
  42530. var PBRMaterial = /** @class */ (function (_super) {
  42531. __extends(PBRMaterial, _super);
  42532. /**
  42533. * Instantiates a new PBRMaterial instance.
  42534. *
  42535. * @param name The material name
  42536. * @param scene The scene the material will be use in.
  42537. */
  42538. function PBRMaterial(name, scene) {
  42539. var _this = _super.call(this, name, scene) || this;
  42540. /**
  42541. * Intensity of the direct lights e.g. the four lights available in your scene.
  42542. * This impacts both the direct diffuse and specular highlights.
  42543. */
  42544. _this.directIntensity = 1.0;
  42545. /**
  42546. * Intensity of the emissive part of the material.
  42547. * This helps controlling the emissive effect without modifying the emissive color.
  42548. */
  42549. _this.emissiveIntensity = 1.0;
  42550. /**
  42551. * Intensity of the environment e.g. how much the environment will light the object
  42552. * either through harmonics for rough material or through the refelction for shiny ones.
  42553. */
  42554. _this.environmentIntensity = 1.0;
  42555. /**
  42556. * This is a special control allowing the reduction of the specular highlights coming from the
  42557. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  42558. */
  42559. _this.specularIntensity = 1.0;
  42560. /**
  42561. * Debug Control allowing disabling the bump map on this material.
  42562. */
  42563. _this.disableBumpMap = false;
  42564. /**
  42565. * AKA Occlusion Texture Intensity in other nomenclature.
  42566. */
  42567. _this.ambientTextureStrength = 1.0;
  42568. /**
  42569. * The color of a material in ambient lighting.
  42570. */
  42571. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42572. /**
  42573. * AKA Diffuse Color in other nomenclature.
  42574. */
  42575. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  42576. /**
  42577. * AKA Specular Color in other nomenclature.
  42578. */
  42579. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  42580. /**
  42581. * The color reflected from the material.
  42582. */
  42583. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  42584. /**
  42585. * The color emitted from the material.
  42586. */
  42587. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42588. /**
  42589. * AKA Glossiness in other nomenclature.
  42590. */
  42591. _this.microSurface = 1.0;
  42592. /**
  42593. * source material index of refraction (IOR)' / 'destination material IOR.
  42594. */
  42595. _this.indexOfRefraction = 0.66;
  42596. /**
  42597. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  42598. */
  42599. _this.invertRefractionY = false;
  42600. /**
  42601. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  42602. * Materials half opaque for instance using refraction could benefit from this control.
  42603. */
  42604. _this.linkRefractionWithTransparency = false;
  42605. _this.useLightmapAsShadowmap = false;
  42606. /**
  42607. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  42608. */
  42609. _this.useAlphaFromAlbedoTexture = false;
  42610. /**
  42611. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  42612. */
  42613. _this.forceAlphaTest = false;
  42614. /**
  42615. * Defines the alpha limits in alpha test mode.
  42616. */
  42617. _this.alphaCutOff = 0.4;
  42618. /**
  42619. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  42620. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  42621. */
  42622. _this.useSpecularOverAlpha = true;
  42623. /**
  42624. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  42625. */
  42626. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  42627. /**
  42628. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  42629. */
  42630. _this.useRoughnessFromMetallicTextureAlpha = true;
  42631. /**
  42632. * Specifies if the metallic texture contains the roughness information in its green channel.
  42633. */
  42634. _this.useRoughnessFromMetallicTextureGreen = false;
  42635. /**
  42636. * Specifies if the metallic texture contains the metallness information in its blue channel.
  42637. */
  42638. _this.useMetallnessFromMetallicTextureBlue = false;
  42639. /**
  42640. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  42641. */
  42642. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  42643. /**
  42644. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  42645. */
  42646. _this.useAmbientInGrayScale = false;
  42647. /**
  42648. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  42649. * The material will try to infer what glossiness each pixel should be.
  42650. */
  42651. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  42652. /**
  42653. * BJS is using an harcoded light falloff based on a manually sets up range.
  42654. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  42655. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  42656. */
  42657. _this.usePhysicalLightFalloff = true;
  42658. /**
  42659. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  42660. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  42661. */
  42662. _this.useRadianceOverAlpha = true;
  42663. /**
  42664. * Allows using an object space normal map (instead of tangent space).
  42665. */
  42666. _this.useObjectSpaceNormalMap = false;
  42667. /**
  42668. * Allows using the bump map in parallax mode.
  42669. */
  42670. _this.useParallax = false;
  42671. /**
  42672. * Allows using the bump map in parallax occlusion mode.
  42673. */
  42674. _this.useParallaxOcclusion = false;
  42675. /**
  42676. * Controls the scale bias of the parallax mode.
  42677. */
  42678. _this.parallaxScaleBias = 0.05;
  42679. /**
  42680. * If sets to true, disables all the lights affecting the material.
  42681. */
  42682. _this.disableLighting = false;
  42683. /**
  42684. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  42685. */
  42686. _this.forceIrradianceInFragment = false;
  42687. /**
  42688. * Number of Simultaneous lights allowed on the material.
  42689. */
  42690. _this.maxSimultaneousLights = 4;
  42691. /**
  42692. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42693. */
  42694. _this.invertNormalMapX = false;
  42695. /**
  42696. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42697. */
  42698. _this.invertNormalMapY = false;
  42699. /**
  42700. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42701. */
  42702. _this.twoSidedLighting = false;
  42703. /**
  42704. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42705. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  42706. */
  42707. _this.useAlphaFresnel = false;
  42708. /**
  42709. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42710. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  42711. */
  42712. _this.useLinearAlphaFresnel = false;
  42713. /**
  42714. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42715. * And/Or occlude the blended part.
  42716. */
  42717. _this.environmentBRDFTexture = null;
  42718. /**
  42719. * Force normal to face away from face.
  42720. */
  42721. _this.forceNormalForward = false;
  42722. /**
  42723. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  42724. * makes the reflect vector face the model (under horizon).
  42725. */
  42726. _this.useHorizonOcclusion = true;
  42727. /**
  42728. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  42729. * too much the area relying on ambient texture to define their ambient occlusion.
  42730. */
  42731. _this.useRadianceOcclusion = true;
  42732. /**
  42733. * If set to true, no lighting calculations will be applied.
  42734. */
  42735. _this.unlit = false;
  42736. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  42737. return _this;
  42738. }
  42739. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  42740. /**
  42741. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  42742. */
  42743. get: function () {
  42744. return this._PBRMATERIAL_OPAQUE;
  42745. },
  42746. enumerable: true,
  42747. configurable: true
  42748. });
  42749. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  42750. /**
  42751. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42752. */
  42753. get: function () {
  42754. return this._PBRMATERIAL_ALPHATEST;
  42755. },
  42756. enumerable: true,
  42757. configurable: true
  42758. });
  42759. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  42760. /**
  42761. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42762. */
  42763. get: function () {
  42764. return this._PBRMATERIAL_ALPHABLEND;
  42765. },
  42766. enumerable: true,
  42767. configurable: true
  42768. });
  42769. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  42770. /**
  42771. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42772. * They are also discarded below the alpha cutoff threshold to improve performances.
  42773. */
  42774. get: function () {
  42775. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  42776. },
  42777. enumerable: true,
  42778. configurable: true
  42779. });
  42780. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  42781. /**
  42782. * Gets the image processing configuration used either in this material.
  42783. */
  42784. get: function () {
  42785. return this._imageProcessingConfiguration;
  42786. },
  42787. /**
  42788. * Sets the Default image processing configuration used either in the this material.
  42789. *
  42790. * If sets to null, the scene one is in use.
  42791. */
  42792. set: function (value) {
  42793. this._attachImageProcessingConfiguration(value);
  42794. // Ensure the effect will be rebuilt.
  42795. this._markAllSubMeshesAsTexturesDirty();
  42796. },
  42797. enumerable: true,
  42798. configurable: true
  42799. });
  42800. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  42801. /**
  42802. * Gets wether the color curves effect is enabled.
  42803. */
  42804. get: function () {
  42805. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42806. },
  42807. /**
  42808. * Sets wether the color curves effect is enabled.
  42809. */
  42810. set: function (value) {
  42811. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42812. },
  42813. enumerable: true,
  42814. configurable: true
  42815. });
  42816. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  42817. /**
  42818. * Gets wether the color grading effect is enabled.
  42819. */
  42820. get: function () {
  42821. return this.imageProcessingConfiguration.colorGradingEnabled;
  42822. },
  42823. /**
  42824. * Gets wether the color grading effect is enabled.
  42825. */
  42826. set: function (value) {
  42827. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42828. },
  42829. enumerable: true,
  42830. configurable: true
  42831. });
  42832. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  42833. /**
  42834. * Gets wether tonemapping is enabled or not.
  42835. */
  42836. get: function () {
  42837. return this._imageProcessingConfiguration.toneMappingEnabled;
  42838. },
  42839. /**
  42840. * Sets wether tonemapping is enabled or not
  42841. */
  42842. set: function (value) {
  42843. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42844. },
  42845. enumerable: true,
  42846. configurable: true
  42847. });
  42848. ;
  42849. ;
  42850. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  42851. /**
  42852. * The camera exposure used on this material.
  42853. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42854. * This corresponds to a photographic exposure.
  42855. */
  42856. get: function () {
  42857. return this._imageProcessingConfiguration.exposure;
  42858. },
  42859. /**
  42860. * The camera exposure used on this material.
  42861. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42862. * This corresponds to a photographic exposure.
  42863. */
  42864. set: function (value) {
  42865. this._imageProcessingConfiguration.exposure = value;
  42866. },
  42867. enumerable: true,
  42868. configurable: true
  42869. });
  42870. ;
  42871. ;
  42872. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  42873. /**
  42874. * Gets The camera contrast used on this material.
  42875. */
  42876. get: function () {
  42877. return this._imageProcessingConfiguration.contrast;
  42878. },
  42879. /**
  42880. * Sets The camera contrast used on this material.
  42881. */
  42882. set: function (value) {
  42883. this._imageProcessingConfiguration.contrast = value;
  42884. },
  42885. enumerable: true,
  42886. configurable: true
  42887. });
  42888. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  42889. /**
  42890. * Gets the Color Grading 2D Lookup Texture.
  42891. */
  42892. get: function () {
  42893. return this._imageProcessingConfiguration.colorGradingTexture;
  42894. },
  42895. /**
  42896. * Sets the Color Grading 2D Lookup Texture.
  42897. */
  42898. set: function (value) {
  42899. this._imageProcessingConfiguration.colorGradingTexture = value;
  42900. },
  42901. enumerable: true,
  42902. configurable: true
  42903. });
  42904. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  42905. /**
  42906. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42907. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42908. * 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;
  42909. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42910. */
  42911. get: function () {
  42912. return this._imageProcessingConfiguration.colorCurves;
  42913. },
  42914. /**
  42915. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42916. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42917. * 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;
  42918. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42919. */
  42920. set: function (value) {
  42921. this._imageProcessingConfiguration.colorCurves = value;
  42922. },
  42923. enumerable: true,
  42924. configurable: true
  42925. });
  42926. /**
  42927. * Returns the name of this material class.
  42928. */
  42929. PBRMaterial.prototype.getClassName = function () {
  42930. return "PBRMaterial";
  42931. };
  42932. /**
  42933. * Returns an array of the actively used textures.
  42934. * @returns - Array of BaseTextures
  42935. */
  42936. PBRMaterial.prototype.getActiveTextures = function () {
  42937. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42938. if (this._albedoTexture) {
  42939. activeTextures.push(this._albedoTexture);
  42940. }
  42941. if (this._ambientTexture) {
  42942. activeTextures.push(this._ambientTexture);
  42943. }
  42944. if (this._opacityTexture) {
  42945. activeTextures.push(this._opacityTexture);
  42946. }
  42947. if (this._reflectionTexture) {
  42948. activeTextures.push(this._reflectionTexture);
  42949. }
  42950. if (this._emissiveTexture) {
  42951. activeTextures.push(this._emissiveTexture);
  42952. }
  42953. if (this._reflectivityTexture) {
  42954. activeTextures.push(this._reflectivityTexture);
  42955. }
  42956. if (this._metallicTexture) {
  42957. activeTextures.push(this._metallicTexture);
  42958. }
  42959. if (this._microSurfaceTexture) {
  42960. activeTextures.push(this._microSurfaceTexture);
  42961. }
  42962. if (this._bumpTexture) {
  42963. activeTextures.push(this._bumpTexture);
  42964. }
  42965. if (this._lightmapTexture) {
  42966. activeTextures.push(this._lightmapTexture);
  42967. }
  42968. if (this._refractionTexture) {
  42969. activeTextures.push(this._refractionTexture);
  42970. }
  42971. return activeTextures;
  42972. };
  42973. /**
  42974. * Checks to see if a texture is used in the material.
  42975. * @param texture - Base texture to use.
  42976. * @returns - Boolean specifying if a texture is used in the material.
  42977. */
  42978. PBRMaterial.prototype.hasTexture = function (texture) {
  42979. if (_super.prototype.hasTexture.call(this, texture)) {
  42980. return true;
  42981. }
  42982. if (this._albedoTexture === texture) {
  42983. return true;
  42984. }
  42985. if (this._ambientTexture === texture) {
  42986. return true;
  42987. }
  42988. if (this._opacityTexture === texture) {
  42989. return true;
  42990. }
  42991. if (this._reflectionTexture === texture) {
  42992. return true;
  42993. }
  42994. if (this._reflectivityTexture === texture) {
  42995. return true;
  42996. }
  42997. if (this._metallicTexture === texture) {
  42998. return true;
  42999. }
  43000. if (this._microSurfaceTexture === texture) {
  43001. return true;
  43002. }
  43003. if (this._bumpTexture === texture) {
  43004. return true;
  43005. }
  43006. if (this._lightmapTexture === texture) {
  43007. return true;
  43008. }
  43009. if (this._refractionTexture === texture) {
  43010. return true;
  43011. }
  43012. return false;
  43013. };
  43014. /**
  43015. * Makes a duplicate of the current material.
  43016. * @param name - name to use for the new material.
  43017. */
  43018. PBRMaterial.prototype.clone = function (name) {
  43019. var _this = this;
  43020. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  43021. clone.id = name;
  43022. clone.name = name;
  43023. return clone;
  43024. };
  43025. /**
  43026. * Serializes this PBR Material.
  43027. * @returns - An object with the serialized material.
  43028. */
  43029. PBRMaterial.prototype.serialize = function () {
  43030. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43031. serializationObject.customType = "BABYLON.PBRMaterial";
  43032. return serializationObject;
  43033. };
  43034. // Statics
  43035. /**
  43036. * Parses a PBR Material from a serialized object.
  43037. * @param source - Serialized object.
  43038. * @param scene - BJS scene instance.
  43039. * @param rootUrl - url for the scene object
  43040. * @returns - PBRMaterial
  43041. */
  43042. PBRMaterial.Parse = function (source, scene, rootUrl) {
  43043. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  43044. };
  43045. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  43046. /**
  43047. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  43048. */
  43049. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  43050. /**
  43051. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  43052. */
  43053. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  43054. /**
  43055. * 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.
  43056. * They are also discarded below the alpha cutoff threshold to improve performances.
  43057. */
  43058. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  43059. __decorate([
  43060. BABYLON.serialize(),
  43061. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43062. ], PBRMaterial.prototype, "directIntensity", void 0);
  43063. __decorate([
  43064. BABYLON.serialize(),
  43065. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43066. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  43067. __decorate([
  43068. BABYLON.serialize(),
  43069. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43070. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  43071. __decorate([
  43072. BABYLON.serialize(),
  43073. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43074. ], PBRMaterial.prototype, "specularIntensity", void 0);
  43075. __decorate([
  43076. BABYLON.serialize(),
  43077. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43078. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  43079. __decorate([
  43080. BABYLON.serializeAsTexture(),
  43081. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43082. ], PBRMaterial.prototype, "albedoTexture", void 0);
  43083. __decorate([
  43084. BABYLON.serializeAsTexture(),
  43085. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43086. ], PBRMaterial.prototype, "ambientTexture", void 0);
  43087. __decorate([
  43088. BABYLON.serialize(),
  43089. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43090. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  43091. __decorate([
  43092. BABYLON.serializeAsTexture(),
  43093. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43094. ], PBRMaterial.prototype, "opacityTexture", void 0);
  43095. __decorate([
  43096. BABYLON.serializeAsTexture(),
  43097. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43098. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  43099. __decorate([
  43100. BABYLON.serializeAsTexture(),
  43101. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43102. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  43103. __decorate([
  43104. BABYLON.serializeAsTexture(),
  43105. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43106. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  43107. __decorate([
  43108. BABYLON.serializeAsTexture(),
  43109. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43110. ], PBRMaterial.prototype, "metallicTexture", void 0);
  43111. __decorate([
  43112. BABYLON.serialize(),
  43113. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43114. ], PBRMaterial.prototype, "metallic", void 0);
  43115. __decorate([
  43116. BABYLON.serialize(),
  43117. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43118. ], PBRMaterial.prototype, "roughness", void 0);
  43119. __decorate([
  43120. BABYLON.serializeAsTexture(),
  43121. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43122. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  43123. __decorate([
  43124. BABYLON.serializeAsTexture(),
  43125. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43126. ], PBRMaterial.prototype, "bumpTexture", void 0);
  43127. __decorate([
  43128. BABYLON.serializeAsTexture(),
  43129. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  43130. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  43131. __decorate([
  43132. BABYLON.serializeAsTexture(),
  43133. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43134. ], PBRMaterial.prototype, "refractionTexture", void 0);
  43135. __decorate([
  43136. BABYLON.serializeAsColor3("ambient"),
  43137. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43138. ], PBRMaterial.prototype, "ambientColor", void 0);
  43139. __decorate([
  43140. BABYLON.serializeAsColor3("albedo"),
  43141. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43142. ], PBRMaterial.prototype, "albedoColor", void 0);
  43143. __decorate([
  43144. BABYLON.serializeAsColor3("reflectivity"),
  43145. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43146. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  43147. __decorate([
  43148. BABYLON.serializeAsColor3("reflection"),
  43149. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43150. ], PBRMaterial.prototype, "reflectionColor", void 0);
  43151. __decorate([
  43152. BABYLON.serializeAsColor3("emissive"),
  43153. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43154. ], PBRMaterial.prototype, "emissiveColor", void 0);
  43155. __decorate([
  43156. BABYLON.serialize(),
  43157. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43158. ], PBRMaterial.prototype, "microSurface", void 0);
  43159. __decorate([
  43160. BABYLON.serialize(),
  43161. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43162. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  43163. __decorate([
  43164. BABYLON.serialize(),
  43165. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43166. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  43167. __decorate([
  43168. BABYLON.serialize(),
  43169. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43170. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  43171. __decorate([
  43172. BABYLON.serialize(),
  43173. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43174. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43175. __decorate([
  43176. BABYLON.serialize(),
  43177. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43178. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  43179. __decorate([
  43180. BABYLON.serialize(),
  43181. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43182. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  43183. __decorate([
  43184. BABYLON.serialize(),
  43185. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43186. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  43187. __decorate([
  43188. BABYLON.serialize(),
  43189. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43190. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  43191. __decorate([
  43192. BABYLON.serialize(),
  43193. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43194. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  43195. __decorate([
  43196. BABYLON.serialize(),
  43197. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43198. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  43199. __decorate([
  43200. BABYLON.serialize(),
  43201. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43202. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  43203. __decorate([
  43204. BABYLON.serialize(),
  43205. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43206. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  43207. __decorate([
  43208. BABYLON.serialize(),
  43209. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43210. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  43211. __decorate([
  43212. BABYLON.serialize(),
  43213. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43214. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  43215. __decorate([
  43216. BABYLON.serialize(),
  43217. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43218. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  43219. __decorate([
  43220. BABYLON.serialize(),
  43221. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43222. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  43223. __decorate([
  43224. BABYLON.serialize(),
  43225. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43226. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  43227. __decorate([
  43228. BABYLON.serialize(),
  43229. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43230. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43231. __decorate([
  43232. BABYLON.serialize(),
  43233. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43234. ], PBRMaterial.prototype, "useParallax", void 0);
  43235. __decorate([
  43236. BABYLON.serialize(),
  43237. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43238. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  43239. __decorate([
  43240. BABYLON.serialize(),
  43241. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43242. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  43243. __decorate([
  43244. BABYLON.serialize(),
  43245. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43246. ], PBRMaterial.prototype, "disableLighting", void 0);
  43247. __decorate([
  43248. BABYLON.serialize(),
  43249. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43250. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  43251. __decorate([
  43252. BABYLON.serialize(),
  43253. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43254. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  43255. __decorate([
  43256. BABYLON.serialize(),
  43257. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43258. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  43259. __decorate([
  43260. BABYLON.serialize(),
  43261. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43262. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  43263. __decorate([
  43264. BABYLON.serialize(),
  43265. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43266. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  43267. __decorate([
  43268. BABYLON.serialize(),
  43269. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43270. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  43271. __decorate([
  43272. BABYLON.serialize(),
  43273. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43274. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  43275. __decorate([
  43276. BABYLON.serializeAsTexture(),
  43277. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43278. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  43279. __decorate([
  43280. BABYLON.serialize(),
  43281. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43282. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  43283. __decorate([
  43284. BABYLON.serialize(),
  43285. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43286. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  43287. __decorate([
  43288. BABYLON.serialize(),
  43289. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43290. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  43291. __decorate([
  43292. BABYLON.serialize(),
  43293. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43294. ], PBRMaterial.prototype, "unlit", void 0);
  43295. return PBRMaterial;
  43296. }(BABYLON.PBRBaseMaterial));
  43297. BABYLON.PBRMaterial = PBRMaterial;
  43298. })(BABYLON || (BABYLON = {}));
  43299. //# sourceMappingURL=babylon.pbrMaterial.js.map
  43300. "use strict";
  43301. var BABYLON;
  43302. (function (BABYLON) {
  43303. /**
  43304. * The PBR material of BJS following the metal roughness convention.
  43305. *
  43306. * This fits to the PBR convention in the GLTF definition:
  43307. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  43308. */
  43309. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  43310. __extends(PBRMetallicRoughnessMaterial, _super);
  43311. /**
  43312. * Instantiates a new PBRMetalRoughnessMaterial instance.
  43313. *
  43314. * @param name The material name
  43315. * @param scene The scene the material will be use in.
  43316. */
  43317. function PBRMetallicRoughnessMaterial(name, scene) {
  43318. var _this = _super.call(this, name, scene) || this;
  43319. _this._useRoughnessFromMetallicTextureAlpha = false;
  43320. _this._useRoughnessFromMetallicTextureGreen = true;
  43321. _this._useMetallnessFromMetallicTextureBlue = true;
  43322. _this.metallic = 1.0;
  43323. _this.roughness = 1.0;
  43324. return _this;
  43325. }
  43326. /**
  43327. * Return the currrent class name of the material.
  43328. */
  43329. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  43330. return "PBRMetallicRoughnessMaterial";
  43331. };
  43332. /**
  43333. * Return the active textures of the material.
  43334. */
  43335. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  43336. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43337. if (this.baseTexture) {
  43338. activeTextures.push(this.baseTexture);
  43339. }
  43340. if (this.metallicRoughnessTexture) {
  43341. activeTextures.push(this.metallicRoughnessTexture);
  43342. }
  43343. return activeTextures;
  43344. };
  43345. /**
  43346. * Checks to see if a texture is used in the material.
  43347. * @param texture - Base texture to use.
  43348. * @returns - Boolean specifying if a texture is used in the material.
  43349. */
  43350. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  43351. if (_super.prototype.hasTexture.call(this, texture)) {
  43352. return true;
  43353. }
  43354. if (this.baseTexture === texture) {
  43355. return true;
  43356. }
  43357. if (this.metallicRoughnessTexture === texture) {
  43358. return true;
  43359. }
  43360. return false;
  43361. };
  43362. /**
  43363. * Makes a duplicate of the current material.
  43364. * @param name - name to use for the new material.
  43365. */
  43366. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  43367. var _this = this;
  43368. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  43369. clone.id = name;
  43370. clone.name = name;
  43371. return clone;
  43372. };
  43373. /**
  43374. * Serialize the material to a parsable JSON object.
  43375. */
  43376. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  43377. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43378. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  43379. return serializationObject;
  43380. };
  43381. /**
  43382. * Parses a JSON object correponding to the serialize function.
  43383. */
  43384. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  43385. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  43386. };
  43387. __decorate([
  43388. BABYLON.serializeAsColor3(),
  43389. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  43390. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  43391. __decorate([
  43392. BABYLON.serializeAsTexture(),
  43393. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  43394. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  43395. __decorate([
  43396. BABYLON.serialize(),
  43397. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43398. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  43399. __decorate([
  43400. BABYLON.serialize(),
  43401. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43402. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  43403. __decorate([
  43404. BABYLON.serializeAsTexture(),
  43405. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  43406. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  43407. return PBRMetallicRoughnessMaterial;
  43408. }(BABYLON.PBRBaseSimpleMaterial));
  43409. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  43410. })(BABYLON || (BABYLON = {}));
  43411. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  43412. "use strict";
  43413. var BABYLON;
  43414. (function (BABYLON) {
  43415. /**
  43416. * The PBR material of BJS following the specular glossiness convention.
  43417. *
  43418. * This fits to the PBR convention in the GLTF definition:
  43419. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  43420. */
  43421. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  43422. __extends(PBRSpecularGlossinessMaterial, _super);
  43423. /**
  43424. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  43425. *
  43426. * @param name The material name
  43427. * @param scene The scene the material will be use in.
  43428. */
  43429. function PBRSpecularGlossinessMaterial(name, scene) {
  43430. var _this = _super.call(this, name, scene) || this;
  43431. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  43432. return _this;
  43433. }
  43434. /**
  43435. * Return the currrent class name of the material.
  43436. */
  43437. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  43438. return "PBRSpecularGlossinessMaterial";
  43439. };
  43440. /**
  43441. * Return the active textures of the material.
  43442. */
  43443. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  43444. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43445. if (this.diffuseTexture) {
  43446. activeTextures.push(this.diffuseTexture);
  43447. }
  43448. if (this.specularGlossinessTexture) {
  43449. activeTextures.push(this.specularGlossinessTexture);
  43450. }
  43451. return activeTextures;
  43452. };
  43453. /**
  43454. * Checks to see if a texture is used in the material.
  43455. * @param texture - Base texture to use.
  43456. * @returns - Boolean specifying if a texture is used in the material.
  43457. */
  43458. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  43459. if (_super.prototype.hasTexture.call(this, texture)) {
  43460. return true;
  43461. }
  43462. if (this.diffuseTexture === texture) {
  43463. return true;
  43464. }
  43465. if (this.specularGlossinessTexture === texture) {
  43466. return true;
  43467. }
  43468. return false;
  43469. };
  43470. /**
  43471. * Makes a duplicate of the current material.
  43472. * @param name - name to use for the new material.
  43473. */
  43474. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  43475. var _this = this;
  43476. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  43477. clone.id = name;
  43478. clone.name = name;
  43479. return clone;
  43480. };
  43481. /**
  43482. * Serialize the material to a parsable JSON object.
  43483. */
  43484. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  43485. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43486. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  43487. return serializationObject;
  43488. };
  43489. /**
  43490. * Parses a JSON object correponding to the serialize function.
  43491. */
  43492. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  43493. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  43494. };
  43495. __decorate([
  43496. BABYLON.serializeAsColor3("diffuse"),
  43497. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  43498. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  43499. __decorate([
  43500. BABYLON.serializeAsTexture(),
  43501. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  43502. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  43503. __decorate([
  43504. BABYLON.serializeAsColor3("specular"),
  43505. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  43506. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  43507. __decorate([
  43508. BABYLON.serialize(),
  43509. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  43510. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  43511. __decorate([
  43512. BABYLON.serializeAsTexture(),
  43513. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  43514. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  43515. return PBRSpecularGlossinessMaterial;
  43516. }(BABYLON.PBRBaseSimpleMaterial));
  43517. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  43518. })(BABYLON || (BABYLON = {}));
  43519. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  43520. "use strict";
  43521. var BABYLON;
  43522. (function (BABYLON) {
  43523. BABYLON.CameraInputTypes = {};
  43524. var CameraInputsManager = /** @class */ (function () {
  43525. function CameraInputsManager(camera) {
  43526. this.attached = {};
  43527. this.camera = camera;
  43528. this.checkInputs = function () { };
  43529. }
  43530. /**
  43531. * Add an input method to a camera.
  43532. * builtin inputs example: camera.inputs.addGamepad();
  43533. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  43534. * @param input camera input method
  43535. */
  43536. CameraInputsManager.prototype.add = function (input) {
  43537. var type = input.getSimpleName();
  43538. if (this.attached[type]) {
  43539. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  43540. return;
  43541. }
  43542. this.attached[type] = input;
  43543. input.camera = this.camera;
  43544. //for checkInputs, we are dynamically creating a function
  43545. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  43546. if (input.checkInputs) {
  43547. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43548. }
  43549. if (this.attachedElement) {
  43550. input.attachControl(this.attachedElement);
  43551. }
  43552. };
  43553. /**
  43554. * Remove a specific input method from a camera
  43555. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  43556. * @param inputToRemove camera input method
  43557. */
  43558. CameraInputsManager.prototype.remove = function (inputToRemove) {
  43559. for (var cam in this.attached) {
  43560. var input = this.attached[cam];
  43561. if (input === inputToRemove) {
  43562. input.detachControl(this.attachedElement);
  43563. input.camera = null;
  43564. delete this.attached[cam];
  43565. this.rebuildInputCheck();
  43566. }
  43567. }
  43568. };
  43569. CameraInputsManager.prototype.removeByType = function (inputType) {
  43570. for (var cam in this.attached) {
  43571. var input = this.attached[cam];
  43572. if (input.getClassName() === inputType) {
  43573. input.detachControl(this.attachedElement);
  43574. input.camera = null;
  43575. delete this.attached[cam];
  43576. this.rebuildInputCheck();
  43577. }
  43578. }
  43579. };
  43580. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  43581. var current = this.checkInputs;
  43582. return function () {
  43583. current();
  43584. fn();
  43585. };
  43586. };
  43587. CameraInputsManager.prototype.attachInput = function (input) {
  43588. if (this.attachedElement) {
  43589. input.attachControl(this.attachedElement, this.noPreventDefault);
  43590. }
  43591. };
  43592. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  43593. if (noPreventDefault === void 0) { noPreventDefault = false; }
  43594. if (this.attachedElement) {
  43595. return;
  43596. }
  43597. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  43598. this.attachedElement = element;
  43599. this.noPreventDefault = noPreventDefault;
  43600. for (var cam in this.attached) {
  43601. this.attached[cam].attachControl(element, noPreventDefault);
  43602. }
  43603. };
  43604. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  43605. if (disconnect === void 0) { disconnect = false; }
  43606. if (this.attachedElement !== element) {
  43607. return;
  43608. }
  43609. for (var cam in this.attached) {
  43610. this.attached[cam].detachControl(element);
  43611. if (disconnect) {
  43612. this.attached[cam].camera = null;
  43613. }
  43614. }
  43615. this.attachedElement = null;
  43616. };
  43617. CameraInputsManager.prototype.rebuildInputCheck = function () {
  43618. this.checkInputs = function () { };
  43619. for (var cam in this.attached) {
  43620. var input = this.attached[cam];
  43621. if (input.checkInputs) {
  43622. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43623. }
  43624. }
  43625. };
  43626. /**
  43627. * Remove all attached input methods from a camera
  43628. */
  43629. CameraInputsManager.prototype.clear = function () {
  43630. if (this.attachedElement) {
  43631. this.detachElement(this.attachedElement, true);
  43632. }
  43633. this.attached = {};
  43634. this.attachedElement = null;
  43635. this.checkInputs = function () { };
  43636. };
  43637. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  43638. var inputs = {};
  43639. for (var cam in this.attached) {
  43640. var input = this.attached[cam];
  43641. var res = BABYLON.SerializationHelper.Serialize(input);
  43642. inputs[input.getClassName()] = res;
  43643. }
  43644. serializedCamera.inputsmgr = inputs;
  43645. };
  43646. CameraInputsManager.prototype.parse = function (parsedCamera) {
  43647. var parsedInputs = parsedCamera.inputsmgr;
  43648. if (parsedInputs) {
  43649. this.clear();
  43650. for (var n in parsedInputs) {
  43651. var construct = BABYLON.CameraInputTypes[n];
  43652. if (construct) {
  43653. var parsedinput = parsedInputs[n];
  43654. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  43655. this.add(input);
  43656. }
  43657. }
  43658. }
  43659. else {
  43660. //2016-03-08 this part is for managing backward compatibility
  43661. for (var n in this.attached) {
  43662. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  43663. if (construct) {
  43664. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  43665. this.remove(this.attached[n]);
  43666. this.add(input);
  43667. }
  43668. }
  43669. }
  43670. };
  43671. return CameraInputsManager;
  43672. }());
  43673. BABYLON.CameraInputsManager = CameraInputsManager;
  43674. })(BABYLON || (BABYLON = {}));
  43675. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  43676. "use strict";
  43677. var BABYLON;
  43678. (function (BABYLON) {
  43679. var TargetCamera = /** @class */ (function (_super) {
  43680. __extends(TargetCamera, _super);
  43681. function TargetCamera(name, position, scene) {
  43682. var _this = _super.call(this, name, position, scene) || this;
  43683. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43684. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  43685. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  43686. _this.speed = 2.0;
  43687. _this.noRotationConstraint = false;
  43688. _this.lockedTarget = null;
  43689. _this._currentTarget = BABYLON.Vector3.Zero();
  43690. _this._viewMatrix = BABYLON.Matrix.Zero();
  43691. _this._camMatrix = BABYLON.Matrix.Zero();
  43692. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  43693. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  43694. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  43695. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  43696. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  43697. _this._lookAtTemp = BABYLON.Matrix.Zero();
  43698. _this._tempMatrix = BABYLON.Matrix.Zero();
  43699. return _this;
  43700. }
  43701. TargetCamera.prototype.getFrontPosition = function (distance) {
  43702. this.getWorldMatrix();
  43703. var direction = this.getTarget().subtract(this.position);
  43704. direction.normalize();
  43705. direction.scaleInPlace(distance);
  43706. return this.globalPosition.add(direction);
  43707. };
  43708. TargetCamera.prototype._getLockedTargetPosition = function () {
  43709. if (!this.lockedTarget) {
  43710. return null;
  43711. }
  43712. if (this.lockedTarget.absolutePosition) {
  43713. this.lockedTarget.computeWorldMatrix();
  43714. }
  43715. return this.lockedTarget.absolutePosition || this.lockedTarget;
  43716. };
  43717. TargetCamera.prototype.storeState = function () {
  43718. this._storedPosition = this.position.clone();
  43719. this._storedRotation = this.rotation.clone();
  43720. if (this.rotationQuaternion) {
  43721. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  43722. }
  43723. return _super.prototype.storeState.call(this);
  43724. };
  43725. /**
  43726. * Restored camera state. You must call storeState() first
  43727. */
  43728. TargetCamera.prototype._restoreStateValues = function () {
  43729. if (!_super.prototype._restoreStateValues.call(this)) {
  43730. return false;
  43731. }
  43732. this.position = this._storedPosition.clone();
  43733. this.rotation = this._storedRotation.clone();
  43734. if (this.rotationQuaternion) {
  43735. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  43736. }
  43737. this.cameraDirection.copyFromFloats(0, 0, 0);
  43738. this.cameraRotation.copyFromFloats(0, 0);
  43739. return true;
  43740. };
  43741. // Cache
  43742. TargetCamera.prototype._initCache = function () {
  43743. _super.prototype._initCache.call(this);
  43744. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43745. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43746. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43747. };
  43748. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  43749. if (!ignoreParentClass) {
  43750. _super.prototype._updateCache.call(this);
  43751. }
  43752. var lockedTargetPosition = this._getLockedTargetPosition();
  43753. if (!lockedTargetPosition) {
  43754. this._cache.lockedTarget = null;
  43755. }
  43756. else {
  43757. if (!this._cache.lockedTarget) {
  43758. this._cache.lockedTarget = lockedTargetPosition.clone();
  43759. }
  43760. else {
  43761. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  43762. }
  43763. }
  43764. this._cache.rotation.copyFrom(this.rotation);
  43765. if (this.rotationQuaternion)
  43766. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43767. };
  43768. // Synchronized
  43769. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  43770. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  43771. return false;
  43772. }
  43773. var lockedTargetPosition = this._getLockedTargetPosition();
  43774. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  43775. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  43776. };
  43777. // Methods
  43778. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  43779. var engine = this.getEngine();
  43780. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  43781. };
  43782. // Target
  43783. TargetCamera.prototype.setTarget = function (target) {
  43784. this.upVector.normalize();
  43785. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  43786. this._camMatrix.invert();
  43787. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  43788. var vDir = target.subtract(this.position);
  43789. if (vDir.x >= 0.0) {
  43790. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  43791. }
  43792. else {
  43793. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  43794. }
  43795. this.rotation.z = 0;
  43796. if (isNaN(this.rotation.x)) {
  43797. this.rotation.x = 0;
  43798. }
  43799. if (isNaN(this.rotation.y)) {
  43800. this.rotation.y = 0;
  43801. }
  43802. if (isNaN(this.rotation.z)) {
  43803. this.rotation.z = 0;
  43804. }
  43805. if (this.rotationQuaternion) {
  43806. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43807. }
  43808. };
  43809. /**
  43810. * Return the current target position of the camera. This value is expressed in local space.
  43811. */
  43812. TargetCamera.prototype.getTarget = function () {
  43813. return this._currentTarget;
  43814. };
  43815. TargetCamera.prototype._decideIfNeedsToMove = function () {
  43816. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43817. };
  43818. TargetCamera.prototype._updatePosition = function () {
  43819. if (this.parent) {
  43820. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  43821. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  43822. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  43823. return;
  43824. }
  43825. this.position.addInPlace(this.cameraDirection);
  43826. };
  43827. TargetCamera.prototype._checkInputs = function () {
  43828. var needToMove = this._decideIfNeedsToMove();
  43829. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  43830. // Move
  43831. if (needToMove) {
  43832. this._updatePosition();
  43833. }
  43834. // Rotate
  43835. if (needToRotate) {
  43836. this.rotation.x += this.cameraRotation.x;
  43837. this.rotation.y += this.cameraRotation.y;
  43838. //rotate, if quaternion is set and rotation was used
  43839. if (this.rotationQuaternion) {
  43840. var len = this.rotation.lengthSquared();
  43841. if (len) {
  43842. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43843. }
  43844. }
  43845. if (!this.noRotationConstraint) {
  43846. var limit = (Math.PI / 2) * 0.95;
  43847. if (this.rotation.x > limit)
  43848. this.rotation.x = limit;
  43849. if (this.rotation.x < -limit)
  43850. this.rotation.x = -limit;
  43851. }
  43852. }
  43853. // Inertia
  43854. if (needToMove) {
  43855. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  43856. this.cameraDirection.x = 0;
  43857. }
  43858. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  43859. this.cameraDirection.y = 0;
  43860. }
  43861. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  43862. this.cameraDirection.z = 0;
  43863. }
  43864. this.cameraDirection.scaleInPlace(this.inertia);
  43865. }
  43866. if (needToRotate) {
  43867. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  43868. this.cameraRotation.x = 0;
  43869. }
  43870. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  43871. this.cameraRotation.y = 0;
  43872. }
  43873. this.cameraRotation.scaleInPlace(this.inertia);
  43874. }
  43875. _super.prototype._checkInputs.call(this);
  43876. };
  43877. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  43878. if (this.rotationQuaternion) {
  43879. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  43880. }
  43881. else {
  43882. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  43883. }
  43884. //update the up vector!
  43885. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  43886. };
  43887. TargetCamera.prototype._getViewMatrix = function () {
  43888. if (this.lockedTarget) {
  43889. this.setTarget(this._getLockedTargetPosition());
  43890. }
  43891. // Compute
  43892. this._updateCameraRotationMatrix();
  43893. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  43894. // Computing target and final matrix
  43895. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  43896. if (this.getScene().useRightHandedSystem) {
  43897. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43898. }
  43899. else {
  43900. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43901. }
  43902. return this._viewMatrix;
  43903. };
  43904. /**
  43905. * @override
  43906. * Override Camera.createRigCamera
  43907. */
  43908. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  43909. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  43910. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  43911. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  43912. if (!this.rotationQuaternion) {
  43913. this.rotationQuaternion = new BABYLON.Quaternion();
  43914. }
  43915. rigCamera._cameraRigParams = {};
  43916. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  43917. }
  43918. return rigCamera;
  43919. }
  43920. return null;
  43921. };
  43922. /**
  43923. * @override
  43924. * Override Camera._updateRigCameras
  43925. */
  43926. TargetCamera.prototype._updateRigCameras = function () {
  43927. var camLeft = this._rigCameras[0];
  43928. var camRight = this._rigCameras[1];
  43929. switch (this.cameraRigMode) {
  43930. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  43931. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  43932. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  43933. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  43934. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  43935. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  43936. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  43937. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  43938. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  43939. camLeft.setTarget(this.getTarget());
  43940. camRight.setTarget(this.getTarget());
  43941. break;
  43942. case BABYLON.Camera.RIG_MODE_VR:
  43943. if (camLeft.rotationQuaternion) {
  43944. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43945. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43946. }
  43947. else {
  43948. camLeft.rotation.copyFrom(this.rotation);
  43949. camRight.rotation.copyFrom(this.rotation);
  43950. }
  43951. camLeft.position.copyFrom(this.position);
  43952. camRight.position.copyFrom(this.position);
  43953. break;
  43954. }
  43955. _super.prototype._updateRigCameras.call(this);
  43956. };
  43957. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  43958. if (!this._rigCamTransformMatrix) {
  43959. this._rigCamTransformMatrix = new BABYLON.Matrix();
  43960. }
  43961. var target = this.getTarget();
  43962. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  43963. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  43964. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  43965. };
  43966. TargetCamera.prototype.getClassName = function () {
  43967. return "TargetCamera";
  43968. };
  43969. __decorate([
  43970. BABYLON.serializeAsVector3()
  43971. ], TargetCamera.prototype, "rotation", void 0);
  43972. __decorate([
  43973. BABYLON.serialize()
  43974. ], TargetCamera.prototype, "speed", void 0);
  43975. __decorate([
  43976. BABYLON.serializeAsMeshReference("lockedTargetId")
  43977. ], TargetCamera.prototype, "lockedTarget", void 0);
  43978. return TargetCamera;
  43979. }(BABYLON.Camera));
  43980. BABYLON.TargetCamera = TargetCamera;
  43981. })(BABYLON || (BABYLON = {}));
  43982. //# sourceMappingURL=babylon.targetCamera.js.map
  43983. "use strict";
  43984. var BABYLON;
  43985. (function (BABYLON) {
  43986. var FreeCameraMouseInput = /** @class */ (function () {
  43987. function FreeCameraMouseInput(touchEnabled) {
  43988. if (touchEnabled === void 0) { touchEnabled = true; }
  43989. this.touchEnabled = touchEnabled;
  43990. this.buttons = [0, 1, 2];
  43991. this.angularSensibility = 2000.0;
  43992. this.previousPosition = null;
  43993. }
  43994. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  43995. var _this = this;
  43996. var engine = this.camera.getEngine();
  43997. if (!this._pointerInput) {
  43998. this._pointerInput = function (p, s) {
  43999. var evt = p.event;
  44000. if (engine.isInVRExclusivePointerMode) {
  44001. return;
  44002. }
  44003. if (!_this.touchEnabled && evt.pointerType === "touch") {
  44004. return;
  44005. }
  44006. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  44007. return;
  44008. }
  44009. var srcElement = (evt.srcElement || evt.target);
  44010. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  44011. try {
  44012. srcElement.setPointerCapture(evt.pointerId);
  44013. }
  44014. catch (e) {
  44015. //Nothing to do with the error. Execution will continue.
  44016. }
  44017. _this.previousPosition = {
  44018. x: evt.clientX,
  44019. y: evt.clientY
  44020. };
  44021. if (!noPreventDefault) {
  44022. evt.preventDefault();
  44023. element.focus();
  44024. }
  44025. }
  44026. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  44027. try {
  44028. srcElement.releasePointerCapture(evt.pointerId);
  44029. }
  44030. catch (e) {
  44031. //Nothing to do with the error.
  44032. }
  44033. _this.previousPosition = null;
  44034. if (!noPreventDefault) {
  44035. evt.preventDefault();
  44036. }
  44037. }
  44038. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44039. if (!_this.previousPosition || engine.isPointerLock) {
  44040. return;
  44041. }
  44042. var offsetX = evt.clientX - _this.previousPosition.x;
  44043. var offsetY = evt.clientY - _this.previousPosition.y;
  44044. if (_this.camera.getScene().useRightHandedSystem) {
  44045. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  44046. }
  44047. else {
  44048. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  44049. }
  44050. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  44051. _this.previousPosition = {
  44052. x: evt.clientX,
  44053. y: evt.clientY
  44054. };
  44055. if (!noPreventDefault) {
  44056. evt.preventDefault();
  44057. }
  44058. }
  44059. };
  44060. }
  44061. this._onMouseMove = function (evt) {
  44062. if (!engine.isPointerLock) {
  44063. return;
  44064. }
  44065. if (engine.isInVRExclusivePointerMode) {
  44066. return;
  44067. }
  44068. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44069. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44070. if (_this.camera.getScene().useRightHandedSystem) {
  44071. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  44072. }
  44073. else {
  44074. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  44075. }
  44076. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  44077. _this.previousPosition = null;
  44078. if (!noPreventDefault) {
  44079. evt.preventDefault();
  44080. }
  44081. };
  44082. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  44083. element.addEventListener("mousemove", this._onMouseMove, false);
  44084. };
  44085. FreeCameraMouseInput.prototype.detachControl = function (element) {
  44086. if (this._observer && element) {
  44087. this.camera.getScene().onPointerObservable.remove(this._observer);
  44088. if (this._onMouseMove) {
  44089. element.removeEventListener("mousemove", this._onMouseMove);
  44090. }
  44091. this._observer = null;
  44092. this._onMouseMove = null;
  44093. this.previousPosition = null;
  44094. }
  44095. };
  44096. FreeCameraMouseInput.prototype.getClassName = function () {
  44097. return "FreeCameraMouseInput";
  44098. };
  44099. FreeCameraMouseInput.prototype.getSimpleName = function () {
  44100. return "mouse";
  44101. };
  44102. __decorate([
  44103. BABYLON.serialize()
  44104. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  44105. __decorate([
  44106. BABYLON.serialize()
  44107. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  44108. return FreeCameraMouseInput;
  44109. }());
  44110. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  44111. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  44112. })(BABYLON || (BABYLON = {}));
  44113. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  44114. "use strict";
  44115. var BABYLON;
  44116. (function (BABYLON) {
  44117. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  44118. function FreeCameraKeyboardMoveInput() {
  44119. this._keys = new Array();
  44120. this.keysUp = [38];
  44121. this.keysDown = [40];
  44122. this.keysLeft = [37];
  44123. this.keysRight = [39];
  44124. }
  44125. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  44126. var _this = this;
  44127. if (this._onCanvasBlurObserver) {
  44128. return;
  44129. }
  44130. this._scene = this.camera.getScene();
  44131. this._engine = this._scene.getEngine();
  44132. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  44133. _this._keys = [];
  44134. });
  44135. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  44136. var evt = info.event;
  44137. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  44138. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44139. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44140. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44141. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  44142. var index = _this._keys.indexOf(evt.keyCode);
  44143. if (index === -1) {
  44144. _this._keys.push(evt.keyCode);
  44145. }
  44146. if (!noPreventDefault) {
  44147. evt.preventDefault();
  44148. }
  44149. }
  44150. }
  44151. else {
  44152. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44153. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44154. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44155. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  44156. var index = _this._keys.indexOf(evt.keyCode);
  44157. if (index >= 0) {
  44158. _this._keys.splice(index, 1);
  44159. }
  44160. if (!noPreventDefault) {
  44161. evt.preventDefault();
  44162. }
  44163. }
  44164. }
  44165. });
  44166. };
  44167. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  44168. if (this._scene) {
  44169. if (this._onKeyboardObserver) {
  44170. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  44171. }
  44172. if (this._onCanvasBlurObserver) {
  44173. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  44174. }
  44175. this._onKeyboardObserver = null;
  44176. this._onCanvasBlurObserver = null;
  44177. }
  44178. this._keys = [];
  44179. };
  44180. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44181. if (this._onKeyboardObserver) {
  44182. var camera = this.camera;
  44183. // Keyboard
  44184. for (var index = 0; index < this._keys.length; index++) {
  44185. var keyCode = this._keys[index];
  44186. var speed = camera._computeLocalCameraSpeed();
  44187. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44188. camera._localDirection.copyFromFloats(-speed, 0, 0);
  44189. }
  44190. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44191. camera._localDirection.copyFromFloats(0, 0, speed);
  44192. }
  44193. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44194. camera._localDirection.copyFromFloats(speed, 0, 0);
  44195. }
  44196. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44197. camera._localDirection.copyFromFloats(0, 0, -speed);
  44198. }
  44199. if (camera.getScene().useRightHandedSystem) {
  44200. camera._localDirection.z *= -1;
  44201. }
  44202. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  44203. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  44204. camera.cameraDirection.addInPlace(camera._transformedDirection);
  44205. }
  44206. }
  44207. };
  44208. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  44209. return "FreeCameraKeyboardMoveInput";
  44210. };
  44211. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  44212. this._keys = [];
  44213. };
  44214. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44215. return "keyboard";
  44216. };
  44217. __decorate([
  44218. BABYLON.serialize()
  44219. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44220. __decorate([
  44221. BABYLON.serialize()
  44222. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44223. __decorate([
  44224. BABYLON.serialize()
  44225. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44226. __decorate([
  44227. BABYLON.serialize()
  44228. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44229. return FreeCameraKeyboardMoveInput;
  44230. }());
  44231. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  44232. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  44233. })(BABYLON || (BABYLON = {}));
  44234. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  44235. "use strict";
  44236. var BABYLON;
  44237. (function (BABYLON) {
  44238. var FreeCameraInputsManager = /** @class */ (function (_super) {
  44239. __extends(FreeCameraInputsManager, _super);
  44240. function FreeCameraInputsManager(camera) {
  44241. return _super.call(this, camera) || this;
  44242. }
  44243. FreeCameraInputsManager.prototype.addKeyboard = function () {
  44244. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  44245. return this;
  44246. };
  44247. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  44248. if (touchEnabled === void 0) { touchEnabled = true; }
  44249. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  44250. return this;
  44251. };
  44252. FreeCameraInputsManager.prototype.addGamepad = function () {
  44253. this.add(new BABYLON.FreeCameraGamepadInput());
  44254. return this;
  44255. };
  44256. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  44257. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  44258. return this;
  44259. };
  44260. FreeCameraInputsManager.prototype.addTouch = function () {
  44261. this.add(new BABYLON.FreeCameraTouchInput());
  44262. return this;
  44263. };
  44264. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  44265. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  44266. return this;
  44267. };
  44268. return FreeCameraInputsManager;
  44269. }(BABYLON.CameraInputsManager));
  44270. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  44271. })(BABYLON || (BABYLON = {}));
  44272. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  44273. "use strict";
  44274. var BABYLON;
  44275. (function (BABYLON) {
  44276. var FreeCamera = /** @class */ (function (_super) {
  44277. __extends(FreeCamera, _super);
  44278. function FreeCamera(name, position, scene) {
  44279. var _this = _super.call(this, name, position, scene) || this;
  44280. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  44281. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  44282. _this.checkCollisions = false;
  44283. _this.applyGravity = false;
  44284. _this._needMoveForGravity = false;
  44285. _this._oldPosition = BABYLON.Vector3.Zero();
  44286. _this._diffPosition = BABYLON.Vector3.Zero();
  44287. _this._newPosition = BABYLON.Vector3.Zero();
  44288. // Collisions
  44289. _this._collisionMask = -1;
  44290. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44291. if (collidedMesh === void 0) { collidedMesh = null; }
  44292. //TODO move this to the collision coordinator!
  44293. if (_this.getScene().workerCollisions)
  44294. newPosition.multiplyInPlace(_this._collider._radius);
  44295. var updatePosition = function (newPos) {
  44296. _this._newPosition.copyFrom(newPos);
  44297. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  44298. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  44299. _this.position.addInPlace(_this._diffPosition);
  44300. if (_this.onCollide && collidedMesh) {
  44301. _this.onCollide(collidedMesh);
  44302. }
  44303. }
  44304. };
  44305. updatePosition(newPosition);
  44306. };
  44307. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  44308. _this.inputs.addKeyboard().addMouse();
  44309. return _this;
  44310. }
  44311. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  44312. //-- begin properties for backward compatibility for inputs
  44313. /**
  44314. * Gets the input sensibility for a mouse input. (default is 2000.0)
  44315. * Higher values reduce sensitivity.
  44316. */
  44317. get: function () {
  44318. var mouse = this.inputs.attached["mouse"];
  44319. if (mouse)
  44320. return mouse.angularSensibility;
  44321. return 0;
  44322. },
  44323. /**
  44324. * Sets the input sensibility for a mouse input. (default is 2000.0)
  44325. * Higher values reduce sensitivity.
  44326. */
  44327. set: function (value) {
  44328. var mouse = this.inputs.attached["mouse"];
  44329. if (mouse)
  44330. mouse.angularSensibility = value;
  44331. },
  44332. enumerable: true,
  44333. configurable: true
  44334. });
  44335. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  44336. get: function () {
  44337. var keyboard = this.inputs.attached["keyboard"];
  44338. if (keyboard)
  44339. return keyboard.keysUp;
  44340. return [];
  44341. },
  44342. set: function (value) {
  44343. var keyboard = this.inputs.attached["keyboard"];
  44344. if (keyboard)
  44345. keyboard.keysUp = value;
  44346. },
  44347. enumerable: true,
  44348. configurable: true
  44349. });
  44350. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  44351. get: function () {
  44352. var keyboard = this.inputs.attached["keyboard"];
  44353. if (keyboard)
  44354. return keyboard.keysDown;
  44355. return [];
  44356. },
  44357. set: function (value) {
  44358. var keyboard = this.inputs.attached["keyboard"];
  44359. if (keyboard)
  44360. keyboard.keysDown = value;
  44361. },
  44362. enumerable: true,
  44363. configurable: true
  44364. });
  44365. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  44366. get: function () {
  44367. var keyboard = this.inputs.attached["keyboard"];
  44368. if (keyboard)
  44369. return keyboard.keysLeft;
  44370. return [];
  44371. },
  44372. set: function (value) {
  44373. var keyboard = this.inputs.attached["keyboard"];
  44374. if (keyboard)
  44375. keyboard.keysLeft = value;
  44376. },
  44377. enumerable: true,
  44378. configurable: true
  44379. });
  44380. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  44381. get: function () {
  44382. var keyboard = this.inputs.attached["keyboard"];
  44383. if (keyboard)
  44384. return keyboard.keysRight;
  44385. return [];
  44386. },
  44387. set: function (value) {
  44388. var keyboard = this.inputs.attached["keyboard"];
  44389. if (keyboard)
  44390. keyboard.keysRight = value;
  44391. },
  44392. enumerable: true,
  44393. configurable: true
  44394. });
  44395. // Controls
  44396. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  44397. this.inputs.attachElement(element, noPreventDefault);
  44398. };
  44399. FreeCamera.prototype.detachControl = function (element) {
  44400. this.inputs.detachElement(element);
  44401. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  44402. this.cameraRotation = new BABYLON.Vector2(0, 0);
  44403. };
  44404. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  44405. get: function () {
  44406. return this._collisionMask;
  44407. },
  44408. set: function (mask) {
  44409. this._collisionMask = !isNaN(mask) ? mask : -1;
  44410. },
  44411. enumerable: true,
  44412. configurable: true
  44413. });
  44414. FreeCamera.prototype._collideWithWorld = function (displacement) {
  44415. var globalPosition;
  44416. if (this.parent) {
  44417. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  44418. }
  44419. else {
  44420. globalPosition = this.position;
  44421. }
  44422. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  44423. this._oldPosition.addInPlace(this.ellipsoidOffset);
  44424. if (!this._collider) {
  44425. this._collider = new BABYLON.Collider();
  44426. }
  44427. this._collider._radius = this.ellipsoid;
  44428. this._collider.collisionMask = this._collisionMask;
  44429. //no need for clone, as long as gravity is not on.
  44430. var actualDisplacement = displacement;
  44431. //add gravity to the direction to prevent the dual-collision checking
  44432. if (this.applyGravity) {
  44433. //this prevents mending with cameraDirection, a global variable of the free camera class.
  44434. actualDisplacement = displacement.add(this.getScene().gravity);
  44435. }
  44436. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  44437. };
  44438. FreeCamera.prototype._checkInputs = function () {
  44439. if (!this._localDirection) {
  44440. this._localDirection = BABYLON.Vector3.Zero();
  44441. this._transformedDirection = BABYLON.Vector3.Zero();
  44442. }
  44443. this.inputs.checkInputs();
  44444. _super.prototype._checkInputs.call(this);
  44445. };
  44446. FreeCamera.prototype._decideIfNeedsToMove = function () {
  44447. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  44448. };
  44449. FreeCamera.prototype._updatePosition = function () {
  44450. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  44451. this._collideWithWorld(this.cameraDirection);
  44452. }
  44453. else {
  44454. _super.prototype._updatePosition.call(this);
  44455. }
  44456. };
  44457. FreeCamera.prototype.dispose = function () {
  44458. this.inputs.clear();
  44459. _super.prototype.dispose.call(this);
  44460. };
  44461. FreeCamera.prototype.getClassName = function () {
  44462. return "FreeCamera";
  44463. };
  44464. __decorate([
  44465. BABYLON.serializeAsVector3()
  44466. ], FreeCamera.prototype, "ellipsoid", void 0);
  44467. __decorate([
  44468. BABYLON.serializeAsVector3()
  44469. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  44470. __decorate([
  44471. BABYLON.serialize()
  44472. ], FreeCamera.prototype, "checkCollisions", void 0);
  44473. __decorate([
  44474. BABYLON.serialize()
  44475. ], FreeCamera.prototype, "applyGravity", void 0);
  44476. return FreeCamera;
  44477. }(BABYLON.TargetCamera));
  44478. BABYLON.FreeCamera = FreeCamera;
  44479. })(BABYLON || (BABYLON = {}));
  44480. //# sourceMappingURL=babylon.freeCamera.js.map
  44481. "use strict";
  44482. var BABYLON;
  44483. (function (BABYLON) {
  44484. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  44485. function ArcRotateCameraKeyboardMoveInput() {
  44486. this._keys = new Array();
  44487. this.keysUp = [38];
  44488. this.keysDown = [40];
  44489. this.keysLeft = [37];
  44490. this.keysRight = [39];
  44491. this.keysReset = [220];
  44492. this.panningSensibility = 50.0;
  44493. this.zoomingSensibility = 25.0;
  44494. this.useAltToZoom = true;
  44495. }
  44496. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  44497. var _this = this;
  44498. if (this._onCanvasBlurObserver) {
  44499. return;
  44500. }
  44501. this._scene = this.camera.getScene();
  44502. this._engine = this._scene.getEngine();
  44503. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  44504. _this._keys = [];
  44505. });
  44506. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  44507. var evt = info.event;
  44508. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  44509. _this._ctrlPressed = evt.ctrlKey;
  44510. _this._altPressed = evt.altKey;
  44511. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44512. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44513. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44514. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44515. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44516. var index = _this._keys.indexOf(evt.keyCode);
  44517. if (index === -1) {
  44518. _this._keys.push(evt.keyCode);
  44519. }
  44520. if (evt.preventDefault) {
  44521. if (!noPreventDefault) {
  44522. evt.preventDefault();
  44523. }
  44524. }
  44525. }
  44526. }
  44527. else {
  44528. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44529. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44530. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44531. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44532. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44533. var index = _this._keys.indexOf(evt.keyCode);
  44534. if (index >= 0) {
  44535. _this._keys.splice(index, 1);
  44536. }
  44537. if (evt.preventDefault) {
  44538. if (!noPreventDefault) {
  44539. evt.preventDefault();
  44540. }
  44541. }
  44542. }
  44543. }
  44544. });
  44545. };
  44546. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  44547. if (this._scene) {
  44548. if (this._onKeyboardObserver) {
  44549. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  44550. }
  44551. if (this._onCanvasBlurObserver) {
  44552. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  44553. }
  44554. this._onKeyboardObserver = null;
  44555. this._onCanvasBlurObserver = null;
  44556. }
  44557. this._keys = [];
  44558. };
  44559. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44560. if (this._onKeyboardObserver) {
  44561. var camera = this.camera;
  44562. for (var index = 0; index < this._keys.length; index++) {
  44563. var keyCode = this._keys[index];
  44564. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44565. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44566. camera.inertialPanningX -= 1 / this.panningSensibility;
  44567. }
  44568. else {
  44569. camera.inertialAlphaOffset -= 0.01;
  44570. }
  44571. }
  44572. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44573. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44574. camera.inertialPanningY += 1 / this.panningSensibility;
  44575. }
  44576. else if (this._altPressed && this.useAltToZoom) {
  44577. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  44578. }
  44579. else {
  44580. camera.inertialBetaOffset -= 0.01;
  44581. }
  44582. }
  44583. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44584. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44585. camera.inertialPanningX += 1 / this.panningSensibility;
  44586. }
  44587. else {
  44588. camera.inertialAlphaOffset += 0.01;
  44589. }
  44590. }
  44591. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44592. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44593. camera.inertialPanningY -= 1 / this.panningSensibility;
  44594. }
  44595. else if (this._altPressed && this.useAltToZoom) {
  44596. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  44597. }
  44598. else {
  44599. camera.inertialBetaOffset += 0.01;
  44600. }
  44601. }
  44602. else if (this.keysReset.indexOf(keyCode) !== -1) {
  44603. camera.restoreState();
  44604. }
  44605. }
  44606. }
  44607. };
  44608. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  44609. return "ArcRotateCameraKeyboardMoveInput";
  44610. };
  44611. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44612. return "keyboard";
  44613. };
  44614. __decorate([
  44615. BABYLON.serialize()
  44616. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44617. __decorate([
  44618. BABYLON.serialize()
  44619. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44620. __decorate([
  44621. BABYLON.serialize()
  44622. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44623. __decorate([
  44624. BABYLON.serialize()
  44625. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44626. __decorate([
  44627. BABYLON.serialize()
  44628. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  44629. __decorate([
  44630. BABYLON.serialize()
  44631. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  44632. __decorate([
  44633. BABYLON.serialize()
  44634. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  44635. __decorate([
  44636. BABYLON.serialize()
  44637. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  44638. return ArcRotateCameraKeyboardMoveInput;
  44639. }());
  44640. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  44641. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  44642. })(BABYLON || (BABYLON = {}));
  44643. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  44644. "use strict";
  44645. var BABYLON;
  44646. (function (BABYLON) {
  44647. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  44648. function ArcRotateCameraMouseWheelInput() {
  44649. this.wheelPrecision = 3.0;
  44650. /**
  44651. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  44652. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  44653. */
  44654. this.wheelDeltaPercentage = 0;
  44655. }
  44656. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  44657. var _this = this;
  44658. this._wheel = function (p, s) {
  44659. //sanity check - this should be a PointerWheel event.
  44660. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  44661. return;
  44662. var event = p.event;
  44663. var delta = 0;
  44664. if (event.wheelDelta) {
  44665. if (_this.wheelDeltaPercentage) {
  44666. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  44667. if (event.wheelDelta > 0) {
  44668. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  44669. }
  44670. else {
  44671. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  44672. }
  44673. }
  44674. else {
  44675. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  44676. }
  44677. }
  44678. else if (event.detail) {
  44679. delta = -event.detail / _this.wheelPrecision;
  44680. }
  44681. if (delta)
  44682. _this.camera.inertialRadiusOffset += delta;
  44683. if (event.preventDefault) {
  44684. if (!noPreventDefault) {
  44685. event.preventDefault();
  44686. }
  44687. }
  44688. };
  44689. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  44690. };
  44691. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  44692. if (this._observer && element) {
  44693. this.camera.getScene().onPointerObservable.remove(this._observer);
  44694. this._observer = null;
  44695. this._wheel = null;
  44696. }
  44697. };
  44698. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  44699. return "ArcRotateCameraMouseWheelInput";
  44700. };
  44701. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  44702. return "mousewheel";
  44703. };
  44704. __decorate([
  44705. BABYLON.serialize()
  44706. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  44707. __decorate([
  44708. BABYLON.serialize()
  44709. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  44710. return ArcRotateCameraMouseWheelInput;
  44711. }());
  44712. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  44713. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  44714. })(BABYLON || (BABYLON = {}));
  44715. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  44716. "use strict";
  44717. var BABYLON;
  44718. (function (BABYLON) {
  44719. var ArcRotateCameraPointersInput = /** @class */ (function () {
  44720. function ArcRotateCameraPointersInput() {
  44721. this.buttons = [0, 1, 2];
  44722. this.angularSensibilityX = 1000.0;
  44723. this.angularSensibilityY = 1000.0;
  44724. this.pinchPrecision = 12.0;
  44725. /**
  44726. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  44727. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  44728. */
  44729. this.pinchDeltaPercentage = 0;
  44730. this.panningSensibility = 1000.0;
  44731. this.multiTouchPanning = true;
  44732. this.multiTouchPanAndZoom = true;
  44733. this._isPanClick = false;
  44734. this.pinchInwards = true;
  44735. }
  44736. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  44737. var _this = this;
  44738. var engine = this.camera.getEngine();
  44739. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  44740. var pointA = null;
  44741. var pointB = null;
  44742. var previousPinchSquaredDistance = 0;
  44743. var initialDistance = 0;
  44744. var twoFingerActivityCount = 0;
  44745. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  44746. this._pointerInput = function (p, s) {
  44747. var evt = p.event;
  44748. var isTouch = p.event.pointerType === "touch";
  44749. if (engine.isInVRExclusivePointerMode) {
  44750. return;
  44751. }
  44752. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  44753. return;
  44754. }
  44755. var srcElement = (evt.srcElement || evt.target);
  44756. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  44757. try {
  44758. srcElement.setPointerCapture(evt.pointerId);
  44759. }
  44760. catch (e) {
  44761. //Nothing to do with the error. Execution will continue.
  44762. }
  44763. // Manage panning with pan button click
  44764. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  44765. // manage pointers
  44766. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  44767. if (pointA === null) {
  44768. pointA = cacheSoloPointer;
  44769. }
  44770. else if (pointB === null) {
  44771. pointB = cacheSoloPointer;
  44772. }
  44773. if (!noPreventDefault) {
  44774. evt.preventDefault();
  44775. element.focus();
  44776. }
  44777. }
  44778. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  44779. _this.camera.restoreState();
  44780. }
  44781. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  44782. try {
  44783. srcElement.releasePointerCapture(evt.pointerId);
  44784. }
  44785. catch (e) {
  44786. //Nothing to do with the error.
  44787. }
  44788. cacheSoloPointer = null;
  44789. previousPinchSquaredDistance = 0;
  44790. previousMultiTouchPanPosition.isPaning = false;
  44791. previousMultiTouchPanPosition.isPinching = false;
  44792. twoFingerActivityCount = 0;
  44793. initialDistance = 0;
  44794. if (!isTouch) {
  44795. pointB = null; // Mouse and pen are mono pointer
  44796. }
  44797. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  44798. //but emptying completly pointers collection is required to fix a bug on iPhone :
  44799. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  44800. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  44801. if (engine.badOS) {
  44802. pointA = pointB = null;
  44803. }
  44804. else {
  44805. //only remove the impacted pointer in case of multitouch allowing on most
  44806. //platforms switching from rotate to zoom and pan seamlessly.
  44807. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  44808. pointA = pointB;
  44809. pointB = null;
  44810. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44811. }
  44812. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  44813. pointB = null;
  44814. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44815. }
  44816. else {
  44817. pointA = pointB = null;
  44818. }
  44819. }
  44820. if (!noPreventDefault) {
  44821. evt.preventDefault();
  44822. }
  44823. }
  44824. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44825. if (!noPreventDefault) {
  44826. evt.preventDefault();
  44827. }
  44828. // One button down
  44829. if (pointA && pointB === null && cacheSoloPointer) {
  44830. if (_this.panningSensibility !== 0 &&
  44831. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  44832. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  44833. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  44834. }
  44835. else {
  44836. var offsetX = evt.clientX - cacheSoloPointer.x;
  44837. var offsetY = evt.clientY - cacheSoloPointer.y;
  44838. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44839. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44840. }
  44841. cacheSoloPointer.x = evt.clientX;
  44842. cacheSoloPointer.y = evt.clientY;
  44843. }
  44844. else if (pointA && pointB) {
  44845. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  44846. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  44847. ed.x = evt.clientX;
  44848. ed.y = evt.clientY;
  44849. var direction = _this.pinchInwards ? 1 : -1;
  44850. var distX = pointA.x - pointB.x;
  44851. var distY = pointA.y - pointB.y;
  44852. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  44853. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  44854. if (previousPinchSquaredDistance === 0) {
  44855. initialDistance = pinchDistance;
  44856. previousPinchSquaredDistance = pinchSquaredDistance;
  44857. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  44858. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  44859. return;
  44860. }
  44861. if (_this.multiTouchPanAndZoom) {
  44862. if (_this.pinchDeltaPercentage) {
  44863. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44864. }
  44865. else {
  44866. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44867. (_this.pinchPrecision *
  44868. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44869. direction);
  44870. }
  44871. if (_this.panningSensibility !== 0) {
  44872. var pointersCenterX = (pointA.x + pointB.x) / 2;
  44873. var pointersCenterY = (pointA.y + pointB.y) / 2;
  44874. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  44875. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  44876. previousMultiTouchPanPosition.x = pointersCenterX;
  44877. previousMultiTouchPanPosition.y = pointersCenterY;
  44878. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  44879. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  44880. }
  44881. }
  44882. else {
  44883. twoFingerActivityCount++;
  44884. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  44885. if (_this.pinchDeltaPercentage) {
  44886. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44887. }
  44888. else {
  44889. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44890. (_this.pinchPrecision *
  44891. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44892. direction);
  44893. }
  44894. previousMultiTouchPanPosition.isPaning = false;
  44895. previousMultiTouchPanPosition.isPinching = true;
  44896. }
  44897. else {
  44898. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  44899. if (!previousMultiTouchPanPosition.isPaning) {
  44900. previousMultiTouchPanPosition.isPaning = true;
  44901. previousMultiTouchPanPosition.isPinching = false;
  44902. previousMultiTouchPanPosition.x = ed.x;
  44903. previousMultiTouchPanPosition.y = ed.y;
  44904. return;
  44905. }
  44906. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  44907. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  44908. }
  44909. }
  44910. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  44911. previousMultiTouchPanPosition.x = ed.x;
  44912. previousMultiTouchPanPosition.y = ed.y;
  44913. }
  44914. }
  44915. previousPinchSquaredDistance = pinchSquaredDistance;
  44916. }
  44917. }
  44918. };
  44919. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  44920. this._onContextMenu = function (evt) {
  44921. evt.preventDefault();
  44922. };
  44923. if (!this.camera._useCtrlForPanning) {
  44924. element.addEventListener("contextmenu", this._onContextMenu, false);
  44925. }
  44926. this._onLostFocus = function () {
  44927. //this._keys = [];
  44928. pointA = pointB = null;
  44929. previousPinchSquaredDistance = 0;
  44930. previousMultiTouchPanPosition.isPaning = false;
  44931. previousMultiTouchPanPosition.isPinching = false;
  44932. twoFingerActivityCount = 0;
  44933. cacheSoloPointer = null;
  44934. initialDistance = 0;
  44935. };
  44936. this._onMouseMove = function (evt) {
  44937. if (!engine.isPointerLock) {
  44938. return;
  44939. }
  44940. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44941. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44942. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44943. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44944. if (!noPreventDefault) {
  44945. evt.preventDefault();
  44946. }
  44947. };
  44948. this._onGestureStart = function (e) {
  44949. if (window.MSGesture === undefined) {
  44950. return;
  44951. }
  44952. if (!_this._MSGestureHandler) {
  44953. _this._MSGestureHandler = new MSGesture();
  44954. _this._MSGestureHandler.target = element;
  44955. }
  44956. _this._MSGestureHandler.addPointer(e.pointerId);
  44957. };
  44958. this._onGesture = function (e) {
  44959. _this.camera.radius *= e.scale;
  44960. if (e.preventDefault) {
  44961. if (!noPreventDefault) {
  44962. e.stopPropagation();
  44963. e.preventDefault();
  44964. }
  44965. }
  44966. };
  44967. element.addEventListener("mousemove", this._onMouseMove, false);
  44968. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  44969. element.addEventListener("MSGestureChange", this._onGesture, false);
  44970. BABYLON.Tools.RegisterTopRootEvents([
  44971. { name: "blur", handler: this._onLostFocus }
  44972. ]);
  44973. };
  44974. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  44975. if (this._onLostFocus) {
  44976. BABYLON.Tools.UnregisterTopRootEvents([
  44977. { name: "blur", handler: this._onLostFocus }
  44978. ]);
  44979. }
  44980. if (element && this._observer) {
  44981. this.camera.getScene().onPointerObservable.remove(this._observer);
  44982. this._observer = null;
  44983. if (this._onContextMenu) {
  44984. element.removeEventListener("contextmenu", this._onContextMenu);
  44985. }
  44986. if (this._onMouseMove) {
  44987. element.removeEventListener("mousemove", this._onMouseMove);
  44988. }
  44989. if (this._onGestureStart) {
  44990. element.removeEventListener("MSPointerDown", this._onGestureStart);
  44991. }
  44992. if (this._onGesture) {
  44993. element.removeEventListener("MSGestureChange", this._onGesture);
  44994. }
  44995. this._isPanClick = false;
  44996. this.pinchInwards = true;
  44997. this._onMouseMove = null;
  44998. this._onGestureStart = null;
  44999. this._onGesture = null;
  45000. this._MSGestureHandler = null;
  45001. this._onLostFocus = null;
  45002. this._onContextMenu = null;
  45003. }
  45004. };
  45005. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  45006. return "ArcRotateCameraPointersInput";
  45007. };
  45008. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  45009. return "pointers";
  45010. };
  45011. __decorate([
  45012. BABYLON.serialize()
  45013. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  45014. __decorate([
  45015. BABYLON.serialize()
  45016. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  45017. __decorate([
  45018. BABYLON.serialize()
  45019. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  45020. __decorate([
  45021. BABYLON.serialize()
  45022. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  45023. __decorate([
  45024. BABYLON.serialize()
  45025. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  45026. __decorate([
  45027. BABYLON.serialize()
  45028. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  45029. __decorate([
  45030. BABYLON.serialize()
  45031. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  45032. __decorate([
  45033. BABYLON.serialize()
  45034. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  45035. return ArcRotateCameraPointersInput;
  45036. }());
  45037. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  45038. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  45039. })(BABYLON || (BABYLON = {}));
  45040. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  45041. "use strict";
  45042. var BABYLON;
  45043. (function (BABYLON) {
  45044. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  45045. __extends(ArcRotateCameraInputsManager, _super);
  45046. function ArcRotateCameraInputsManager(camera) {
  45047. return _super.call(this, camera) || this;
  45048. }
  45049. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  45050. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  45051. return this;
  45052. };
  45053. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  45054. this.add(new BABYLON.ArcRotateCameraPointersInput());
  45055. return this;
  45056. };
  45057. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  45058. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  45059. return this;
  45060. };
  45061. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  45062. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  45063. return this;
  45064. };
  45065. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  45066. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  45067. return this;
  45068. };
  45069. return ArcRotateCameraInputsManager;
  45070. }(BABYLON.CameraInputsManager));
  45071. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  45072. })(BABYLON || (BABYLON = {}));
  45073. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  45074. "use strict";
  45075. var BABYLON;
  45076. (function (BABYLON) {
  45077. var ArcRotateCamera = /** @class */ (function (_super) {
  45078. __extends(ArcRotateCamera, _super);
  45079. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  45080. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  45081. _this.inertialAlphaOffset = 0;
  45082. _this.inertialBetaOffset = 0;
  45083. _this.inertialRadiusOffset = 0;
  45084. _this.lowerAlphaLimit = null;
  45085. _this.upperAlphaLimit = null;
  45086. _this.lowerBetaLimit = 0.01;
  45087. _this.upperBetaLimit = Math.PI;
  45088. _this.lowerRadiusLimit = null;
  45089. _this.upperRadiusLimit = null;
  45090. _this.inertialPanningX = 0;
  45091. _this.inertialPanningY = 0;
  45092. _this.pinchToPanMaxDistance = 20;
  45093. _this.panningDistanceLimit = null;
  45094. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  45095. _this.panningInertia = 0.9;
  45096. //-- end properties for backward compatibility for inputs
  45097. _this.zoomOnFactor = 1;
  45098. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  45099. _this.allowUpsideDown = true;
  45100. _this._viewMatrix = new BABYLON.Matrix();
  45101. // Panning
  45102. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  45103. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  45104. _this.checkCollisions = false;
  45105. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  45106. _this._previousPosition = BABYLON.Vector3.Zero();
  45107. _this._collisionVelocity = BABYLON.Vector3.Zero();
  45108. _this._newPosition = BABYLON.Vector3.Zero();
  45109. _this._computationVector = BABYLON.Vector3.Zero();
  45110. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  45111. if (collidedMesh === void 0) { collidedMesh = null; }
  45112. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  45113. newPosition.multiplyInPlace(_this._collider._radius);
  45114. }
  45115. if (!collidedMesh) {
  45116. _this._previousPosition.copyFrom(_this.position);
  45117. }
  45118. else {
  45119. _this.setPosition(newPosition);
  45120. if (_this.onCollide) {
  45121. _this.onCollide(collidedMesh);
  45122. }
  45123. }
  45124. // Recompute because of constraints
  45125. var cosa = Math.cos(_this.alpha);
  45126. var sina = Math.sin(_this.alpha);
  45127. var cosb = Math.cos(_this.beta);
  45128. var sinb = Math.sin(_this.beta);
  45129. if (sinb === 0) {
  45130. sinb = 0.0001;
  45131. }
  45132. var target = _this._getTargetPosition();
  45133. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  45134. target.addToRef(_this._computationVector, _this._newPosition);
  45135. _this.position.copyFrom(_this._newPosition);
  45136. var up = _this.upVector;
  45137. if (_this.allowUpsideDown && _this.beta < 0) {
  45138. up = up.clone();
  45139. up = up.negate();
  45140. }
  45141. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  45142. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  45143. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  45144. _this._collisionTriggered = false;
  45145. };
  45146. _this._target = BABYLON.Vector3.Zero();
  45147. if (target) {
  45148. _this.setTarget(target);
  45149. }
  45150. _this.alpha = alpha;
  45151. _this.beta = beta;
  45152. _this.radius = radius;
  45153. _this.getViewMatrix();
  45154. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  45155. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  45156. return _this;
  45157. }
  45158. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  45159. get: function () {
  45160. return this._target;
  45161. },
  45162. set: function (value) {
  45163. this.setTarget(value);
  45164. },
  45165. enumerable: true,
  45166. configurable: true
  45167. });
  45168. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  45169. //-- begin properties for backward compatibility for inputs
  45170. get: function () {
  45171. var pointers = this.inputs.attached["pointers"];
  45172. if (pointers)
  45173. return pointers.angularSensibilityX;
  45174. return 0;
  45175. },
  45176. set: function (value) {
  45177. var pointers = this.inputs.attached["pointers"];
  45178. if (pointers) {
  45179. pointers.angularSensibilityX = value;
  45180. }
  45181. },
  45182. enumerable: true,
  45183. configurable: true
  45184. });
  45185. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  45186. get: function () {
  45187. var pointers = this.inputs.attached["pointers"];
  45188. if (pointers)
  45189. return pointers.angularSensibilityY;
  45190. return 0;
  45191. },
  45192. set: function (value) {
  45193. var pointers = this.inputs.attached["pointers"];
  45194. if (pointers) {
  45195. pointers.angularSensibilityY = value;
  45196. }
  45197. },
  45198. enumerable: true,
  45199. configurable: true
  45200. });
  45201. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  45202. get: function () {
  45203. var pointers = this.inputs.attached["pointers"];
  45204. if (pointers)
  45205. return pointers.pinchPrecision;
  45206. return 0;
  45207. },
  45208. set: function (value) {
  45209. var pointers = this.inputs.attached["pointers"];
  45210. if (pointers) {
  45211. pointers.pinchPrecision = value;
  45212. }
  45213. },
  45214. enumerable: true,
  45215. configurable: true
  45216. });
  45217. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  45218. get: function () {
  45219. var pointers = this.inputs.attached["pointers"];
  45220. if (pointers)
  45221. return pointers.pinchDeltaPercentage;
  45222. return 0;
  45223. },
  45224. set: function (value) {
  45225. var pointers = this.inputs.attached["pointers"];
  45226. if (pointers) {
  45227. pointers.pinchDeltaPercentage = value;
  45228. }
  45229. },
  45230. enumerable: true,
  45231. configurable: true
  45232. });
  45233. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  45234. get: function () {
  45235. var pointers = this.inputs.attached["pointers"];
  45236. if (pointers)
  45237. return pointers.panningSensibility;
  45238. return 0;
  45239. },
  45240. set: function (value) {
  45241. var pointers = this.inputs.attached["pointers"];
  45242. if (pointers) {
  45243. pointers.panningSensibility = value;
  45244. }
  45245. },
  45246. enumerable: true,
  45247. configurable: true
  45248. });
  45249. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  45250. get: function () {
  45251. var keyboard = this.inputs.attached["keyboard"];
  45252. if (keyboard)
  45253. return keyboard.keysUp;
  45254. return [];
  45255. },
  45256. set: function (value) {
  45257. var keyboard = this.inputs.attached["keyboard"];
  45258. if (keyboard)
  45259. keyboard.keysUp = value;
  45260. },
  45261. enumerable: true,
  45262. configurable: true
  45263. });
  45264. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  45265. get: function () {
  45266. var keyboard = this.inputs.attached["keyboard"];
  45267. if (keyboard)
  45268. return keyboard.keysDown;
  45269. return [];
  45270. },
  45271. set: function (value) {
  45272. var keyboard = this.inputs.attached["keyboard"];
  45273. if (keyboard)
  45274. keyboard.keysDown = value;
  45275. },
  45276. enumerable: true,
  45277. configurable: true
  45278. });
  45279. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  45280. get: function () {
  45281. var keyboard = this.inputs.attached["keyboard"];
  45282. if (keyboard)
  45283. return keyboard.keysLeft;
  45284. return [];
  45285. },
  45286. set: function (value) {
  45287. var keyboard = this.inputs.attached["keyboard"];
  45288. if (keyboard)
  45289. keyboard.keysLeft = value;
  45290. },
  45291. enumerable: true,
  45292. configurable: true
  45293. });
  45294. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  45295. get: function () {
  45296. var keyboard = this.inputs.attached["keyboard"];
  45297. if (keyboard)
  45298. return keyboard.keysRight;
  45299. return [];
  45300. },
  45301. set: function (value) {
  45302. var keyboard = this.inputs.attached["keyboard"];
  45303. if (keyboard)
  45304. keyboard.keysRight = value;
  45305. },
  45306. enumerable: true,
  45307. configurable: true
  45308. });
  45309. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  45310. get: function () {
  45311. var mousewheel = this.inputs.attached["mousewheel"];
  45312. if (mousewheel)
  45313. return mousewheel.wheelPrecision;
  45314. return 0;
  45315. },
  45316. set: function (value) {
  45317. var mousewheel = this.inputs.attached["mousewheel"];
  45318. if (mousewheel)
  45319. mousewheel.wheelPrecision = value;
  45320. },
  45321. enumerable: true,
  45322. configurable: true
  45323. });
  45324. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  45325. get: function () {
  45326. var mousewheel = this.inputs.attached["mousewheel"];
  45327. if (mousewheel)
  45328. return mousewheel.wheelDeltaPercentage;
  45329. return 0;
  45330. },
  45331. set: function (value) {
  45332. var mousewheel = this.inputs.attached["mousewheel"];
  45333. if (mousewheel)
  45334. mousewheel.wheelDeltaPercentage = value;
  45335. },
  45336. enumerable: true,
  45337. configurable: true
  45338. });
  45339. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  45340. get: function () {
  45341. return this._bouncingBehavior;
  45342. },
  45343. enumerable: true,
  45344. configurable: true
  45345. });
  45346. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  45347. get: function () {
  45348. return this._bouncingBehavior != null;
  45349. },
  45350. set: function (value) {
  45351. if (value === this.useBouncingBehavior) {
  45352. return;
  45353. }
  45354. if (value) {
  45355. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  45356. this.addBehavior(this._bouncingBehavior);
  45357. }
  45358. else if (this._bouncingBehavior) {
  45359. this.removeBehavior(this._bouncingBehavior);
  45360. this._bouncingBehavior = null;
  45361. }
  45362. },
  45363. enumerable: true,
  45364. configurable: true
  45365. });
  45366. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  45367. get: function () {
  45368. return this._framingBehavior;
  45369. },
  45370. enumerable: true,
  45371. configurable: true
  45372. });
  45373. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  45374. get: function () {
  45375. return this._framingBehavior != null;
  45376. },
  45377. set: function (value) {
  45378. if (value === this.useFramingBehavior) {
  45379. return;
  45380. }
  45381. if (value) {
  45382. this._framingBehavior = new BABYLON.FramingBehavior();
  45383. this.addBehavior(this._framingBehavior);
  45384. }
  45385. else if (this._framingBehavior) {
  45386. this.removeBehavior(this._framingBehavior);
  45387. this._framingBehavior = null;
  45388. }
  45389. },
  45390. enumerable: true,
  45391. configurable: true
  45392. });
  45393. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  45394. get: function () {
  45395. return this._autoRotationBehavior;
  45396. },
  45397. enumerable: true,
  45398. configurable: true
  45399. });
  45400. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  45401. get: function () {
  45402. return this._autoRotationBehavior != null;
  45403. },
  45404. set: function (value) {
  45405. if (value === this.useAutoRotationBehavior) {
  45406. return;
  45407. }
  45408. if (value) {
  45409. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  45410. this.addBehavior(this._autoRotationBehavior);
  45411. }
  45412. else if (this._autoRotationBehavior) {
  45413. this.removeBehavior(this._autoRotationBehavior);
  45414. this._autoRotationBehavior = null;
  45415. }
  45416. },
  45417. enumerable: true,
  45418. configurable: true
  45419. });
  45420. // Cache
  45421. ArcRotateCamera.prototype._initCache = function () {
  45422. _super.prototype._initCache.call(this);
  45423. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45424. this._cache.alpha = undefined;
  45425. this._cache.beta = undefined;
  45426. this._cache.radius = undefined;
  45427. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  45428. };
  45429. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  45430. if (!ignoreParentClass) {
  45431. _super.prototype._updateCache.call(this);
  45432. }
  45433. this._cache._target.copyFrom(this._getTargetPosition());
  45434. this._cache.alpha = this.alpha;
  45435. this._cache.beta = this.beta;
  45436. this._cache.radius = this.radius;
  45437. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  45438. };
  45439. ArcRotateCamera.prototype._getTargetPosition = function () {
  45440. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  45441. var pos = this._targetHost.getAbsolutePosition();
  45442. if (this._targetBoundingCenter) {
  45443. pos.addToRef(this._targetBoundingCenter, this._target);
  45444. }
  45445. else {
  45446. this._target.copyFrom(pos);
  45447. }
  45448. }
  45449. var lockedTargetPosition = this._getLockedTargetPosition();
  45450. if (lockedTargetPosition) {
  45451. return lockedTargetPosition;
  45452. }
  45453. return this._target;
  45454. };
  45455. ArcRotateCamera.prototype.storeState = function () {
  45456. this._storedAlpha = this.alpha;
  45457. this._storedBeta = this.beta;
  45458. this._storedRadius = this.radius;
  45459. this._storedTarget = this._getTargetPosition().clone();
  45460. return _super.prototype.storeState.call(this);
  45461. };
  45462. /**
  45463. * Restored camera state. You must call storeState() first
  45464. */
  45465. ArcRotateCamera.prototype._restoreStateValues = function () {
  45466. if (!_super.prototype._restoreStateValues.call(this)) {
  45467. return false;
  45468. }
  45469. this.alpha = this._storedAlpha;
  45470. this.beta = this._storedBeta;
  45471. this.radius = this._storedRadius;
  45472. this.setTarget(this._storedTarget.clone());
  45473. this.inertialAlphaOffset = 0;
  45474. this.inertialBetaOffset = 0;
  45475. this.inertialRadiusOffset = 0;
  45476. this.inertialPanningX = 0;
  45477. this.inertialPanningY = 0;
  45478. return true;
  45479. };
  45480. // Synchronized
  45481. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  45482. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  45483. return false;
  45484. return this._cache._target.equals(this._getTargetPosition())
  45485. && this._cache.alpha === this.alpha
  45486. && this._cache.beta === this.beta
  45487. && this._cache.radius === this.radius
  45488. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  45489. };
  45490. // Methods
  45491. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  45492. var _this = this;
  45493. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  45494. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  45495. this._useCtrlForPanning = useCtrlForPanning;
  45496. this._panningMouseButton = panningMouseButton;
  45497. this.inputs.attachElement(element, noPreventDefault);
  45498. this._reset = function () {
  45499. _this.inertialAlphaOffset = 0;
  45500. _this.inertialBetaOffset = 0;
  45501. _this.inertialRadiusOffset = 0;
  45502. _this.inertialPanningX = 0;
  45503. _this.inertialPanningY = 0;
  45504. };
  45505. };
  45506. ArcRotateCamera.prototype.detachControl = function (element) {
  45507. this.inputs.detachElement(element);
  45508. if (this._reset) {
  45509. this._reset();
  45510. }
  45511. };
  45512. ArcRotateCamera.prototype._checkInputs = function () {
  45513. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  45514. if (this._collisionTriggered) {
  45515. return;
  45516. }
  45517. this.inputs.checkInputs();
  45518. // Inertia
  45519. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  45520. if (this.getScene().useRightHandedSystem) {
  45521. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45522. }
  45523. else {
  45524. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45525. }
  45526. this.beta += this.inertialBetaOffset;
  45527. this.radius -= this.inertialRadiusOffset;
  45528. this.inertialAlphaOffset *= this.inertia;
  45529. this.inertialBetaOffset *= this.inertia;
  45530. this.inertialRadiusOffset *= this.inertia;
  45531. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  45532. this.inertialAlphaOffset = 0;
  45533. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  45534. this.inertialBetaOffset = 0;
  45535. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  45536. this.inertialRadiusOffset = 0;
  45537. }
  45538. // Panning inertia
  45539. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  45540. if (!this._localDirection) {
  45541. this._localDirection = BABYLON.Vector3.Zero();
  45542. this._transformedDirection = BABYLON.Vector3.Zero();
  45543. }
  45544. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  45545. this._localDirection.multiplyInPlace(this.panningAxis);
  45546. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  45547. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  45548. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  45549. if (!this.panningAxis.y) {
  45550. this._transformedDirection.y = 0;
  45551. }
  45552. if (!this._targetHost) {
  45553. if (this.panningDistanceLimit) {
  45554. this._transformedDirection.addInPlace(this._target);
  45555. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  45556. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  45557. this._target.copyFrom(this._transformedDirection);
  45558. }
  45559. }
  45560. else {
  45561. this._target.addInPlace(this._transformedDirection);
  45562. }
  45563. }
  45564. this.inertialPanningX *= this.panningInertia;
  45565. this.inertialPanningY *= this.panningInertia;
  45566. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  45567. this.inertialPanningX = 0;
  45568. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  45569. this.inertialPanningY = 0;
  45570. }
  45571. // Limits
  45572. this._checkLimits();
  45573. _super.prototype._checkInputs.call(this);
  45574. };
  45575. ArcRotateCamera.prototype._checkLimits = function () {
  45576. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  45577. if (this.allowUpsideDown && this.beta > Math.PI) {
  45578. this.beta = this.beta - (2 * Math.PI);
  45579. }
  45580. }
  45581. else {
  45582. if (this.beta < this.lowerBetaLimit) {
  45583. this.beta = this.lowerBetaLimit;
  45584. }
  45585. }
  45586. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  45587. if (this.allowUpsideDown && this.beta < -Math.PI) {
  45588. this.beta = this.beta + (2 * Math.PI);
  45589. }
  45590. }
  45591. else {
  45592. if (this.beta > this.upperBetaLimit) {
  45593. this.beta = this.upperBetaLimit;
  45594. }
  45595. }
  45596. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  45597. this.alpha = this.lowerAlphaLimit;
  45598. }
  45599. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  45600. this.alpha = this.upperAlphaLimit;
  45601. }
  45602. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  45603. this.radius = this.lowerRadiusLimit;
  45604. }
  45605. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  45606. this.radius = this.upperRadiusLimit;
  45607. }
  45608. };
  45609. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  45610. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  45611. this.radius = this._computationVector.length();
  45612. if (this.radius === 0) {
  45613. this.radius = 0.0001; // Just to avoid division by zero
  45614. }
  45615. // Alpha
  45616. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  45617. if (this._computationVector.z < 0) {
  45618. this.alpha = 2 * Math.PI - this.alpha;
  45619. }
  45620. // Beta
  45621. this.beta = Math.acos(this._computationVector.y / this.radius);
  45622. this._checkLimits();
  45623. };
  45624. ArcRotateCamera.prototype.setPosition = function (position) {
  45625. if (this.position.equals(position)) {
  45626. return;
  45627. }
  45628. this.position.copyFrom(position);
  45629. this.rebuildAnglesAndRadius();
  45630. };
  45631. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  45632. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  45633. if (allowSamePosition === void 0) { allowSamePosition = false; }
  45634. if (target.getBoundingInfo) {
  45635. if (toBoundingCenter) {
  45636. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  45637. }
  45638. else {
  45639. this._targetBoundingCenter = null;
  45640. }
  45641. this._targetHost = target;
  45642. this._target = this._getTargetPosition();
  45643. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  45644. }
  45645. else {
  45646. var newTarget = target;
  45647. var currentTarget = this._getTargetPosition();
  45648. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  45649. return;
  45650. }
  45651. this._targetHost = null;
  45652. this._target = newTarget;
  45653. this._targetBoundingCenter = null;
  45654. this.onMeshTargetChangedObservable.notifyObservers(null);
  45655. }
  45656. this.rebuildAnglesAndRadius();
  45657. };
  45658. ArcRotateCamera.prototype._getViewMatrix = function () {
  45659. // Compute
  45660. var cosa = Math.cos(this.alpha);
  45661. var sina = Math.sin(this.alpha);
  45662. var cosb = Math.cos(this.beta);
  45663. var sinb = Math.sin(this.beta);
  45664. if (sinb === 0) {
  45665. sinb = 0.0001;
  45666. }
  45667. var target = this._getTargetPosition();
  45668. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  45669. target.addToRef(this._computationVector, this._newPosition);
  45670. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  45671. if (!this._collider) {
  45672. this._collider = new BABYLON.Collider();
  45673. }
  45674. this._collider._radius = this.collisionRadius;
  45675. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  45676. this._collisionTriggered = true;
  45677. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  45678. }
  45679. else {
  45680. this.position.copyFrom(this._newPosition);
  45681. var up = this.upVector;
  45682. if (this.allowUpsideDown && sinb < 0) {
  45683. up = up.clone();
  45684. up = up.negate();
  45685. }
  45686. if (this.getScene().useRightHandedSystem) {
  45687. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  45688. }
  45689. else {
  45690. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  45691. }
  45692. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  45693. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  45694. }
  45695. this._currentTarget = target;
  45696. return this._viewMatrix;
  45697. };
  45698. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  45699. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45700. meshes = meshes || this.getScene().meshes;
  45701. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  45702. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  45703. this.radius = distance * this.zoomOnFactor;
  45704. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  45705. };
  45706. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  45707. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45708. var meshesOrMinMaxVector;
  45709. var distance;
  45710. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  45711. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  45712. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  45713. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  45714. }
  45715. else {
  45716. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  45717. meshesOrMinMaxVector = minMaxVectorAndDistance;
  45718. distance = minMaxVectorAndDistance.distance;
  45719. }
  45720. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  45721. if (!doNotUpdateMaxZ) {
  45722. this.maxZ = distance * 2;
  45723. }
  45724. };
  45725. /**
  45726. * @override
  45727. * Override Camera.createRigCamera
  45728. */
  45729. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  45730. var alphaShift = 0;
  45731. switch (this.cameraRigMode) {
  45732. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45733. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45734. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45735. case BABYLON.Camera.RIG_MODE_VR:
  45736. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  45737. break;
  45738. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45739. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  45740. break;
  45741. }
  45742. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  45743. rigCam._cameraRigParams = {};
  45744. return rigCam;
  45745. };
  45746. /**
  45747. * @override
  45748. * Override Camera._updateRigCameras
  45749. */
  45750. ArcRotateCamera.prototype._updateRigCameras = function () {
  45751. var camLeft = this._rigCameras[0];
  45752. var camRight = this._rigCameras[1];
  45753. camLeft.beta = camRight.beta = this.beta;
  45754. camLeft.radius = camRight.radius = this.radius;
  45755. switch (this.cameraRigMode) {
  45756. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45757. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45758. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45759. case BABYLON.Camera.RIG_MODE_VR:
  45760. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45761. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45762. break;
  45763. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45764. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45765. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45766. break;
  45767. }
  45768. _super.prototype._updateRigCameras.call(this);
  45769. };
  45770. ArcRotateCamera.prototype.dispose = function () {
  45771. this.inputs.clear();
  45772. _super.prototype.dispose.call(this);
  45773. };
  45774. ArcRotateCamera.prototype.getClassName = function () {
  45775. return "ArcRotateCamera";
  45776. };
  45777. __decorate([
  45778. BABYLON.serialize()
  45779. ], ArcRotateCamera.prototype, "alpha", void 0);
  45780. __decorate([
  45781. BABYLON.serialize()
  45782. ], ArcRotateCamera.prototype, "beta", void 0);
  45783. __decorate([
  45784. BABYLON.serialize()
  45785. ], ArcRotateCamera.prototype, "radius", void 0);
  45786. __decorate([
  45787. BABYLON.serializeAsVector3("target")
  45788. ], ArcRotateCamera.prototype, "_target", void 0);
  45789. __decorate([
  45790. BABYLON.serialize()
  45791. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  45792. __decorate([
  45793. BABYLON.serialize()
  45794. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  45795. __decorate([
  45796. BABYLON.serialize()
  45797. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  45798. __decorate([
  45799. BABYLON.serialize()
  45800. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  45801. __decorate([
  45802. BABYLON.serialize()
  45803. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  45804. __decorate([
  45805. BABYLON.serialize()
  45806. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  45807. __decorate([
  45808. BABYLON.serialize()
  45809. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  45810. __decorate([
  45811. BABYLON.serialize()
  45812. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  45813. __decorate([
  45814. BABYLON.serialize()
  45815. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  45816. __decorate([
  45817. BABYLON.serialize()
  45818. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  45819. __decorate([
  45820. BABYLON.serialize()
  45821. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  45822. __decorate([
  45823. BABYLON.serialize()
  45824. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  45825. __decorate([
  45826. BABYLON.serialize()
  45827. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  45828. __decorate([
  45829. BABYLON.serializeAsVector3()
  45830. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  45831. __decorate([
  45832. BABYLON.serialize()
  45833. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  45834. __decorate([
  45835. BABYLON.serialize()
  45836. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  45837. __decorate([
  45838. BABYLON.serialize()
  45839. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  45840. return ArcRotateCamera;
  45841. }(BABYLON.TargetCamera));
  45842. BABYLON.ArcRotateCamera = ArcRotateCamera;
  45843. })(BABYLON || (BABYLON = {}));
  45844. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  45845. "use strict";
  45846. var BABYLON;
  45847. (function (BABYLON) {
  45848. /**
  45849. * The HemisphericLight simulates the ambient environment light,
  45850. * so the passed direction is the light reflection direction, not the incoming direction.
  45851. */
  45852. var HemisphericLight = /** @class */ (function (_super) {
  45853. __extends(HemisphericLight, _super);
  45854. /**
  45855. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  45856. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  45857. * The HemisphericLight can't cast shadows.
  45858. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45859. * @param name The friendly name of the light
  45860. * @param direction The direction of the light reflection
  45861. * @param scene The scene the light belongs to
  45862. */
  45863. function HemisphericLight(name, direction, scene) {
  45864. var _this = _super.call(this, name, scene) || this;
  45865. /**
  45866. * The groundColor is the light in the opposite direction to the one specified during creation.
  45867. * 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.
  45868. */
  45869. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  45870. _this.direction = direction || BABYLON.Vector3.Up();
  45871. return _this;
  45872. }
  45873. HemisphericLight.prototype._buildUniformLayout = function () {
  45874. this._uniformBuffer.addUniform("vLightData", 4);
  45875. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45876. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45877. this._uniformBuffer.addUniform("vLightGround", 3);
  45878. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45879. this._uniformBuffer.addUniform("depthValues", 2);
  45880. this._uniformBuffer.create();
  45881. };
  45882. /**
  45883. * Returns the string "HemisphericLight".
  45884. * @return The class name
  45885. */
  45886. HemisphericLight.prototype.getClassName = function () {
  45887. return "HemisphericLight";
  45888. };
  45889. /**
  45890. * Sets the HemisphericLight direction towards the passed target (Vector3).
  45891. * Returns the updated direction.
  45892. * @param target The target the direction should point to
  45893. * @return The computed direction
  45894. */
  45895. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  45896. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  45897. return this.direction;
  45898. };
  45899. /**
  45900. * Returns the shadow generator associated to the light.
  45901. * @returns Always null for hemispheric lights because it does not support shadows.
  45902. */
  45903. HemisphericLight.prototype.getShadowGenerator = function () {
  45904. return null;
  45905. };
  45906. /**
  45907. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  45908. * @param effect The effect to update
  45909. * @param lightIndex The index of the light in the effect to update
  45910. * @returns The hemispheric light
  45911. */
  45912. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  45913. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45914. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  45915. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  45916. return this;
  45917. };
  45918. /**
  45919. * @ignore internal use only.
  45920. */
  45921. HemisphericLight.prototype._getWorldMatrix = function () {
  45922. if (!this._worldMatrix) {
  45923. this._worldMatrix = BABYLON.Matrix.Identity();
  45924. }
  45925. return this._worldMatrix;
  45926. };
  45927. /**
  45928. * Returns the integer 3.
  45929. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45930. */
  45931. HemisphericLight.prototype.getTypeID = function () {
  45932. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  45933. };
  45934. __decorate([
  45935. BABYLON.serializeAsColor3()
  45936. ], HemisphericLight.prototype, "groundColor", void 0);
  45937. __decorate([
  45938. BABYLON.serializeAsVector3()
  45939. ], HemisphericLight.prototype, "direction", void 0);
  45940. return HemisphericLight;
  45941. }(BABYLON.Light));
  45942. BABYLON.HemisphericLight = HemisphericLight;
  45943. })(BABYLON || (BABYLON = {}));
  45944. //# sourceMappingURL=babylon.hemisphericLight.js.map
  45945. "use strict";
  45946. var BABYLON;
  45947. (function (BABYLON) {
  45948. /**
  45949. * Base implementation IShadowLight
  45950. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  45951. */
  45952. var ShadowLight = /** @class */ (function (_super) {
  45953. __extends(ShadowLight, _super);
  45954. function ShadowLight() {
  45955. var _this = _super !== null && _super.apply(this, arguments) || this;
  45956. _this._needProjectionMatrixCompute = true;
  45957. return _this;
  45958. }
  45959. ShadowLight.prototype._setPosition = function (value) {
  45960. this._position = value;
  45961. };
  45962. Object.defineProperty(ShadowLight.prototype, "position", {
  45963. /**
  45964. * Sets the position the shadow will be casted from. Also use as the light position for both
  45965. * point and spot lights.
  45966. */
  45967. get: function () {
  45968. return this._position;
  45969. },
  45970. /**
  45971. * Sets the position the shadow will be casted from. Also use as the light position for both
  45972. * point and spot lights.
  45973. */
  45974. set: function (value) {
  45975. this._setPosition(value);
  45976. },
  45977. enumerable: true,
  45978. configurable: true
  45979. });
  45980. ShadowLight.prototype._setDirection = function (value) {
  45981. this._direction = value;
  45982. };
  45983. Object.defineProperty(ShadowLight.prototype, "direction", {
  45984. /**
  45985. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  45986. * Also use as the light direction on spot and directional lights.
  45987. */
  45988. get: function () {
  45989. return this._direction;
  45990. },
  45991. /**
  45992. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  45993. * Also use as the light direction on spot and directional lights.
  45994. */
  45995. set: function (value) {
  45996. this._setDirection(value);
  45997. },
  45998. enumerable: true,
  45999. configurable: true
  46000. });
  46001. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  46002. /**
  46003. * Gets the shadow projection clipping minimum z value.
  46004. */
  46005. get: function () {
  46006. return this._shadowMinZ;
  46007. },
  46008. /**
  46009. * Sets the shadow projection clipping minimum z value.
  46010. */
  46011. set: function (value) {
  46012. this._shadowMinZ = value;
  46013. this.forceProjectionMatrixCompute();
  46014. },
  46015. enumerable: true,
  46016. configurable: true
  46017. });
  46018. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  46019. /**
  46020. * Sets the shadow projection clipping maximum z value.
  46021. */
  46022. get: function () {
  46023. return this._shadowMaxZ;
  46024. },
  46025. /**
  46026. * Gets the shadow projection clipping maximum z value.
  46027. */
  46028. set: function (value) {
  46029. this._shadowMaxZ = value;
  46030. this.forceProjectionMatrixCompute();
  46031. },
  46032. enumerable: true,
  46033. configurable: true
  46034. });
  46035. /**
  46036. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  46037. * @returns true if the information has been computed, false if it does not need to (no parenting)
  46038. */
  46039. ShadowLight.prototype.computeTransformedInformation = function () {
  46040. if (this.parent && this.parent.getWorldMatrix) {
  46041. if (!this.transformedPosition) {
  46042. this.transformedPosition = BABYLON.Vector3.Zero();
  46043. }
  46044. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  46045. // In case the direction is present.
  46046. if (this.direction) {
  46047. if (!this.transformedDirection) {
  46048. this.transformedDirection = BABYLON.Vector3.Zero();
  46049. }
  46050. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  46051. }
  46052. return true;
  46053. }
  46054. return false;
  46055. };
  46056. /**
  46057. * Return the depth scale used for the shadow map.
  46058. * @returns the depth scale.
  46059. */
  46060. ShadowLight.prototype.getDepthScale = function () {
  46061. return 50.0;
  46062. };
  46063. /**
  46064. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  46065. * @param faceIndex The index of the face we are computed the direction to generate shadow
  46066. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  46067. */
  46068. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  46069. return this.transformedDirection ? this.transformedDirection : this.direction;
  46070. };
  46071. /**
  46072. * Returns the ShadowLight absolute position in the World.
  46073. * @returns the position vector in world space
  46074. */
  46075. ShadowLight.prototype.getAbsolutePosition = function () {
  46076. return this.transformedPosition ? this.transformedPosition : this.position;
  46077. };
  46078. /**
  46079. * Sets the ShadowLight direction toward the passed target.
  46080. * @param target The point tot target in local space
  46081. * @returns the updated ShadowLight direction
  46082. */
  46083. ShadowLight.prototype.setDirectionToTarget = function (target) {
  46084. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  46085. return this.direction;
  46086. };
  46087. /**
  46088. * Returns the light rotation in euler definition.
  46089. * @returns the x y z rotation in local space.
  46090. */
  46091. ShadowLight.prototype.getRotation = function () {
  46092. this.direction.normalize();
  46093. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  46094. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  46095. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  46096. };
  46097. /**
  46098. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  46099. * @returns true if a cube texture needs to be use
  46100. */
  46101. ShadowLight.prototype.needCube = function () {
  46102. return false;
  46103. };
  46104. /**
  46105. * Detects if the projection matrix requires to be recomputed this frame.
  46106. * @returns true if it requires to be recomputed otherwise, false.
  46107. */
  46108. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  46109. return this._needProjectionMatrixCompute;
  46110. };
  46111. /**
  46112. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  46113. */
  46114. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  46115. this._needProjectionMatrixCompute = true;
  46116. };
  46117. /**
  46118. * Get the world matrix of the sahdow lights.
  46119. * @ignore Internal Use Only
  46120. */
  46121. ShadowLight.prototype._getWorldMatrix = function () {
  46122. if (!this._worldMatrix) {
  46123. this._worldMatrix = BABYLON.Matrix.Identity();
  46124. }
  46125. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  46126. return this._worldMatrix;
  46127. };
  46128. /**
  46129. * Gets the minZ used for shadow according to both the scene and the light.
  46130. * @param activeCamera The camera we are returning the min for
  46131. * @returns the depth min z
  46132. */
  46133. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  46134. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  46135. };
  46136. /**
  46137. * Gets the maxZ used for shadow according to both the scene and the light.
  46138. * @param activeCamera The camera we are returning the max for
  46139. * @returns the depth max z
  46140. */
  46141. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  46142. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  46143. };
  46144. /**
  46145. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  46146. * @param matrix The materix to updated with the projection information
  46147. * @param viewMatrix The transform matrix of the light
  46148. * @param renderList The list of mesh to render in the map
  46149. * @returns The current light
  46150. */
  46151. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46152. if (this.customProjectionMatrixBuilder) {
  46153. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  46154. }
  46155. else {
  46156. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  46157. }
  46158. return this;
  46159. };
  46160. __decorate([
  46161. BABYLON.serializeAsVector3()
  46162. ], ShadowLight.prototype, "position", null);
  46163. __decorate([
  46164. BABYLON.serializeAsVector3()
  46165. ], ShadowLight.prototype, "direction", null);
  46166. __decorate([
  46167. BABYLON.serialize()
  46168. ], ShadowLight.prototype, "shadowMinZ", null);
  46169. __decorate([
  46170. BABYLON.serialize()
  46171. ], ShadowLight.prototype, "shadowMaxZ", null);
  46172. return ShadowLight;
  46173. }(BABYLON.Light));
  46174. BABYLON.ShadowLight = ShadowLight;
  46175. })(BABYLON || (BABYLON = {}));
  46176. //# sourceMappingURL=babylon.shadowLight.js.map
  46177. "use strict";
  46178. var BABYLON;
  46179. (function (BABYLON) {
  46180. /**
  46181. * A point light is a light defined by an unique point in world space.
  46182. * The light is emitted in every direction from this point.
  46183. * A good example of a point light is a standard light bulb.
  46184. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46185. */
  46186. var PointLight = /** @class */ (function (_super) {
  46187. __extends(PointLight, _super);
  46188. /**
  46189. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  46190. * A PointLight emits the light in every direction.
  46191. * It can cast shadows.
  46192. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  46193. * ```javascript
  46194. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  46195. * ```
  46196. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46197. * @param name The light friendly name
  46198. * @param position The position of the point light in the scene
  46199. * @param scene The scene the lights belongs to
  46200. */
  46201. function PointLight(name, position, scene) {
  46202. var _this = _super.call(this, name, scene) || this;
  46203. _this._shadowAngle = Math.PI / 2;
  46204. _this.position = position;
  46205. return _this;
  46206. }
  46207. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  46208. /**
  46209. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46210. * This specifies what angle the shadow will use to be created.
  46211. *
  46212. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  46213. */
  46214. get: function () {
  46215. return this._shadowAngle;
  46216. },
  46217. /**
  46218. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46219. * This specifies what angle the shadow will use to be created.
  46220. *
  46221. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  46222. */
  46223. set: function (value) {
  46224. this._shadowAngle = value;
  46225. this.forceProjectionMatrixCompute();
  46226. },
  46227. enumerable: true,
  46228. configurable: true
  46229. });
  46230. Object.defineProperty(PointLight.prototype, "direction", {
  46231. /**
  46232. * Gets the direction if it has been set.
  46233. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46234. */
  46235. get: function () {
  46236. return this._direction;
  46237. },
  46238. /**
  46239. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46240. */
  46241. set: function (value) {
  46242. var previousNeedCube = this.needCube();
  46243. this._direction = value;
  46244. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  46245. this._shadowGenerator.recreateShadowMap();
  46246. }
  46247. },
  46248. enumerable: true,
  46249. configurable: true
  46250. });
  46251. /**
  46252. * Returns the string "PointLight"
  46253. * @returns the class name
  46254. */
  46255. PointLight.prototype.getClassName = function () {
  46256. return "PointLight";
  46257. };
  46258. /**
  46259. * Returns the integer 0.
  46260. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46261. */
  46262. PointLight.prototype.getTypeID = function () {
  46263. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  46264. };
  46265. /**
  46266. * Specifies wether or not the shadowmap should be a cube texture.
  46267. * @returns true if the shadowmap needs to be a cube texture.
  46268. */
  46269. PointLight.prototype.needCube = function () {
  46270. return !this.direction;
  46271. };
  46272. /**
  46273. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  46274. * @param faceIndex The index of the face we are computed the direction to generate shadow
  46275. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  46276. */
  46277. PointLight.prototype.getShadowDirection = function (faceIndex) {
  46278. if (this.direction) {
  46279. return _super.prototype.getShadowDirection.call(this, faceIndex);
  46280. }
  46281. else {
  46282. switch (faceIndex) {
  46283. case 0:
  46284. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  46285. case 1:
  46286. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  46287. case 2:
  46288. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  46289. case 3:
  46290. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  46291. case 4:
  46292. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  46293. case 5:
  46294. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  46295. }
  46296. }
  46297. return BABYLON.Vector3.Zero();
  46298. };
  46299. /**
  46300. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  46301. * - fov = PI / 2
  46302. * - aspect ratio : 1.0
  46303. * - z-near and far equal to the active camera minZ and maxZ.
  46304. * Returns the PointLight.
  46305. */
  46306. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46307. var activeCamera = this.getScene().activeCamera;
  46308. if (!activeCamera) {
  46309. return;
  46310. }
  46311. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46312. };
  46313. PointLight.prototype._buildUniformLayout = function () {
  46314. this._uniformBuffer.addUniform("vLightData", 4);
  46315. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46316. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46317. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46318. this._uniformBuffer.addUniform("depthValues", 2);
  46319. this._uniformBuffer.create();
  46320. };
  46321. /**
  46322. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  46323. * @param effect The effect to update
  46324. * @param lightIndex The index of the light in the effect to update
  46325. * @returns The point light
  46326. */
  46327. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  46328. if (this.computeTransformedInformation()) {
  46329. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  46330. return this;
  46331. }
  46332. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  46333. return this;
  46334. };
  46335. __decorate([
  46336. BABYLON.serialize()
  46337. ], PointLight.prototype, "shadowAngle", null);
  46338. return PointLight;
  46339. }(BABYLON.ShadowLight));
  46340. BABYLON.PointLight = PointLight;
  46341. })(BABYLON || (BABYLON = {}));
  46342. //# sourceMappingURL=babylon.pointLight.js.map
  46343. "use strict";
  46344. var BABYLON;
  46345. (function (BABYLON) {
  46346. /**
  46347. * A directional light is defined by a direction (what a surprise!).
  46348. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  46349. * 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.
  46350. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46351. */
  46352. var DirectionalLight = /** @class */ (function (_super) {
  46353. __extends(DirectionalLight, _super);
  46354. /**
  46355. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  46356. * The directional light is emitted from everywhere in the given direction.
  46357. * It can cast shawdows.
  46358. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46359. * @param name The friendly name of the light
  46360. * @param direction The direction of the light
  46361. * @param scene The scene the light belongs to
  46362. */
  46363. function DirectionalLight(name, direction, scene) {
  46364. var _this = _super.call(this, name, scene) || this;
  46365. _this._shadowFrustumSize = 0;
  46366. _this._shadowOrthoScale = 0.1;
  46367. /**
  46368. * Automatically compute the projection matrix to best fit (including all the casters)
  46369. * on each frame.
  46370. */
  46371. _this.autoUpdateExtends = true;
  46372. // Cache
  46373. _this._orthoLeft = Number.MAX_VALUE;
  46374. _this._orthoRight = Number.MIN_VALUE;
  46375. _this._orthoTop = Number.MIN_VALUE;
  46376. _this._orthoBottom = Number.MAX_VALUE;
  46377. _this.position = direction.scale(-1.0);
  46378. _this.direction = direction;
  46379. return _this;
  46380. }
  46381. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  46382. /**
  46383. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  46384. */
  46385. get: function () {
  46386. return this._shadowFrustumSize;
  46387. },
  46388. /**
  46389. * Specifies a fix frustum size for the shadow generation.
  46390. */
  46391. set: function (value) {
  46392. this._shadowFrustumSize = value;
  46393. this.forceProjectionMatrixCompute();
  46394. },
  46395. enumerable: true,
  46396. configurable: true
  46397. });
  46398. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  46399. /**
  46400. * Gets the shadow projection scale against the optimal computed one.
  46401. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  46402. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  46403. */
  46404. get: function () {
  46405. return this._shadowOrthoScale;
  46406. },
  46407. /**
  46408. * Sets the shadow projection scale against the optimal computed one.
  46409. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  46410. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  46411. */
  46412. set: function (value) {
  46413. this._shadowOrthoScale = value;
  46414. this.forceProjectionMatrixCompute();
  46415. },
  46416. enumerable: true,
  46417. configurable: true
  46418. });
  46419. /**
  46420. * Returns the string "DirectionalLight".
  46421. * @return The class name
  46422. */
  46423. DirectionalLight.prototype.getClassName = function () {
  46424. return "DirectionalLight";
  46425. };
  46426. /**
  46427. * Returns the integer 1.
  46428. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46429. */
  46430. DirectionalLight.prototype.getTypeID = function () {
  46431. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  46432. };
  46433. /**
  46434. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  46435. * Returns the DirectionalLight Shadow projection matrix.
  46436. */
  46437. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46438. if (this.shadowFrustumSize > 0) {
  46439. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  46440. }
  46441. else {
  46442. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  46443. }
  46444. };
  46445. /**
  46446. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  46447. * Returns the DirectionalLight Shadow projection matrix.
  46448. */
  46449. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  46450. var activeCamera = this.getScene().activeCamera;
  46451. if (!activeCamera) {
  46452. return;
  46453. }
  46454. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  46455. };
  46456. /**
  46457. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  46458. * Returns the DirectionalLight Shadow projection matrix.
  46459. */
  46460. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46461. var activeCamera = this.getScene().activeCamera;
  46462. if (!activeCamera) {
  46463. return;
  46464. }
  46465. // Check extends
  46466. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  46467. var tempVector3 = BABYLON.Vector3.Zero();
  46468. this._orthoLeft = Number.MAX_VALUE;
  46469. this._orthoRight = Number.MIN_VALUE;
  46470. this._orthoTop = Number.MIN_VALUE;
  46471. this._orthoBottom = Number.MAX_VALUE;
  46472. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  46473. var mesh = renderList[meshIndex];
  46474. if (!mesh) {
  46475. continue;
  46476. }
  46477. var boundingInfo = mesh.getBoundingInfo();
  46478. var boundingBox = boundingInfo.boundingBox;
  46479. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  46480. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  46481. if (tempVector3.x < this._orthoLeft)
  46482. this._orthoLeft = tempVector3.x;
  46483. if (tempVector3.y < this._orthoBottom)
  46484. this._orthoBottom = tempVector3.y;
  46485. if (tempVector3.x > this._orthoRight)
  46486. this._orthoRight = tempVector3.x;
  46487. if (tempVector3.y > this._orthoTop)
  46488. this._orthoTop = tempVector3.y;
  46489. }
  46490. }
  46491. }
  46492. var xOffset = this._orthoRight - this._orthoLeft;
  46493. var yOffset = this._orthoTop - this._orthoBottom;
  46494. 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);
  46495. };
  46496. DirectionalLight.prototype._buildUniformLayout = function () {
  46497. this._uniformBuffer.addUniform("vLightData", 4);
  46498. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46499. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46500. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46501. this._uniformBuffer.addUniform("depthValues", 2);
  46502. this._uniformBuffer.create();
  46503. };
  46504. /**
  46505. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  46506. * @param effect The effect to update
  46507. * @param lightIndex The index of the light in the effect to update
  46508. * @returns The directional light
  46509. */
  46510. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  46511. if (this.computeTransformedInformation()) {
  46512. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  46513. return this;
  46514. }
  46515. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  46516. return this;
  46517. };
  46518. /**
  46519. * Gets the minZ used for shadow according to both the scene and the light.
  46520. *
  46521. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46522. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46523. * @param activeCamera The camera we are returning the min for
  46524. * @returns the depth min z
  46525. */
  46526. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  46527. return 1;
  46528. };
  46529. /**
  46530. * Gets the maxZ used for shadow according to both the scene and the light.
  46531. *
  46532. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46533. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46534. * @param activeCamera The camera we are returning the max for
  46535. * @returns the depth max z
  46536. */
  46537. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  46538. return 1;
  46539. };
  46540. __decorate([
  46541. BABYLON.serialize()
  46542. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  46543. __decorate([
  46544. BABYLON.serialize()
  46545. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  46546. __decorate([
  46547. BABYLON.serialize()
  46548. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  46549. return DirectionalLight;
  46550. }(BABYLON.ShadowLight));
  46551. BABYLON.DirectionalLight = DirectionalLight;
  46552. })(BABYLON || (BABYLON = {}));
  46553. //# sourceMappingURL=babylon.directionalLight.js.map
  46554. "use strict";
  46555. var BABYLON;
  46556. (function (BABYLON) {
  46557. /**
  46558. * A spot light is defined by a position, a direction, an angle, and an exponent.
  46559. * These values define a cone of light starting from the position, emitting toward the direction.
  46560. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  46561. * and the exponent defines the speed of the decay of the light with distance (reach).
  46562. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46563. */
  46564. var SpotLight = /** @class */ (function (_super) {
  46565. __extends(SpotLight, _super);
  46566. /**
  46567. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  46568. * It can cast shadows.
  46569. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46570. * @param name The light friendly name
  46571. * @param position The position of the spot light in the scene
  46572. * @param direction The direction of the light in the scene
  46573. * @param angle The cone angle of the light in Radians
  46574. * @param exponent The light decay speed with the distance from the emission spot
  46575. * @param scene The scene the lights belongs to
  46576. */
  46577. function SpotLight(name, position, direction, angle, exponent, scene) {
  46578. var _this = _super.call(this, name, scene) || this;
  46579. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  46580. _this._projectionTextureLightNear = 1e-6;
  46581. _this._projectionTextureLightFar = 1000.0;
  46582. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  46583. _this._projectionTextureViewLightDirty = true;
  46584. _this._projectionTextureProjectionLightDirty = true;
  46585. _this._projectionTextureDirty = true;
  46586. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  46587. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  46588. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  46589. _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);
  46590. _this.position = position;
  46591. _this.direction = direction;
  46592. _this.angle = angle;
  46593. _this.exponent = exponent;
  46594. return _this;
  46595. }
  46596. Object.defineProperty(SpotLight.prototype, "angle", {
  46597. /**
  46598. * Gets the cone angle of the spot light in Radians.
  46599. */
  46600. get: function () {
  46601. return this._angle;
  46602. },
  46603. /**
  46604. * Sets the cone angle of the spot light in Radians.
  46605. */
  46606. set: function (value) {
  46607. this._angle = value;
  46608. this._projectionTextureProjectionLightDirty = true;
  46609. this.forceProjectionMatrixCompute();
  46610. },
  46611. enumerable: true,
  46612. configurable: true
  46613. });
  46614. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  46615. /**
  46616. * Allows scaling the angle of the light for shadow generation only.
  46617. */
  46618. get: function () {
  46619. return this._shadowAngleScale;
  46620. },
  46621. /**
  46622. * Allows scaling the angle of the light for shadow generation only.
  46623. */
  46624. set: function (value) {
  46625. this._shadowAngleScale = value;
  46626. this.forceProjectionMatrixCompute();
  46627. },
  46628. enumerable: true,
  46629. configurable: true
  46630. });
  46631. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  46632. /**
  46633. * Allows reading the projecton texture
  46634. */
  46635. get: function () {
  46636. return this._projectionTextureMatrix;
  46637. },
  46638. enumerable: true,
  46639. configurable: true
  46640. });
  46641. ;
  46642. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  46643. /**
  46644. * Gets the near clip of the Spotlight for texture projection.
  46645. */
  46646. get: function () {
  46647. return this._projectionTextureLightNear;
  46648. },
  46649. /**
  46650. * Sets the near clip of the Spotlight for texture projection.
  46651. */
  46652. set: function (value) {
  46653. this._projectionTextureLightNear = value;
  46654. this._projectionTextureProjectionLightDirty = true;
  46655. },
  46656. enumerable: true,
  46657. configurable: true
  46658. });
  46659. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  46660. /**
  46661. * Gets the far clip of the Spotlight for texture projection.
  46662. */
  46663. get: function () {
  46664. return this._projectionTextureLightFar;
  46665. },
  46666. /**
  46667. * Sets the far clip of the Spotlight for texture projection.
  46668. */
  46669. set: function (value) {
  46670. this._projectionTextureLightFar = value;
  46671. this._projectionTextureProjectionLightDirty = true;
  46672. },
  46673. enumerable: true,
  46674. configurable: true
  46675. });
  46676. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  46677. /**
  46678. * Gets the Up vector of the Spotlight for texture projection.
  46679. */
  46680. get: function () {
  46681. return this._projectionTextureUpDirection;
  46682. },
  46683. /**
  46684. * Sets the Up vector of the Spotlight for texture projection.
  46685. */
  46686. set: function (value) {
  46687. this._projectionTextureUpDirection = value;
  46688. this._projectionTextureProjectionLightDirty = true;
  46689. },
  46690. enumerable: true,
  46691. configurable: true
  46692. });
  46693. ;
  46694. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  46695. /**
  46696. * Gets the projection texture of the light.
  46697. */
  46698. get: function () {
  46699. return this._projectionTexture;
  46700. },
  46701. /**
  46702. * Sets the projection texture of the light.
  46703. */
  46704. set: function (value) {
  46705. this._projectionTexture = value;
  46706. this._projectionTextureDirty = true;
  46707. },
  46708. enumerable: true,
  46709. configurable: true
  46710. });
  46711. /**
  46712. * Returns the string "SpotLight".
  46713. * @returns the class name
  46714. */
  46715. SpotLight.prototype.getClassName = function () {
  46716. return "SpotLight";
  46717. };
  46718. /**
  46719. * Returns the integer 2.
  46720. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46721. */
  46722. SpotLight.prototype.getTypeID = function () {
  46723. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  46724. };
  46725. /**
  46726. * Overrides the direction setter to recompute the projection texture view light Matrix.
  46727. */
  46728. SpotLight.prototype._setDirection = function (value) {
  46729. _super.prototype._setDirection.call(this, value);
  46730. this._projectionTextureViewLightDirty = true;
  46731. };
  46732. /**
  46733. * Overrides the position setter to recompute the projection texture view light Matrix.
  46734. */
  46735. SpotLight.prototype._setPosition = function (value) {
  46736. _super.prototype._setPosition.call(this, value);
  46737. this._projectionTextureViewLightDirty = true;
  46738. };
  46739. /**
  46740. * 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.
  46741. * Returns the SpotLight.
  46742. */
  46743. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46744. var activeCamera = this.getScene().activeCamera;
  46745. if (!activeCamera) {
  46746. return;
  46747. }
  46748. this._shadowAngleScale = this._shadowAngleScale || 1;
  46749. var angle = this._shadowAngleScale * this._angle;
  46750. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46751. };
  46752. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  46753. this._projectionTextureViewLightDirty = false;
  46754. this._projectionTextureDirty = true;
  46755. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  46756. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  46757. };
  46758. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  46759. this._projectionTextureProjectionLightDirty = false;
  46760. this._projectionTextureDirty = true;
  46761. var light_far = this.projectionTextureLightFar;
  46762. var light_near = this.projectionTextureLightNear;
  46763. var P = light_far / (light_far - light_near);
  46764. var Q = -P * light_near;
  46765. var S = 1.0 / Math.tan(this._angle / 2.0);
  46766. var A = 1.0;
  46767. 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);
  46768. };
  46769. /**
  46770. * Main function for light texture projection matrix computing.
  46771. */
  46772. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  46773. this._projectionTextureDirty = false;
  46774. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  46775. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  46776. };
  46777. SpotLight.prototype._buildUniformLayout = function () {
  46778. this._uniformBuffer.addUniform("vLightData", 4);
  46779. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46780. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46781. this._uniformBuffer.addUniform("vLightDirection", 3);
  46782. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46783. this._uniformBuffer.addUniform("depthValues", 2);
  46784. this._uniformBuffer.create();
  46785. };
  46786. /**
  46787. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  46788. * @param effect The effect to update
  46789. * @param lightIndex The index of the light in the effect to update
  46790. * @returns The spot light
  46791. */
  46792. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  46793. var normalizeDirection;
  46794. if (this.computeTransformedInformation()) {
  46795. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  46796. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  46797. }
  46798. else {
  46799. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  46800. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  46801. }
  46802. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  46803. if (this.projectionTexture && this.projectionTexture.isReady()) {
  46804. if (this._projectionTextureViewLightDirty) {
  46805. this._computeProjectionTextureViewLightMatrix();
  46806. }
  46807. if (this._projectionTextureProjectionLightDirty) {
  46808. this._computeProjectionTextureProjectionLightMatrix();
  46809. }
  46810. if (this._projectionTextureDirty) {
  46811. this._computeProjectionTextureMatrix();
  46812. }
  46813. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  46814. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  46815. }
  46816. return this;
  46817. };
  46818. /**
  46819. * Disposes the light and the associated resources.
  46820. */
  46821. SpotLight.prototype.dispose = function () {
  46822. _super.prototype.dispose.call(this);
  46823. if (this._projectionTexture) {
  46824. this._projectionTexture.dispose();
  46825. }
  46826. };
  46827. __decorate([
  46828. BABYLON.serialize()
  46829. ], SpotLight.prototype, "angle", null);
  46830. __decorate([
  46831. BABYLON.serialize()
  46832. ], SpotLight.prototype, "shadowAngleScale", null);
  46833. __decorate([
  46834. BABYLON.serialize()
  46835. ], SpotLight.prototype, "exponent", void 0);
  46836. __decorate([
  46837. BABYLON.serialize()
  46838. ], SpotLight.prototype, "projectionTextureLightNear", null);
  46839. __decorate([
  46840. BABYLON.serialize()
  46841. ], SpotLight.prototype, "projectionTextureLightFar", null);
  46842. __decorate([
  46843. BABYLON.serialize()
  46844. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  46845. __decorate([
  46846. BABYLON.serializeAsTexture("projectedLightTexture")
  46847. ], SpotLight.prototype, "_projectionTexture", void 0);
  46848. return SpotLight;
  46849. }(BABYLON.ShadowLight));
  46850. BABYLON.SpotLight = SpotLight;
  46851. })(BABYLON || (BABYLON = {}));
  46852. //# sourceMappingURL=babylon.spotLight.js.map
  46853. "use strict";
  46854. var BABYLON;
  46855. (function (BABYLON) {
  46856. /**
  46857. * Class used to override all child animations of a given target
  46858. */
  46859. var AnimationPropertiesOverride = /** @class */ (function () {
  46860. function AnimationPropertiesOverride() {
  46861. /**
  46862. * Gets or sets a value indicating if animation blending must be used
  46863. */
  46864. this.enableBlending = false;
  46865. /**
  46866. * Gets or sets the blending speed to use when enableBlending is true
  46867. */
  46868. this.blendingSpeed = 0.01;
  46869. /**
  46870. * Gets or sets the default loop mode to use
  46871. */
  46872. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  46873. }
  46874. return AnimationPropertiesOverride;
  46875. }());
  46876. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  46877. })(BABYLON || (BABYLON = {}));
  46878. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  46879. "use strict";
  46880. var BABYLON;
  46881. (function (BABYLON) {
  46882. var AnimationRange = /** @class */ (function () {
  46883. function AnimationRange(name, from, to) {
  46884. this.name = name;
  46885. this.from = from;
  46886. this.to = to;
  46887. }
  46888. AnimationRange.prototype.clone = function () {
  46889. return new AnimationRange(this.name, this.from, this.to);
  46890. };
  46891. return AnimationRange;
  46892. }());
  46893. BABYLON.AnimationRange = AnimationRange;
  46894. /**
  46895. * Composed of a frame, and an action function
  46896. */
  46897. var AnimationEvent = /** @class */ (function () {
  46898. function AnimationEvent(frame, action, onlyOnce) {
  46899. this.frame = frame;
  46900. this.action = action;
  46901. this.onlyOnce = onlyOnce;
  46902. this.isDone = false;
  46903. }
  46904. return AnimationEvent;
  46905. }());
  46906. BABYLON.AnimationEvent = AnimationEvent;
  46907. var PathCursor = /** @class */ (function () {
  46908. function PathCursor(path) {
  46909. this.path = path;
  46910. this._onchange = new Array();
  46911. this.value = 0;
  46912. this.animations = new Array();
  46913. }
  46914. PathCursor.prototype.getPoint = function () {
  46915. var point = this.path.getPointAtLengthPosition(this.value);
  46916. return new BABYLON.Vector3(point.x, 0, point.y);
  46917. };
  46918. PathCursor.prototype.moveAhead = function (step) {
  46919. if (step === void 0) { step = 0.002; }
  46920. this.move(step);
  46921. return this;
  46922. };
  46923. PathCursor.prototype.moveBack = function (step) {
  46924. if (step === void 0) { step = 0.002; }
  46925. this.move(-step);
  46926. return this;
  46927. };
  46928. PathCursor.prototype.move = function (step) {
  46929. if (Math.abs(step) > 1) {
  46930. throw "step size should be less than 1.";
  46931. }
  46932. this.value += step;
  46933. this.ensureLimits();
  46934. this.raiseOnChange();
  46935. return this;
  46936. };
  46937. PathCursor.prototype.ensureLimits = function () {
  46938. while (this.value > 1) {
  46939. this.value -= 1;
  46940. }
  46941. while (this.value < 0) {
  46942. this.value += 1;
  46943. }
  46944. return this;
  46945. };
  46946. // used by animation engine
  46947. PathCursor.prototype.raiseOnChange = function () {
  46948. var _this = this;
  46949. this._onchange.forEach(function (f) { return f(_this); });
  46950. return this;
  46951. };
  46952. PathCursor.prototype.onchange = function (f) {
  46953. this._onchange.push(f);
  46954. return this;
  46955. };
  46956. return PathCursor;
  46957. }());
  46958. BABYLON.PathCursor = PathCursor;
  46959. var AnimationKeyInterpolation;
  46960. (function (AnimationKeyInterpolation) {
  46961. /**
  46962. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  46963. */
  46964. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  46965. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  46966. var Animation = /** @class */ (function () {
  46967. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  46968. this.name = name;
  46969. this.targetProperty = targetProperty;
  46970. this.framePerSecond = framePerSecond;
  46971. this.dataType = dataType;
  46972. this.loopMode = loopMode;
  46973. this.enableBlending = enableBlending;
  46974. this._runtimeAnimations = new Array();
  46975. // The set of event that will be linked to this animation
  46976. this._events = new Array();
  46977. this.blendingSpeed = 0.01;
  46978. this._ranges = {};
  46979. this.targetPropertyPath = targetProperty.split(".");
  46980. this.dataType = dataType;
  46981. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  46982. }
  46983. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  46984. var dataType = undefined;
  46985. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  46986. dataType = Animation.ANIMATIONTYPE_FLOAT;
  46987. }
  46988. else if (from instanceof BABYLON.Quaternion) {
  46989. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  46990. }
  46991. else if (from instanceof BABYLON.Vector3) {
  46992. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  46993. }
  46994. else if (from instanceof BABYLON.Vector2) {
  46995. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  46996. }
  46997. else if (from instanceof BABYLON.Color3) {
  46998. dataType = Animation.ANIMATIONTYPE_COLOR3;
  46999. }
  47000. else if (from instanceof BABYLON.Size) {
  47001. dataType = Animation.ANIMATIONTYPE_SIZE;
  47002. }
  47003. if (dataType == undefined) {
  47004. return null;
  47005. }
  47006. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  47007. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  47008. animation.setKeys(keys);
  47009. if (easingFunction !== undefined) {
  47010. animation.setEasingFunction(easingFunction);
  47011. }
  47012. return animation;
  47013. };
  47014. /**
  47015. * Sets up an animation.
  47016. * @param property the property to animate
  47017. * @param animationType the animation type to apply
  47018. * @param easingFunction the easing function used in the animation
  47019. * @returns The created animation
  47020. */
  47021. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  47022. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  47023. animation.setEasingFunction(easingFunction);
  47024. return animation;
  47025. };
  47026. /**
  47027. * Create and start an animation on a node
  47028. * @param {string} name defines the name of the global animation that will be run on all nodes
  47029. * @param {BABYLON.Node} node defines the root node where the animation will take place
  47030. * @param {string} targetProperty defines property to animate
  47031. * @param {number} framePerSecond defines the number of frame per second yo use
  47032. * @param {number} totalFrame defines the number of frames in total
  47033. * @param {any} from defines the initial value
  47034. * @param {any} to defines the final value
  47035. * @param {number} loopMode defines which loop mode you want to use (off by default)
  47036. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  47037. * @param onAnimationEnd defines the callback to call when animation end
  47038. * @returns the animatable created for this animation
  47039. */
  47040. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  47041. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  47042. if (!animation) {
  47043. return null;
  47044. }
  47045. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  47046. };
  47047. /**
  47048. * Create and start an animation on a node and its descendants
  47049. * @param {string} name defines the name of the global animation that will be run on all nodes
  47050. * @param {BABYLON.Node} node defines the root node where the animation will take place
  47051. * @param {boolean} 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.
  47052. * @param {string} targetProperty defines property to animate
  47053. * @param {number} framePerSecond defines the number of frame per second yo use
  47054. * @param {number} totalFrame defines the number of frames in total
  47055. * @param {any} from defines the initial value
  47056. * @param {any} to defines the final value
  47057. * @param {number} loopMode defines which loop mode you want to use (off by default)
  47058. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  47059. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  47060. * @returns the list of animatables created for all nodes
  47061. * @example https://www.babylonjs-playground.com/#MH0VLI
  47062. */
  47063. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  47064. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  47065. if (!animation) {
  47066. return null;
  47067. }
  47068. var scene = node.getScene();
  47069. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  47070. };
  47071. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  47072. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  47073. if (!animation) {
  47074. return null;
  47075. }
  47076. node.animations.push(animation);
  47077. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  47078. };
  47079. /**
  47080. * Transition property of the Camera to the target Value.
  47081. * @param property The property to transition
  47082. * @param targetValue The target Value of the property
  47083. * @param host The object where the property to animate belongs
  47084. * @param scene Scene used to run the animation
  47085. * @param frameRate Framerate (in frame/s) to use
  47086. * @param transition The transition type we want to use
  47087. * @param duration The duration of the animation, in milliseconds
  47088. * @param onAnimationEnd Call back trigger at the end of the animation.
  47089. */
  47090. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  47091. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  47092. if (duration <= 0) {
  47093. host[property] = targetValue;
  47094. if (onAnimationEnd) {
  47095. onAnimationEnd();
  47096. }
  47097. return null;
  47098. }
  47099. var endFrame = frameRate * (duration / 1000);
  47100. transition.setKeys([{
  47101. frame: 0,
  47102. value: host[property].clone ? host[property].clone() : host[property]
  47103. },
  47104. {
  47105. frame: endFrame,
  47106. value: targetValue
  47107. }]);
  47108. if (!host.animations) {
  47109. host.animations = [];
  47110. }
  47111. host.animations.push(transition);
  47112. var animation = scene.beginAnimation(host, 0, endFrame, false);
  47113. animation.onAnimationEnd = onAnimationEnd;
  47114. return animation;
  47115. };
  47116. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  47117. /**
  47118. * Return the array of runtime animations currently using this animation
  47119. */
  47120. get: function () {
  47121. return this._runtimeAnimations;
  47122. },
  47123. enumerable: true,
  47124. configurable: true
  47125. });
  47126. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  47127. get: function () {
  47128. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  47129. var runtimeAnimation = _a[_i];
  47130. if (!runtimeAnimation.isStopped) {
  47131. return true;
  47132. }
  47133. }
  47134. return false;
  47135. },
  47136. enumerable: true,
  47137. configurable: true
  47138. });
  47139. // Methods
  47140. /**
  47141. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  47142. */
  47143. Animation.prototype.toString = function (fullDetails) {
  47144. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  47145. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  47146. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  47147. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  47148. if (fullDetails) {
  47149. ret += ", Ranges: {";
  47150. var first = true;
  47151. for (var name in this._ranges) {
  47152. if (first) {
  47153. ret += ", ";
  47154. first = false;
  47155. }
  47156. ret += name;
  47157. }
  47158. ret += "}";
  47159. }
  47160. return ret;
  47161. };
  47162. /**
  47163. * Add an event to this animation.
  47164. */
  47165. Animation.prototype.addEvent = function (event) {
  47166. this._events.push(event);
  47167. };
  47168. /**
  47169. * Remove all events found at the given frame
  47170. * @param frame
  47171. */
  47172. Animation.prototype.removeEvents = function (frame) {
  47173. for (var index = 0; index < this._events.length; index++) {
  47174. if (this._events[index].frame === frame) {
  47175. this._events.splice(index, 1);
  47176. index--;
  47177. }
  47178. }
  47179. };
  47180. Animation.prototype.getEvents = function () {
  47181. return this._events;
  47182. };
  47183. Animation.prototype.createRange = function (name, from, to) {
  47184. // check name not already in use; could happen for bones after serialized
  47185. if (!this._ranges[name]) {
  47186. this._ranges[name] = new AnimationRange(name, from, to);
  47187. }
  47188. };
  47189. Animation.prototype.deleteRange = function (name, deleteFrames) {
  47190. if (deleteFrames === void 0) { deleteFrames = true; }
  47191. var range = this._ranges[name];
  47192. if (!range) {
  47193. return;
  47194. }
  47195. if (deleteFrames) {
  47196. var from = range.from;
  47197. var to = range.to;
  47198. // this loop MUST go high to low for multiple splices to work
  47199. for (var key = this._keys.length - 1; key >= 0; key--) {
  47200. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  47201. this._keys.splice(key, 1);
  47202. }
  47203. }
  47204. }
  47205. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  47206. };
  47207. Animation.prototype.getRange = function (name) {
  47208. return this._ranges[name];
  47209. };
  47210. Animation.prototype.getKeys = function () {
  47211. return this._keys;
  47212. };
  47213. Animation.prototype.getHighestFrame = function () {
  47214. var ret = 0;
  47215. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  47216. if (ret < this._keys[key].frame) {
  47217. ret = this._keys[key].frame;
  47218. }
  47219. }
  47220. return ret;
  47221. };
  47222. Animation.prototype.getEasingFunction = function () {
  47223. return this._easingFunction;
  47224. };
  47225. Animation.prototype.setEasingFunction = function (easingFunction) {
  47226. this._easingFunction = easingFunction;
  47227. };
  47228. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  47229. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  47230. };
  47231. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47232. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47233. };
  47234. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  47235. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  47236. };
  47237. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47238. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  47239. };
  47240. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  47241. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  47242. };
  47243. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47244. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47245. };
  47246. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  47247. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  47248. };
  47249. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47250. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47251. };
  47252. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  47253. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  47254. };
  47255. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  47256. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  47257. };
  47258. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  47259. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  47260. };
  47261. Animation.prototype.clone = function () {
  47262. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  47263. clone.enableBlending = this.enableBlending;
  47264. clone.blendingSpeed = this.blendingSpeed;
  47265. if (this._keys) {
  47266. clone.setKeys(this._keys);
  47267. }
  47268. if (this._ranges) {
  47269. clone._ranges = {};
  47270. for (var name in this._ranges) {
  47271. var range = this._ranges[name];
  47272. if (!range) {
  47273. continue;
  47274. }
  47275. clone._ranges[name] = range.clone();
  47276. }
  47277. }
  47278. return clone;
  47279. };
  47280. Animation.prototype.setKeys = function (values) {
  47281. this._keys = values.slice(0);
  47282. };
  47283. Animation.prototype.serialize = function () {
  47284. var serializationObject = {};
  47285. serializationObject.name = this.name;
  47286. serializationObject.property = this.targetProperty;
  47287. serializationObject.framePerSecond = this.framePerSecond;
  47288. serializationObject.dataType = this.dataType;
  47289. serializationObject.loopBehavior = this.loopMode;
  47290. serializationObject.enableBlending = this.enableBlending;
  47291. serializationObject.blendingSpeed = this.blendingSpeed;
  47292. var dataType = this.dataType;
  47293. serializationObject.keys = [];
  47294. var keys = this.getKeys();
  47295. for (var index = 0; index < keys.length; index++) {
  47296. var animationKey = keys[index];
  47297. var key = {};
  47298. key.frame = animationKey.frame;
  47299. switch (dataType) {
  47300. case Animation.ANIMATIONTYPE_FLOAT:
  47301. key.values = [animationKey.value];
  47302. break;
  47303. case Animation.ANIMATIONTYPE_QUATERNION:
  47304. case Animation.ANIMATIONTYPE_MATRIX:
  47305. case Animation.ANIMATIONTYPE_VECTOR3:
  47306. case Animation.ANIMATIONTYPE_COLOR3:
  47307. key.values = animationKey.value.asArray();
  47308. break;
  47309. }
  47310. serializationObject.keys.push(key);
  47311. }
  47312. serializationObject.ranges = [];
  47313. for (var name in this._ranges) {
  47314. var source = this._ranges[name];
  47315. if (!source) {
  47316. continue;
  47317. }
  47318. var range = {};
  47319. range.name = name;
  47320. range.from = source.from;
  47321. range.to = source.to;
  47322. serializationObject.ranges.push(range);
  47323. }
  47324. return serializationObject;
  47325. };
  47326. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  47327. get: function () {
  47328. return Animation._ANIMATIONTYPE_FLOAT;
  47329. },
  47330. enumerable: true,
  47331. configurable: true
  47332. });
  47333. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  47334. get: function () {
  47335. return Animation._ANIMATIONTYPE_VECTOR3;
  47336. },
  47337. enumerable: true,
  47338. configurable: true
  47339. });
  47340. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  47341. get: function () {
  47342. return Animation._ANIMATIONTYPE_VECTOR2;
  47343. },
  47344. enumerable: true,
  47345. configurable: true
  47346. });
  47347. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  47348. get: function () {
  47349. return Animation._ANIMATIONTYPE_SIZE;
  47350. },
  47351. enumerable: true,
  47352. configurable: true
  47353. });
  47354. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  47355. get: function () {
  47356. return Animation._ANIMATIONTYPE_QUATERNION;
  47357. },
  47358. enumerable: true,
  47359. configurable: true
  47360. });
  47361. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  47362. get: function () {
  47363. return Animation._ANIMATIONTYPE_MATRIX;
  47364. },
  47365. enumerable: true,
  47366. configurable: true
  47367. });
  47368. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  47369. get: function () {
  47370. return Animation._ANIMATIONTYPE_COLOR3;
  47371. },
  47372. enumerable: true,
  47373. configurable: true
  47374. });
  47375. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  47376. get: function () {
  47377. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  47378. },
  47379. enumerable: true,
  47380. configurable: true
  47381. });
  47382. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  47383. get: function () {
  47384. return Animation._ANIMATIONLOOPMODE_CYCLE;
  47385. },
  47386. enumerable: true,
  47387. configurable: true
  47388. });
  47389. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  47390. get: function () {
  47391. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  47392. },
  47393. enumerable: true,
  47394. configurable: true
  47395. });
  47396. Animation.Parse = function (parsedAnimation) {
  47397. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  47398. var dataType = parsedAnimation.dataType;
  47399. var keys = [];
  47400. var data;
  47401. var index;
  47402. if (parsedAnimation.enableBlending) {
  47403. animation.enableBlending = parsedAnimation.enableBlending;
  47404. }
  47405. if (parsedAnimation.blendingSpeed) {
  47406. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  47407. }
  47408. for (index = 0; index < parsedAnimation.keys.length; index++) {
  47409. var key = parsedAnimation.keys[index];
  47410. var inTangent;
  47411. var outTangent;
  47412. switch (dataType) {
  47413. case Animation.ANIMATIONTYPE_FLOAT:
  47414. data = key.values[0];
  47415. if (key.values.length >= 1) {
  47416. inTangent = key.values[1];
  47417. }
  47418. if (key.values.length >= 2) {
  47419. outTangent = key.values[2];
  47420. }
  47421. break;
  47422. case Animation.ANIMATIONTYPE_QUATERNION:
  47423. data = BABYLON.Quaternion.FromArray(key.values);
  47424. if (key.values.length >= 8) {
  47425. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  47426. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  47427. inTangent = _inTangent;
  47428. }
  47429. }
  47430. if (key.values.length >= 12) {
  47431. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  47432. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  47433. outTangent = _outTangent;
  47434. }
  47435. }
  47436. break;
  47437. case Animation.ANIMATIONTYPE_MATRIX:
  47438. data = BABYLON.Matrix.FromArray(key.values);
  47439. break;
  47440. case Animation.ANIMATIONTYPE_COLOR3:
  47441. data = BABYLON.Color3.FromArray(key.values);
  47442. break;
  47443. case Animation.ANIMATIONTYPE_VECTOR3:
  47444. default:
  47445. data = BABYLON.Vector3.FromArray(key.values);
  47446. break;
  47447. }
  47448. var keyData = {};
  47449. keyData.frame = key.frame;
  47450. keyData.value = data;
  47451. if (inTangent != undefined) {
  47452. keyData.inTangent = inTangent;
  47453. }
  47454. if (outTangent != undefined) {
  47455. keyData.outTangent = outTangent;
  47456. }
  47457. keys.push(keyData);
  47458. }
  47459. animation.setKeys(keys);
  47460. if (parsedAnimation.ranges) {
  47461. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  47462. data = parsedAnimation.ranges[index];
  47463. animation.createRange(data.name, data.from, data.to);
  47464. }
  47465. }
  47466. return animation;
  47467. };
  47468. Animation.AppendSerializedAnimations = function (source, destination) {
  47469. if (source.animations) {
  47470. destination.animations = [];
  47471. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  47472. var animation = source.animations[animationIndex];
  47473. destination.animations.push(animation.serialize());
  47474. }
  47475. }
  47476. };
  47477. Animation.AllowMatricesInterpolation = false;
  47478. // Statics
  47479. Animation._ANIMATIONTYPE_FLOAT = 0;
  47480. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  47481. Animation._ANIMATIONTYPE_QUATERNION = 2;
  47482. Animation._ANIMATIONTYPE_MATRIX = 3;
  47483. Animation._ANIMATIONTYPE_COLOR3 = 4;
  47484. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  47485. Animation._ANIMATIONTYPE_SIZE = 6;
  47486. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  47487. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  47488. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  47489. return Animation;
  47490. }());
  47491. BABYLON.Animation = Animation;
  47492. })(BABYLON || (BABYLON = {}));
  47493. //# sourceMappingURL=babylon.animation.js.map
  47494. "use strict";
  47495. var BABYLON;
  47496. (function (BABYLON) {
  47497. /**
  47498. * This class defines the direct association between an animation and a target
  47499. */
  47500. var TargetedAnimation = /** @class */ (function () {
  47501. function TargetedAnimation() {
  47502. }
  47503. return TargetedAnimation;
  47504. }());
  47505. BABYLON.TargetedAnimation = TargetedAnimation;
  47506. /**
  47507. * Use this class to create coordinated animations on multiple targets
  47508. */
  47509. var AnimationGroup = /** @class */ (function () {
  47510. function AnimationGroup(name, scene) {
  47511. if (scene === void 0) { scene = null; }
  47512. this.name = name;
  47513. this._targetedAnimations = new Array();
  47514. this._animatables = new Array();
  47515. this._from = Number.MAX_VALUE;
  47516. this._to = -Number.MAX_VALUE;
  47517. this._speedRatio = 1;
  47518. this.onAnimationEndObservable = new BABYLON.Observable();
  47519. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  47520. this._scene.animationGroups.push(this);
  47521. }
  47522. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  47523. /**
  47524. * Define if the animations are started
  47525. */
  47526. get: function () {
  47527. return this._isStarted;
  47528. },
  47529. enumerable: true,
  47530. configurable: true
  47531. });
  47532. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  47533. /**
  47534. * Gets or sets the speed ratio to use for all animations
  47535. */
  47536. get: function () {
  47537. return this._speedRatio;
  47538. },
  47539. /**
  47540. * Gets or sets the speed ratio to use for all animations
  47541. */
  47542. set: function (value) {
  47543. if (this._speedRatio === value) {
  47544. return;
  47545. }
  47546. this._speedRatio = value;
  47547. for (var index = 0; index < this._animatables.length; index++) {
  47548. var animatable = this._animatables[index];
  47549. animatable.speedRatio = this._speedRatio;
  47550. }
  47551. },
  47552. enumerable: true,
  47553. configurable: true
  47554. });
  47555. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  47556. /**
  47557. * Gets the targeted animations for this animation group
  47558. */
  47559. get: function () {
  47560. return this._targetedAnimations;
  47561. },
  47562. enumerable: true,
  47563. configurable: true
  47564. });
  47565. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  47566. /**
  47567. * returning the list of animatables controlled by this animation group.
  47568. */
  47569. get: function () {
  47570. return this._animatables;
  47571. },
  47572. enumerable: true,
  47573. configurable: true
  47574. });
  47575. /**
  47576. * Add an animation (with its target) in the group
  47577. * @param animation defines the animation we want to add
  47578. * @param target defines the target of the animation
  47579. * @returns the {BABYLON.TargetedAnimation} object
  47580. */
  47581. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  47582. var targetedAnimation = {
  47583. animation: animation,
  47584. target: target
  47585. };
  47586. var keys = animation.getKeys();
  47587. if (this._from > keys[0].frame) {
  47588. this._from = keys[0].frame;
  47589. }
  47590. if (this._to < keys[keys.length - 1].frame) {
  47591. this._to = keys[keys.length - 1].frame;
  47592. }
  47593. this._targetedAnimations.push(targetedAnimation);
  47594. return targetedAnimation;
  47595. };
  47596. /**
  47597. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  47598. * It can add constant keys at begin or end
  47599. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  47600. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  47601. */
  47602. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  47603. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  47604. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  47605. beginFrame = Math.max(beginFrame, this._from);
  47606. endFrame = Math.min(endFrame, this._to);
  47607. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47608. var targetedAnimation = this._targetedAnimations[index];
  47609. var keys = targetedAnimation.animation.getKeys();
  47610. var startKey = keys[0];
  47611. var endKey = keys[keys.length - 1];
  47612. if (startKey.frame > beginFrame) {
  47613. var newKey = {
  47614. frame: beginFrame,
  47615. value: startKey.value,
  47616. inTangent: startKey.inTangent,
  47617. outTangent: startKey.outTangent,
  47618. interpolation: startKey.interpolation
  47619. };
  47620. keys.splice(0, 0, newKey);
  47621. }
  47622. if (endKey.frame < endFrame) {
  47623. var newKey = {
  47624. frame: endFrame,
  47625. value: endKey.value,
  47626. inTangent: endKey.outTangent,
  47627. outTangent: endKey.outTangent,
  47628. interpolation: endKey.interpolation
  47629. };
  47630. keys.push(newKey);
  47631. }
  47632. }
  47633. return this;
  47634. };
  47635. /**
  47636. * Start all animations on given targets
  47637. * @param loop defines if animations must loop
  47638. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  47639. * @param from defines the from key (optional)
  47640. * @param to defines the to key (optional)
  47641. * @returns the current animation group
  47642. */
  47643. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  47644. var _this = this;
  47645. if (loop === void 0) { loop = false; }
  47646. if (speedRatio === void 0) { speedRatio = 1; }
  47647. if (this._isStarted || this._targetedAnimations.length === 0) {
  47648. return this;
  47649. }
  47650. var _loop_1 = function () {
  47651. var targetedAnimation = this_1._targetedAnimations[index];
  47652. if (!targetedAnimation.target.animations) {
  47653. targetedAnimation.target.animations = [];
  47654. }
  47655. if (targetedAnimation.target.animations.indexOf(targetedAnimation.animation) === -1) {
  47656. targetedAnimation.target.animations.push(targetedAnimation.animation);
  47657. }
  47658. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio, function () {
  47659. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  47660. }));
  47661. };
  47662. var this_1 = this;
  47663. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47664. _loop_1();
  47665. }
  47666. this._speedRatio = speedRatio;
  47667. this._isStarted = true;
  47668. return this;
  47669. };
  47670. /**
  47671. * Pause all animations
  47672. */
  47673. AnimationGroup.prototype.pause = function () {
  47674. if (!this._isStarted) {
  47675. return this;
  47676. }
  47677. for (var index = 0; index < this._animatables.length; index++) {
  47678. var animatable = this._animatables[index];
  47679. animatable.pause();
  47680. }
  47681. return this;
  47682. };
  47683. /**
  47684. * Play all animations to initial state
  47685. * This function will start() the animations if they were not started or will restart() them if they were paused
  47686. * @param loop defines if animations must loop
  47687. */
  47688. AnimationGroup.prototype.play = function (loop) {
  47689. if (this.isStarted) {
  47690. if (loop !== undefined) {
  47691. for (var index = 0; index < this._animatables.length; index++) {
  47692. var animatable = this._animatables[index];
  47693. animatable.loopAnimation = loop;
  47694. }
  47695. }
  47696. this.restart();
  47697. }
  47698. else {
  47699. this.start(loop, this._speedRatio);
  47700. }
  47701. return this;
  47702. };
  47703. /**
  47704. * Reset all animations to initial state
  47705. */
  47706. AnimationGroup.prototype.reset = function () {
  47707. if (!this._isStarted) {
  47708. return this;
  47709. }
  47710. for (var index = 0; index < this._animatables.length; index++) {
  47711. var animatable = this._animatables[index];
  47712. animatable.reset();
  47713. }
  47714. return this;
  47715. };
  47716. /**
  47717. * Restart animations from key 0
  47718. */
  47719. AnimationGroup.prototype.restart = function () {
  47720. if (!this._isStarted) {
  47721. return this;
  47722. }
  47723. for (var index = 0; index < this._animatables.length; index++) {
  47724. var animatable = this._animatables[index];
  47725. animatable.restart();
  47726. }
  47727. return this;
  47728. };
  47729. /**
  47730. * Stop all animations
  47731. */
  47732. AnimationGroup.prototype.stop = function () {
  47733. if (!this._isStarted) {
  47734. return this;
  47735. }
  47736. for (var index = 0; index < this._animatables.length; index++) {
  47737. var animatable = this._animatables[index];
  47738. animatable.stop();
  47739. }
  47740. this._isStarted = false;
  47741. return this;
  47742. };
  47743. /**
  47744. * Goes to a specific frame in this animation group
  47745. *
  47746. * @param frame the frame number to go to
  47747. * @return the animationGroup
  47748. */
  47749. AnimationGroup.prototype.goToFrame = function (frame) {
  47750. if (!this._isStarted) {
  47751. return this;
  47752. }
  47753. for (var index = 0; index < this._animatables.length; index++) {
  47754. var animatable = this._animatables[index];
  47755. animatable.goToFrame(frame);
  47756. }
  47757. return this;
  47758. };
  47759. /**
  47760. * Dispose all associated resources
  47761. */
  47762. AnimationGroup.prototype.dispose = function () {
  47763. this._targetedAnimations = [];
  47764. this._animatables = [];
  47765. var index = this._scene.animationGroups.indexOf(this);
  47766. if (index > -1) {
  47767. this._scene.animationGroups.splice(index, 1);
  47768. }
  47769. };
  47770. return AnimationGroup;
  47771. }());
  47772. BABYLON.AnimationGroup = AnimationGroup;
  47773. })(BABYLON || (BABYLON = {}));
  47774. //# sourceMappingURL=babylon.animationGroup.js.map
  47775. "use strict";
  47776. var BABYLON;
  47777. (function (BABYLON) {
  47778. var RuntimeAnimation = /** @class */ (function () {
  47779. /**
  47780. * Create a new RuntimeAnimation object
  47781. * @param target defines the target of the animation
  47782. * @param animation defines the source {BABYLON.Animation} object
  47783. * @param scene defines the hosting scene
  47784. * @param host defines the initiating Animatable
  47785. */
  47786. function RuntimeAnimation(target, animation, scene, host) {
  47787. this._currentFrame = 0;
  47788. this._offsetsCache = {};
  47789. this._highLimitsCache = {};
  47790. this._stopped = false;
  47791. this._blendingFactor = 0;
  47792. this._targetPath = "";
  47793. this._weight = 1.0;
  47794. this._ratioOffset = 0;
  47795. this._previousDelay = 0;
  47796. this._previousRatio = 0;
  47797. this._animation = animation;
  47798. this._target = target;
  47799. this._scene = scene;
  47800. this._host = host;
  47801. animation._runtimeAnimations.push(this);
  47802. }
  47803. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  47804. /**
  47805. * Gets the current frame
  47806. */
  47807. get: function () {
  47808. return this._currentFrame;
  47809. },
  47810. enumerable: true,
  47811. configurable: true
  47812. });
  47813. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  47814. /**
  47815. * Gets the weight of the runtime animation
  47816. */
  47817. get: function () {
  47818. return this._weight;
  47819. },
  47820. enumerable: true,
  47821. configurable: true
  47822. });
  47823. Object.defineProperty(RuntimeAnimation.prototype, "originalValue", {
  47824. /**
  47825. * Gets the original value of the runtime animation
  47826. */
  47827. get: function () {
  47828. return this._originalValue;
  47829. },
  47830. enumerable: true,
  47831. configurable: true
  47832. });
  47833. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  47834. /**
  47835. * Gets the current value of the runtime animation
  47836. */
  47837. get: function () {
  47838. return this._currentValue;
  47839. },
  47840. enumerable: true,
  47841. configurable: true
  47842. });
  47843. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  47844. /**
  47845. * Gets the path where to store the animated value in the target
  47846. */
  47847. get: function () {
  47848. return this._targetPath;
  47849. },
  47850. enumerable: true,
  47851. configurable: true
  47852. });
  47853. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  47854. /**
  47855. * Gets the actual target of the runtime animation
  47856. */
  47857. get: function () {
  47858. return this._activeTarget;
  47859. },
  47860. enumerable: true,
  47861. configurable: true
  47862. });
  47863. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  47864. get: function () {
  47865. return this._animation;
  47866. },
  47867. enumerable: true,
  47868. configurable: true
  47869. });
  47870. RuntimeAnimation.prototype.reset = function () {
  47871. this._offsetsCache = {};
  47872. this._highLimitsCache = {};
  47873. this._currentFrame = 0;
  47874. this._blendingFactor = 0;
  47875. this._originalValue = null;
  47876. };
  47877. RuntimeAnimation.prototype.isStopped = function () {
  47878. return this._stopped;
  47879. };
  47880. RuntimeAnimation.prototype.dispose = function () {
  47881. var index = this._animation.runtimeAnimations.indexOf(this);
  47882. if (index > -1) {
  47883. this._animation.runtimeAnimations.splice(index, 1);
  47884. }
  47885. };
  47886. RuntimeAnimation.prototype._getKeyValue = function (value) {
  47887. if (typeof value === "function") {
  47888. return value();
  47889. }
  47890. return value;
  47891. };
  47892. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  47893. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  47894. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  47895. }
  47896. this._currentFrame = currentFrame;
  47897. var keys = this._animation.getKeys();
  47898. // Try to get a hash to find the right key
  47899. 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));
  47900. if (keys[startKeyIndex].frame >= currentFrame) {
  47901. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  47902. startKeyIndex--;
  47903. }
  47904. }
  47905. for (var key = startKeyIndex; key < keys.length; key++) {
  47906. var endKey = keys[key + 1];
  47907. if (endKey.frame >= currentFrame) {
  47908. var startKey = keys[key];
  47909. var startValue = this._getKeyValue(startKey.value);
  47910. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  47911. return startValue;
  47912. }
  47913. var endValue = this._getKeyValue(endKey.value);
  47914. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  47915. var frameDelta = endKey.frame - startKey.frame;
  47916. // gradient : percent of currentFrame between the frame inf and the frame sup
  47917. var gradient = (currentFrame - startKey.frame) / frameDelta;
  47918. // check for easingFunction and correction of gradient
  47919. var easingFunction = this._animation.getEasingFunction();
  47920. if (easingFunction != null) {
  47921. gradient = easingFunction.ease(gradient);
  47922. }
  47923. switch (this._animation.dataType) {
  47924. // Float
  47925. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47926. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  47927. switch (loopMode) {
  47928. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47929. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47930. return floatValue;
  47931. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47932. return offsetValue * repeatCount + floatValue;
  47933. }
  47934. break;
  47935. // Quaternion
  47936. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47937. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  47938. switch (loopMode) {
  47939. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47940. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47941. return quatValue;
  47942. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47943. return quatValue.add(offsetValue.scale(repeatCount));
  47944. }
  47945. return quatValue;
  47946. // Vector3
  47947. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47948. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  47949. switch (loopMode) {
  47950. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47951. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47952. return vec3Value;
  47953. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47954. return vec3Value.add(offsetValue.scale(repeatCount));
  47955. }
  47956. // Vector2
  47957. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47958. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  47959. switch (loopMode) {
  47960. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47961. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47962. return vec2Value;
  47963. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47964. return vec2Value.add(offsetValue.scale(repeatCount));
  47965. }
  47966. // Size
  47967. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47968. switch (loopMode) {
  47969. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47970. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47971. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  47972. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47973. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47974. }
  47975. // Color3
  47976. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47977. switch (loopMode) {
  47978. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47979. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47980. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  47981. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47982. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47983. }
  47984. // Matrix
  47985. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  47986. switch (loopMode) {
  47987. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47988. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47989. if (BABYLON.Animation.AllowMatricesInterpolation) {
  47990. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  47991. }
  47992. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47993. return startValue;
  47994. }
  47995. default:
  47996. break;
  47997. }
  47998. break;
  47999. }
  48000. }
  48001. return this._getKeyValue(keys[keys.length - 1].value);
  48002. };
  48003. /**
  48004. * Affect the interpolated value to the target
  48005. * @param currentValue defines the value computed by the animation
  48006. * @param weight defines the weight to apply to this value
  48007. */
  48008. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  48009. if (weight === void 0) { weight = 1.0; }
  48010. // Set value
  48011. var path;
  48012. var destination;
  48013. var targetPropertyPath = this._animation.targetPropertyPath;
  48014. if (targetPropertyPath.length > 1) {
  48015. var property = this._target[targetPropertyPath[0]];
  48016. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  48017. property = property[targetPropertyPath[index]];
  48018. }
  48019. path = targetPropertyPath[targetPropertyPath.length - 1];
  48020. destination = property;
  48021. }
  48022. else {
  48023. path = targetPropertyPath[0];
  48024. destination = this._target;
  48025. }
  48026. this._targetPath = path;
  48027. this._activeTarget = destination;
  48028. this._weight = weight;
  48029. // Blending
  48030. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  48031. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  48032. if (enableBlending && this._blendingFactor <= 1.0) {
  48033. if (!this._originalBlendValue) {
  48034. var originalValue = destination[path];
  48035. if (originalValue.clone) {
  48036. this._originalBlendValue = originalValue.clone();
  48037. }
  48038. else {
  48039. this._originalBlendValue = originalValue;
  48040. }
  48041. }
  48042. }
  48043. if (weight !== -1.0) {
  48044. if (!this._originalValue) {
  48045. var originalValue = void 0;
  48046. if (destination.getRestPose) {
  48047. originalValue = destination.getRestPose();
  48048. }
  48049. else {
  48050. originalValue = destination[path];
  48051. }
  48052. if (originalValue.clone) {
  48053. this._originalValue = originalValue.clone();
  48054. }
  48055. else {
  48056. this._originalValue = originalValue;
  48057. }
  48058. }
  48059. }
  48060. if (enableBlending && this._blendingFactor <= 1.0) {
  48061. if (this._originalBlendValue.prototype) {
  48062. if (this._originalBlendValue.prototype.Lerp) {
  48063. this._currentValue = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  48064. }
  48065. else {
  48066. this._currentValue = currentValue;
  48067. }
  48068. }
  48069. else if (this._originalBlendValue.m) {
  48070. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  48071. }
  48072. else {
  48073. this._currentValue = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  48074. }
  48075. this._blendingFactor += blendingSpeed;
  48076. }
  48077. else {
  48078. this._currentValue = currentValue;
  48079. }
  48080. if (weight !== -1.0) {
  48081. this._scene._registerTargetForLateAnimationBinding(this);
  48082. }
  48083. else {
  48084. destination[path] = this._currentValue;
  48085. }
  48086. if (this._target.markAsDirty) {
  48087. this._target.markAsDirty(this._animation.targetProperty);
  48088. }
  48089. };
  48090. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  48091. if (this._target && this._target.animationPropertiesOverride) {
  48092. return this._target.animationPropertiesOverride.loopMode;
  48093. }
  48094. return this._animation.loopMode;
  48095. };
  48096. /**
  48097. * Move the current animation to a given frame
  48098. * @param frame defines the frame to move to
  48099. */
  48100. RuntimeAnimation.prototype.goToFrame = function (frame) {
  48101. var keys = this._animation.getKeys();
  48102. if (frame < keys[0].frame) {
  48103. frame = keys[0].frame;
  48104. }
  48105. else if (frame > keys[keys.length - 1].frame) {
  48106. frame = keys[keys.length - 1].frame;
  48107. }
  48108. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  48109. this.setValue(currentValue, -1);
  48110. };
  48111. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  48112. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  48113. this._ratioOffset = this._previousRatio - newRatio;
  48114. };
  48115. /**
  48116. * Execute the current animation
  48117. * @param delay defines the delay to add to the current frame
  48118. * @param from defines the lower bound of the animation range
  48119. * @param to defines the upper bound of the animation range
  48120. * @param loop defines if the current animation must loop
  48121. * @param speedRatio defines the current speed ratio
  48122. * @param weight defines the weight of the animation (default is -1 so no weight)
  48123. * @returns a boolean indicating if the animation has ended
  48124. */
  48125. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  48126. if (weight === void 0) { weight = -1.0; }
  48127. var targetPropertyPath = this._animation.targetPropertyPath;
  48128. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  48129. this._stopped = true;
  48130. return false;
  48131. }
  48132. var returnValue = true;
  48133. var keys = this._animation.getKeys();
  48134. // Adding a start key at frame 0 if missing
  48135. if (keys[0].frame !== 0) {
  48136. var newKey = { frame: 0, value: keys[0].value };
  48137. keys.splice(0, 0, newKey);
  48138. }
  48139. // Check limits
  48140. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  48141. from = keys[0].frame;
  48142. }
  48143. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  48144. to = keys[keys.length - 1].frame;
  48145. }
  48146. //to and from cannot be the same key
  48147. if (from === to) {
  48148. if (from > keys[0].frame) {
  48149. from--;
  48150. }
  48151. else if (to < keys[keys.length - 1].frame) {
  48152. to++;
  48153. }
  48154. }
  48155. // Compute ratio
  48156. var range = to - from;
  48157. var offsetValue;
  48158. // ratio represents the frame delta between from and to
  48159. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  48160. var highLimitValue = 0;
  48161. this._previousDelay = delay;
  48162. this._previousRatio = ratio;
  48163. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  48164. returnValue = false;
  48165. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  48166. }
  48167. else {
  48168. // Get max value if required
  48169. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  48170. var keyOffset = to.toString() + from.toString();
  48171. if (!this._offsetsCache[keyOffset]) {
  48172. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  48173. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  48174. switch (this._animation.dataType) {
  48175. // Float
  48176. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  48177. this._offsetsCache[keyOffset] = toValue - fromValue;
  48178. break;
  48179. // Quaternion
  48180. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  48181. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48182. break;
  48183. // Vector3
  48184. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  48185. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48186. // Vector2
  48187. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  48188. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48189. // Size
  48190. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  48191. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48192. // Color3
  48193. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  48194. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48195. default:
  48196. break;
  48197. }
  48198. this._highLimitsCache[keyOffset] = toValue;
  48199. }
  48200. highLimitValue = this._highLimitsCache[keyOffset];
  48201. offsetValue = this._offsetsCache[keyOffset];
  48202. }
  48203. }
  48204. if (offsetValue === undefined) {
  48205. switch (this._animation.dataType) {
  48206. // Float
  48207. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  48208. offsetValue = 0;
  48209. break;
  48210. // Quaternion
  48211. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  48212. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  48213. break;
  48214. // Vector3
  48215. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  48216. offsetValue = BABYLON.Vector3.Zero();
  48217. break;
  48218. // Vector2
  48219. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  48220. offsetValue = BABYLON.Vector2.Zero();
  48221. break;
  48222. // Size
  48223. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  48224. offsetValue = BABYLON.Size.Zero();
  48225. break;
  48226. // Color3
  48227. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  48228. offsetValue = BABYLON.Color3.Black();
  48229. }
  48230. }
  48231. // Compute value
  48232. var repeatCount = (ratio / range) >> 0;
  48233. var currentFrame = returnValue ? from + ratio % range : to;
  48234. // Need to normalize?
  48235. if (this._host && this._host.syncRoot) {
  48236. var syncRoot = this._host.syncRoot;
  48237. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  48238. currentFrame = from + (to - from) * hostNormalizedFrame;
  48239. }
  48240. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  48241. // Set value
  48242. this.setValue(currentValue, weight);
  48243. // Check events
  48244. var events = this._animation.getEvents();
  48245. for (var index = 0; index < events.length; index++) {
  48246. // Make sure current frame has passed event frame and that event frame is within the current range
  48247. // Also, handle both forward and reverse animations
  48248. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  48249. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  48250. var event = events[index];
  48251. if (!event.isDone) {
  48252. // If event should be done only once, remove it.
  48253. if (event.onlyOnce) {
  48254. events.splice(index, 1);
  48255. index--;
  48256. }
  48257. event.isDone = true;
  48258. event.action();
  48259. } // Don't do anything if the event has already be done.
  48260. }
  48261. else if (events[index].isDone && !events[index].onlyOnce) {
  48262. // reset event, the animation is looping
  48263. events[index].isDone = false;
  48264. }
  48265. }
  48266. if (!returnValue) {
  48267. this._stopped = true;
  48268. }
  48269. return returnValue;
  48270. };
  48271. return RuntimeAnimation;
  48272. }());
  48273. BABYLON.RuntimeAnimation = RuntimeAnimation;
  48274. })(BABYLON || (BABYLON = {}));
  48275. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  48276. "use strict";
  48277. var BABYLON;
  48278. (function (BABYLON) {
  48279. var Animatable = /** @class */ (function () {
  48280. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  48281. if (fromFrame === void 0) { fromFrame = 0; }
  48282. if (toFrame === void 0) { toFrame = 100; }
  48283. if (loopAnimation === void 0) { loopAnimation = false; }
  48284. if (speedRatio === void 0) { speedRatio = 1.0; }
  48285. this.target = target;
  48286. this.fromFrame = fromFrame;
  48287. this.toFrame = toFrame;
  48288. this.loopAnimation = loopAnimation;
  48289. this.onAnimationEnd = onAnimationEnd;
  48290. this._localDelayOffset = null;
  48291. this._pausedDelay = null;
  48292. this._runtimeAnimations = new Array();
  48293. this._paused = false;
  48294. this._speedRatio = 1;
  48295. this._weight = -1.0;
  48296. this.animationStarted = false;
  48297. if (animations) {
  48298. this.appendAnimations(target, animations);
  48299. }
  48300. this._speedRatio = speedRatio;
  48301. this._scene = scene;
  48302. scene._activeAnimatables.push(this);
  48303. }
  48304. Object.defineProperty(Animatable.prototype, "syncRoot", {
  48305. /**
  48306. * Gets the root Animatable used to synchronize and normalize animations
  48307. */
  48308. get: function () {
  48309. return this._syncRoot;
  48310. },
  48311. enumerable: true,
  48312. configurable: true
  48313. });
  48314. Object.defineProperty(Animatable.prototype, "masterFrame", {
  48315. /**
  48316. * Gets the current frame of the first RuntimeAnimation
  48317. * Used to synchronize Animatables
  48318. */
  48319. get: function () {
  48320. if (this._runtimeAnimations.length === 0) {
  48321. return 0;
  48322. }
  48323. return this._runtimeAnimations[0].currentFrame;
  48324. },
  48325. enumerable: true,
  48326. configurable: true
  48327. });
  48328. Object.defineProperty(Animatable.prototype, "weight", {
  48329. /**
  48330. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  48331. */
  48332. get: function () {
  48333. return this._weight;
  48334. },
  48335. set: function (value) {
  48336. if (value === -1) {
  48337. this._weight = -1;
  48338. return;
  48339. }
  48340. // Else weight must be in [0, 1] range
  48341. this._weight = Math.min(Math.max(value, 0), 1.0);
  48342. },
  48343. enumerable: true,
  48344. configurable: true
  48345. });
  48346. Object.defineProperty(Animatable.prototype, "speedRatio", {
  48347. /**
  48348. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  48349. */
  48350. get: function () {
  48351. return this._speedRatio;
  48352. },
  48353. set: function (value) {
  48354. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  48355. var animation = this._runtimeAnimations[index];
  48356. animation._prepareForSpeedRatioChange(value);
  48357. }
  48358. this._speedRatio = value;
  48359. },
  48360. enumerable: true,
  48361. configurable: true
  48362. });
  48363. // Methods
  48364. /**
  48365. * Synchronize and normalize current Animatable with a source Animatable.
  48366. * This is useful when using animation weights and when animations are not of the same length
  48367. * @param root defines the root Animatable to synchronize with
  48368. * @returns the current Animatable
  48369. */
  48370. Animatable.prototype.syncWith = function (root) {
  48371. this._syncRoot = root;
  48372. if (root) {
  48373. // Make sure this animatable will animate after the root
  48374. var index = this._scene._activeAnimatables.indexOf(this);
  48375. if (index > -1) {
  48376. this._scene._activeAnimatables.splice(index, 1);
  48377. this._scene._activeAnimatables.push(this);
  48378. }
  48379. }
  48380. return this;
  48381. };
  48382. Animatable.prototype.getAnimations = function () {
  48383. return this._runtimeAnimations;
  48384. };
  48385. Animatable.prototype.appendAnimations = function (target, animations) {
  48386. for (var index = 0; index < animations.length; index++) {
  48387. var animation = animations[index];
  48388. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  48389. }
  48390. };
  48391. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  48392. var runtimeAnimations = this._runtimeAnimations;
  48393. for (var index = 0; index < runtimeAnimations.length; index++) {
  48394. if (runtimeAnimations[index].animation.targetProperty === property) {
  48395. return runtimeAnimations[index].animation;
  48396. }
  48397. }
  48398. return null;
  48399. };
  48400. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  48401. var runtimeAnimations = this._runtimeAnimations;
  48402. for (var index = 0; index < runtimeAnimations.length; index++) {
  48403. if (runtimeAnimations[index].animation.targetProperty === property) {
  48404. return runtimeAnimations[index];
  48405. }
  48406. }
  48407. return null;
  48408. };
  48409. Animatable.prototype.reset = function () {
  48410. var runtimeAnimations = this._runtimeAnimations;
  48411. for (var index = 0; index < runtimeAnimations.length; index++) {
  48412. runtimeAnimations[index].reset();
  48413. }
  48414. // Reset to original value
  48415. for (index = 0; index < runtimeAnimations.length; index++) {
  48416. var animation = runtimeAnimations[index];
  48417. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  48418. }
  48419. this._localDelayOffset = null;
  48420. this._pausedDelay = null;
  48421. };
  48422. Animatable.prototype.enableBlending = function (blendingSpeed) {
  48423. var runtimeAnimations = this._runtimeAnimations;
  48424. for (var index = 0; index < runtimeAnimations.length; index++) {
  48425. runtimeAnimations[index].animation.enableBlending = true;
  48426. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  48427. }
  48428. };
  48429. Animatable.prototype.disableBlending = function () {
  48430. var runtimeAnimations = this._runtimeAnimations;
  48431. for (var index = 0; index < runtimeAnimations.length; index++) {
  48432. runtimeAnimations[index].animation.enableBlending = false;
  48433. }
  48434. };
  48435. Animatable.prototype.goToFrame = function (frame) {
  48436. var runtimeAnimations = this._runtimeAnimations;
  48437. if (runtimeAnimations[0]) {
  48438. var fps = runtimeAnimations[0].animation.framePerSecond;
  48439. var currentFrame = runtimeAnimations[0].currentFrame;
  48440. var adjustTime = frame - currentFrame;
  48441. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  48442. if (this._localDelayOffset === null) {
  48443. this._localDelayOffset = 0;
  48444. }
  48445. this._localDelayOffset -= delay;
  48446. }
  48447. for (var index = 0; index < runtimeAnimations.length; index++) {
  48448. runtimeAnimations[index].goToFrame(frame);
  48449. }
  48450. };
  48451. Animatable.prototype.pause = function () {
  48452. if (this._paused) {
  48453. return;
  48454. }
  48455. this._paused = true;
  48456. };
  48457. Animatable.prototype.restart = function () {
  48458. this._paused = false;
  48459. };
  48460. Animatable.prototype.stop = function (animationName) {
  48461. if (animationName) {
  48462. var idx = this._scene._activeAnimatables.indexOf(this);
  48463. if (idx > -1) {
  48464. var runtimeAnimations = this._runtimeAnimations;
  48465. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  48466. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  48467. continue;
  48468. }
  48469. runtimeAnimations[index].dispose();
  48470. runtimeAnimations.splice(index, 1);
  48471. }
  48472. if (runtimeAnimations.length == 0) {
  48473. this._scene._activeAnimatables.splice(idx, 1);
  48474. if (this.onAnimationEnd) {
  48475. this.onAnimationEnd();
  48476. }
  48477. }
  48478. }
  48479. }
  48480. else {
  48481. var index = this._scene._activeAnimatables.indexOf(this);
  48482. if (index > -1) {
  48483. this._scene._activeAnimatables.splice(index, 1);
  48484. var runtimeAnimations = this._runtimeAnimations;
  48485. for (var index = 0; index < runtimeAnimations.length; index++) {
  48486. runtimeAnimations[index].dispose();
  48487. }
  48488. if (this.onAnimationEnd) {
  48489. this.onAnimationEnd();
  48490. }
  48491. }
  48492. }
  48493. };
  48494. Animatable.prototype._animate = function (delay) {
  48495. if (this._paused) {
  48496. this.animationStarted = false;
  48497. if (this._pausedDelay === null) {
  48498. this._pausedDelay = delay;
  48499. }
  48500. return true;
  48501. }
  48502. if (this._localDelayOffset === null) {
  48503. this._localDelayOffset = delay;
  48504. this._pausedDelay = null;
  48505. }
  48506. else if (this._pausedDelay !== null) {
  48507. this._localDelayOffset += delay - this._pausedDelay;
  48508. this._pausedDelay = null;
  48509. }
  48510. if (this._weight === 0) {
  48511. return true;
  48512. }
  48513. // Animating
  48514. var running = false;
  48515. var runtimeAnimations = this._runtimeAnimations;
  48516. var index;
  48517. for (index = 0; index < runtimeAnimations.length; index++) {
  48518. var animation = runtimeAnimations[index];
  48519. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  48520. running = running || isRunning;
  48521. }
  48522. this.animationStarted = running;
  48523. if (!running) {
  48524. // Remove from active animatables
  48525. index = this._scene._activeAnimatables.indexOf(this);
  48526. this._scene._activeAnimatables.splice(index, 1);
  48527. // Dispose all runtime animations
  48528. for (index = 0; index < runtimeAnimations.length; index++) {
  48529. runtimeAnimations[index].dispose();
  48530. }
  48531. }
  48532. if (!running && this.onAnimationEnd) {
  48533. this.onAnimationEnd();
  48534. this.onAnimationEnd = null;
  48535. }
  48536. return running;
  48537. };
  48538. return Animatable;
  48539. }());
  48540. BABYLON.Animatable = Animatable;
  48541. })(BABYLON || (BABYLON = {}));
  48542. //# sourceMappingURL=babylon.animatable.js.map
  48543. "use strict";
  48544. var BABYLON;
  48545. (function (BABYLON) {
  48546. var EasingFunction = /** @class */ (function () {
  48547. function EasingFunction() {
  48548. // Properties
  48549. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  48550. }
  48551. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  48552. get: function () {
  48553. return EasingFunction._EASINGMODE_EASEIN;
  48554. },
  48555. enumerable: true,
  48556. configurable: true
  48557. });
  48558. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  48559. get: function () {
  48560. return EasingFunction._EASINGMODE_EASEOUT;
  48561. },
  48562. enumerable: true,
  48563. configurable: true
  48564. });
  48565. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  48566. get: function () {
  48567. return EasingFunction._EASINGMODE_EASEINOUT;
  48568. },
  48569. enumerable: true,
  48570. configurable: true
  48571. });
  48572. EasingFunction.prototype.setEasingMode = function (easingMode) {
  48573. var n = Math.min(Math.max(easingMode, 0), 2);
  48574. this._easingMode = n;
  48575. };
  48576. EasingFunction.prototype.getEasingMode = function () {
  48577. return this._easingMode;
  48578. };
  48579. EasingFunction.prototype.easeInCore = function (gradient) {
  48580. throw new Error('You must implement this method');
  48581. };
  48582. EasingFunction.prototype.ease = function (gradient) {
  48583. switch (this._easingMode) {
  48584. case EasingFunction.EASINGMODE_EASEIN:
  48585. return this.easeInCore(gradient);
  48586. case EasingFunction.EASINGMODE_EASEOUT:
  48587. return (1 - this.easeInCore(1 - gradient));
  48588. }
  48589. if (gradient >= 0.5) {
  48590. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  48591. }
  48592. return (this.easeInCore(gradient * 2) * 0.5);
  48593. };
  48594. //Statics
  48595. EasingFunction._EASINGMODE_EASEIN = 0;
  48596. EasingFunction._EASINGMODE_EASEOUT = 1;
  48597. EasingFunction._EASINGMODE_EASEINOUT = 2;
  48598. return EasingFunction;
  48599. }());
  48600. BABYLON.EasingFunction = EasingFunction;
  48601. var CircleEase = /** @class */ (function (_super) {
  48602. __extends(CircleEase, _super);
  48603. function CircleEase() {
  48604. return _super !== null && _super.apply(this, arguments) || this;
  48605. }
  48606. CircleEase.prototype.easeInCore = function (gradient) {
  48607. gradient = Math.max(0, Math.min(1, gradient));
  48608. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  48609. };
  48610. return CircleEase;
  48611. }(EasingFunction));
  48612. BABYLON.CircleEase = CircleEase;
  48613. var BackEase = /** @class */ (function (_super) {
  48614. __extends(BackEase, _super);
  48615. function BackEase(amplitude) {
  48616. if (amplitude === void 0) { amplitude = 1; }
  48617. var _this = _super.call(this) || this;
  48618. _this.amplitude = amplitude;
  48619. return _this;
  48620. }
  48621. BackEase.prototype.easeInCore = function (gradient) {
  48622. var num = Math.max(0, this.amplitude);
  48623. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  48624. };
  48625. return BackEase;
  48626. }(EasingFunction));
  48627. BABYLON.BackEase = BackEase;
  48628. var BounceEase = /** @class */ (function (_super) {
  48629. __extends(BounceEase, _super);
  48630. function BounceEase(bounces, bounciness) {
  48631. if (bounces === void 0) { bounces = 3; }
  48632. if (bounciness === void 0) { bounciness = 2; }
  48633. var _this = _super.call(this) || this;
  48634. _this.bounces = bounces;
  48635. _this.bounciness = bounciness;
  48636. return _this;
  48637. }
  48638. BounceEase.prototype.easeInCore = function (gradient) {
  48639. var y = Math.max(0.0, this.bounces);
  48640. var bounciness = this.bounciness;
  48641. if (bounciness <= 1.0) {
  48642. bounciness = 1.001;
  48643. }
  48644. var num9 = Math.pow(bounciness, y);
  48645. var num5 = 1.0 - bounciness;
  48646. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  48647. var num15 = gradient * num4;
  48648. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  48649. var num3 = Math.floor(num65);
  48650. var num13 = num3 + 1.0;
  48651. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  48652. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  48653. var num7 = (num8 + num12) * 0.5;
  48654. var num6 = gradient - num7;
  48655. var num2 = num7 - num8;
  48656. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  48657. };
  48658. return BounceEase;
  48659. }(EasingFunction));
  48660. BABYLON.BounceEase = BounceEase;
  48661. var CubicEase = /** @class */ (function (_super) {
  48662. __extends(CubicEase, _super);
  48663. function CubicEase() {
  48664. return _super !== null && _super.apply(this, arguments) || this;
  48665. }
  48666. CubicEase.prototype.easeInCore = function (gradient) {
  48667. return (gradient * gradient * gradient);
  48668. };
  48669. return CubicEase;
  48670. }(EasingFunction));
  48671. BABYLON.CubicEase = CubicEase;
  48672. var ElasticEase = /** @class */ (function (_super) {
  48673. __extends(ElasticEase, _super);
  48674. function ElasticEase(oscillations, springiness) {
  48675. if (oscillations === void 0) { oscillations = 3; }
  48676. if (springiness === void 0) { springiness = 3; }
  48677. var _this = _super.call(this) || this;
  48678. _this.oscillations = oscillations;
  48679. _this.springiness = springiness;
  48680. return _this;
  48681. }
  48682. ElasticEase.prototype.easeInCore = function (gradient) {
  48683. var num2;
  48684. var num3 = Math.max(0.0, this.oscillations);
  48685. var num = Math.max(0.0, this.springiness);
  48686. if (num == 0) {
  48687. num2 = gradient;
  48688. }
  48689. else {
  48690. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  48691. }
  48692. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  48693. };
  48694. return ElasticEase;
  48695. }(EasingFunction));
  48696. BABYLON.ElasticEase = ElasticEase;
  48697. var ExponentialEase = /** @class */ (function (_super) {
  48698. __extends(ExponentialEase, _super);
  48699. function ExponentialEase(exponent) {
  48700. if (exponent === void 0) { exponent = 2; }
  48701. var _this = _super.call(this) || this;
  48702. _this.exponent = exponent;
  48703. return _this;
  48704. }
  48705. ExponentialEase.prototype.easeInCore = function (gradient) {
  48706. if (this.exponent <= 0) {
  48707. return gradient;
  48708. }
  48709. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  48710. };
  48711. return ExponentialEase;
  48712. }(EasingFunction));
  48713. BABYLON.ExponentialEase = ExponentialEase;
  48714. var PowerEase = /** @class */ (function (_super) {
  48715. __extends(PowerEase, _super);
  48716. function PowerEase(power) {
  48717. if (power === void 0) { power = 2; }
  48718. var _this = _super.call(this) || this;
  48719. _this.power = power;
  48720. return _this;
  48721. }
  48722. PowerEase.prototype.easeInCore = function (gradient) {
  48723. var y = Math.max(0.0, this.power);
  48724. return Math.pow(gradient, y);
  48725. };
  48726. return PowerEase;
  48727. }(EasingFunction));
  48728. BABYLON.PowerEase = PowerEase;
  48729. var QuadraticEase = /** @class */ (function (_super) {
  48730. __extends(QuadraticEase, _super);
  48731. function QuadraticEase() {
  48732. return _super !== null && _super.apply(this, arguments) || this;
  48733. }
  48734. QuadraticEase.prototype.easeInCore = function (gradient) {
  48735. return (gradient * gradient);
  48736. };
  48737. return QuadraticEase;
  48738. }(EasingFunction));
  48739. BABYLON.QuadraticEase = QuadraticEase;
  48740. var QuarticEase = /** @class */ (function (_super) {
  48741. __extends(QuarticEase, _super);
  48742. function QuarticEase() {
  48743. return _super !== null && _super.apply(this, arguments) || this;
  48744. }
  48745. QuarticEase.prototype.easeInCore = function (gradient) {
  48746. return (gradient * gradient * gradient * gradient);
  48747. };
  48748. return QuarticEase;
  48749. }(EasingFunction));
  48750. BABYLON.QuarticEase = QuarticEase;
  48751. var QuinticEase = /** @class */ (function (_super) {
  48752. __extends(QuinticEase, _super);
  48753. function QuinticEase() {
  48754. return _super !== null && _super.apply(this, arguments) || this;
  48755. }
  48756. QuinticEase.prototype.easeInCore = function (gradient) {
  48757. return (gradient * gradient * gradient * gradient * gradient);
  48758. };
  48759. return QuinticEase;
  48760. }(EasingFunction));
  48761. BABYLON.QuinticEase = QuinticEase;
  48762. var SineEase = /** @class */ (function (_super) {
  48763. __extends(SineEase, _super);
  48764. function SineEase() {
  48765. return _super !== null && _super.apply(this, arguments) || this;
  48766. }
  48767. SineEase.prototype.easeInCore = function (gradient) {
  48768. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  48769. };
  48770. return SineEase;
  48771. }(EasingFunction));
  48772. BABYLON.SineEase = SineEase;
  48773. var BezierCurveEase = /** @class */ (function (_super) {
  48774. __extends(BezierCurveEase, _super);
  48775. function BezierCurveEase(x1, y1, x2, y2) {
  48776. if (x1 === void 0) { x1 = 0; }
  48777. if (y1 === void 0) { y1 = 0; }
  48778. if (x2 === void 0) { x2 = 1; }
  48779. if (y2 === void 0) { y2 = 1; }
  48780. var _this = _super.call(this) || this;
  48781. _this.x1 = x1;
  48782. _this.y1 = y1;
  48783. _this.x2 = x2;
  48784. _this.y2 = y2;
  48785. return _this;
  48786. }
  48787. BezierCurveEase.prototype.easeInCore = function (gradient) {
  48788. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  48789. };
  48790. return BezierCurveEase;
  48791. }(EasingFunction));
  48792. BABYLON.BezierCurveEase = BezierCurveEase;
  48793. })(BABYLON || (BABYLON = {}));
  48794. //# sourceMappingURL=babylon.easing.js.map
  48795. "use strict";
  48796. var BABYLON;
  48797. (function (BABYLON) {
  48798. /**
  48799. * A Condition applied to an Action
  48800. */
  48801. var Condition = /** @class */ (function () {
  48802. /**
  48803. * Creates a new Condition
  48804. * @param actionManager the manager of the action the condition is applied to
  48805. */
  48806. function Condition(actionManager) {
  48807. this._actionManager = actionManager;
  48808. }
  48809. /**
  48810. * Check if the current condition is valid
  48811. * @returns a boolean
  48812. */
  48813. Condition.prototype.isValid = function () {
  48814. return true;
  48815. };
  48816. /**
  48817. * Internal only
  48818. * @ignore
  48819. */
  48820. Condition.prototype._getProperty = function (propertyPath) {
  48821. return this._actionManager._getProperty(propertyPath);
  48822. };
  48823. /**
  48824. * Internal only
  48825. * @ignore
  48826. */
  48827. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  48828. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48829. };
  48830. /**
  48831. * Serialize placeholder for child classes
  48832. * @returns the serialized object
  48833. */
  48834. Condition.prototype.serialize = function () {
  48835. };
  48836. /**
  48837. * Internal only
  48838. * @ignore
  48839. */
  48840. Condition.prototype._serialize = function (serializedCondition) {
  48841. return {
  48842. type: 2,
  48843. children: [],
  48844. name: serializedCondition.name,
  48845. properties: serializedCondition.properties
  48846. };
  48847. };
  48848. return Condition;
  48849. }());
  48850. BABYLON.Condition = Condition;
  48851. /**
  48852. * Defines specific conditional operators as extensions of Condition
  48853. */
  48854. var ValueCondition = /** @class */ (function (_super) {
  48855. __extends(ValueCondition, _super);
  48856. /**
  48857. * Creates a new ValueCondition
  48858. * @param actionManager manager for the action the condition applies to
  48859. * @param target for the action
  48860. * @param propertyPath path to specify the property of the target the conditional operator uses
  48861. * @param value the vale compared by the conditional operator against the current value of the property
  48862. * @param operator the conditional operator, default {BABYLON.ValueCondition.IsEqual}
  48863. */
  48864. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  48865. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  48866. var _this = _super.call(this, actionManager) || this;
  48867. _this.propertyPath = propertyPath;
  48868. _this.value = value;
  48869. _this.operator = operator;
  48870. _this._target = target;
  48871. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  48872. _this._property = _this._getProperty(_this.propertyPath);
  48873. return _this;
  48874. }
  48875. Object.defineProperty(ValueCondition, "IsEqual", {
  48876. /**
  48877. * returns the number for IsEqual
  48878. */
  48879. get: function () {
  48880. return ValueCondition._IsEqual;
  48881. },
  48882. enumerable: true,
  48883. configurable: true
  48884. });
  48885. Object.defineProperty(ValueCondition, "IsDifferent", {
  48886. /**
  48887. * Returns the number for IsDifferent
  48888. */
  48889. get: function () {
  48890. return ValueCondition._IsDifferent;
  48891. },
  48892. enumerable: true,
  48893. configurable: true
  48894. });
  48895. Object.defineProperty(ValueCondition, "IsGreater", {
  48896. /**
  48897. * Returns the number for IsGreater
  48898. */
  48899. get: function () {
  48900. return ValueCondition._IsGreater;
  48901. },
  48902. enumerable: true,
  48903. configurable: true
  48904. });
  48905. Object.defineProperty(ValueCondition, "IsLesser", {
  48906. /**
  48907. * Returns the number for IsLesser
  48908. */
  48909. get: function () {
  48910. return ValueCondition._IsLesser;
  48911. },
  48912. enumerable: true,
  48913. configurable: true
  48914. });
  48915. /**
  48916. * Compares the given value with the property value for the specified conditional operator
  48917. * @returns the result of the comparison
  48918. */
  48919. ValueCondition.prototype.isValid = function () {
  48920. switch (this.operator) {
  48921. case ValueCondition.IsGreater:
  48922. return this._effectiveTarget[this._property] > this.value;
  48923. case ValueCondition.IsLesser:
  48924. return this._effectiveTarget[this._property] < this.value;
  48925. case ValueCondition.IsEqual:
  48926. case ValueCondition.IsDifferent:
  48927. var check;
  48928. if (this.value.equals) {
  48929. check = this.value.equals(this._effectiveTarget[this._property]);
  48930. }
  48931. else {
  48932. check = this.value === this._effectiveTarget[this._property];
  48933. }
  48934. return this.operator === ValueCondition.IsEqual ? check : !check;
  48935. }
  48936. return false;
  48937. };
  48938. /**
  48939. * Serialize the ValueCondition into a JSON compatible object
  48940. * @returns serialization object
  48941. */
  48942. ValueCondition.prototype.serialize = function () {
  48943. return this._serialize({
  48944. name: "ValueCondition",
  48945. properties: [
  48946. BABYLON.Action._GetTargetProperty(this._target),
  48947. { name: "propertyPath", value: this.propertyPath },
  48948. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48949. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  48950. ]
  48951. });
  48952. };
  48953. /**
  48954. * Gets the name of the conditional operator for the ValueCondition
  48955. * @param operator the conditional operator
  48956. * @returns the name
  48957. */
  48958. ValueCondition.GetOperatorName = function (operator) {
  48959. switch (operator) {
  48960. case ValueCondition._IsEqual: return "IsEqual";
  48961. case ValueCondition._IsDifferent: return "IsDifferent";
  48962. case ValueCondition._IsGreater: return "IsGreater";
  48963. case ValueCondition._IsLesser: return "IsLesser";
  48964. default: return "";
  48965. }
  48966. };
  48967. /**
  48968. * Internal only
  48969. * @ignore
  48970. */
  48971. ValueCondition._IsEqual = 0;
  48972. /**
  48973. * Internal only
  48974. * @ignore
  48975. */
  48976. ValueCondition._IsDifferent = 1;
  48977. /**
  48978. * Internal only
  48979. * @ignore
  48980. */
  48981. ValueCondition._IsGreater = 2;
  48982. /**
  48983. * Internal only
  48984. * @ignore
  48985. */
  48986. ValueCondition._IsLesser = 3;
  48987. return ValueCondition;
  48988. }(Condition));
  48989. BABYLON.ValueCondition = ValueCondition;
  48990. /**
  48991. * Defines a predicate condition as an extension of Condition
  48992. */
  48993. var PredicateCondition = /** @class */ (function (_super) {
  48994. __extends(PredicateCondition, _super);
  48995. /**
  48996. * Creates a new {BABYLON.PredicateCondition}
  48997. * @param actionManager manager for the action the condition applies to
  48998. * @param predicate
  48999. */
  49000. function PredicateCondition(actionManager, predicate) {
  49001. var _this = _super.call(this, actionManager) || this;
  49002. _this.predicate = predicate;
  49003. return _this;
  49004. }
  49005. /**
  49006. * @returns the validity of the predicate condition
  49007. */
  49008. PredicateCondition.prototype.isValid = function () {
  49009. return this.predicate();
  49010. };
  49011. return PredicateCondition;
  49012. }(Condition));
  49013. BABYLON.PredicateCondition = PredicateCondition;
  49014. /**
  49015. * Defines a state condition as an extension of {BABYLON.Condition}
  49016. */
  49017. var StateCondition = /** @class */ (function (_super) {
  49018. __extends(StateCondition, _super);
  49019. /**
  49020. * Creates a new {BABYLON.StateCondition}
  49021. * @param actionManager manager for the action the condition applies to
  49022. * @param target of the condition
  49023. * @param value to compare with target state
  49024. */
  49025. function StateCondition(actionManager, target, value) {
  49026. var _this = _super.call(this, actionManager) || this;
  49027. _this.value = value;
  49028. _this._target = target;
  49029. return _this;
  49030. }
  49031. /**
  49032. * @returns the validity of the state
  49033. */
  49034. StateCondition.prototype.isValid = function () {
  49035. return this._target.state === this.value;
  49036. };
  49037. /**
  49038. * Serialize the {BABYLON.StateCondition} into a JSON compatible object
  49039. * @returns serialization object
  49040. */
  49041. StateCondition.prototype.serialize = function () {
  49042. return this._serialize({
  49043. name: "StateCondition",
  49044. properties: [
  49045. BABYLON.Action._GetTargetProperty(this._target),
  49046. { name: "value", value: this.value }
  49047. ]
  49048. });
  49049. };
  49050. return StateCondition;
  49051. }(Condition));
  49052. BABYLON.StateCondition = StateCondition;
  49053. })(BABYLON || (BABYLON = {}));
  49054. //# sourceMappingURL=babylon.condition.js.map
  49055. "use strict";
  49056. var BABYLON;
  49057. (function (BABYLON) {
  49058. /**
  49059. * The action to be carried out following a trigger
  49060. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  49061. */
  49062. var Action = /** @class */ (function () {
  49063. /**
  49064. * Creates a new Action
  49065. * @param triggerOptions the trigger, with or without parameters, for the action
  49066. * @param condition an optional determinant of action
  49067. */
  49068. function Action(triggerOptions, condition) {
  49069. this.triggerOptions = triggerOptions;
  49070. /**
  49071. * An event triggered prior to action being executed.
  49072. */
  49073. this.onBeforeExecuteObservable = new BABYLON.Observable();
  49074. if (triggerOptions.parameter) {
  49075. this.trigger = triggerOptions.trigger;
  49076. this._triggerParameter = triggerOptions.parameter;
  49077. }
  49078. else {
  49079. this.trigger = triggerOptions;
  49080. }
  49081. this._nextActiveAction = this;
  49082. this._condition = condition;
  49083. }
  49084. /**
  49085. * Internal only
  49086. * @ignore
  49087. */
  49088. Action.prototype._prepare = function () {
  49089. };
  49090. /**
  49091. * Gets the trigger parameters
  49092. * @returns the trigger parameters
  49093. */
  49094. Action.prototype.getTriggerParameter = function () {
  49095. return this._triggerParameter;
  49096. };
  49097. /**
  49098. * Internal only - executes current action event
  49099. * @ignore
  49100. */
  49101. Action.prototype._executeCurrent = function (evt) {
  49102. if (this._nextActiveAction._condition) {
  49103. var condition = this._nextActiveAction._condition;
  49104. var currentRenderId = this._actionManager.getScene().getRenderId();
  49105. // We cache the current evaluation for the current frame
  49106. if (condition._evaluationId === currentRenderId) {
  49107. if (!condition._currentResult) {
  49108. return;
  49109. }
  49110. }
  49111. else {
  49112. condition._evaluationId = currentRenderId;
  49113. if (!condition.isValid()) {
  49114. condition._currentResult = false;
  49115. return;
  49116. }
  49117. condition._currentResult = true;
  49118. }
  49119. }
  49120. this.onBeforeExecuteObservable.notifyObservers(this);
  49121. this._nextActiveAction.execute(evt);
  49122. this.skipToNextActiveAction();
  49123. };
  49124. /**
  49125. * Execute placeholder for child classes
  49126. * @param evt optional action event
  49127. */
  49128. Action.prototype.execute = function (evt) {
  49129. };
  49130. /**
  49131. * Skips to next active action
  49132. */
  49133. Action.prototype.skipToNextActiveAction = function () {
  49134. if (this._nextActiveAction._child) {
  49135. if (!this._nextActiveAction._child._actionManager) {
  49136. this._nextActiveAction._child._actionManager = this._actionManager;
  49137. }
  49138. this._nextActiveAction = this._nextActiveAction._child;
  49139. }
  49140. else {
  49141. this._nextActiveAction = this;
  49142. }
  49143. };
  49144. /**
  49145. * Adds action to chain of actions, may be a DoNothingAction
  49146. * @param index The index of the attribute.
  49147. * @returns The action passed in
  49148. * @see https://www.babylonjs-playground.com/#1T30HR#0
  49149. */
  49150. Action.prototype.then = function (action) {
  49151. this._child = action;
  49152. action._actionManager = this._actionManager;
  49153. action._prepare();
  49154. return action;
  49155. };
  49156. /**
  49157. * Internal only
  49158. * @ignore
  49159. */
  49160. Action.prototype._getProperty = function (propertyPath) {
  49161. return this._actionManager._getProperty(propertyPath);
  49162. };
  49163. /**
  49164. * Internal only
  49165. * @ignore
  49166. */
  49167. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  49168. return this._actionManager._getEffectiveTarget(target, propertyPath);
  49169. };
  49170. /**
  49171. * Serialize placeholder for child classes
  49172. * @param parent of child
  49173. * @returns the serialized object
  49174. */
  49175. Action.prototype.serialize = function (parent) {
  49176. };
  49177. /**
  49178. * Internal only called by serialize
  49179. * @ignore
  49180. */
  49181. Action.prototype._serialize = function (serializedAction, parent) {
  49182. var serializationObject = {
  49183. type: 1,
  49184. children: [],
  49185. name: serializedAction.name,
  49186. properties: serializedAction.properties || []
  49187. };
  49188. // Serialize child
  49189. if (this._child) {
  49190. this._child.serialize(serializationObject);
  49191. }
  49192. // Check if "this" has a condition
  49193. if (this._condition) {
  49194. var serializedCondition = this._condition.serialize();
  49195. serializedCondition.children.push(serializationObject);
  49196. if (parent) {
  49197. parent.children.push(serializedCondition);
  49198. }
  49199. return serializedCondition;
  49200. }
  49201. if (parent) {
  49202. parent.children.push(serializationObject);
  49203. }
  49204. return serializationObject;
  49205. };
  49206. /**
  49207. * Internal only
  49208. * @ignore
  49209. */
  49210. Action._SerializeValueAsString = function (value) {
  49211. if (typeof value === "number") {
  49212. return value.toString();
  49213. }
  49214. if (typeof value === "boolean") {
  49215. return value ? "true" : "false";
  49216. }
  49217. if (value instanceof BABYLON.Vector2) {
  49218. return value.x + ", " + value.y;
  49219. }
  49220. if (value instanceof BABYLON.Vector3) {
  49221. return value.x + ", " + value.y + ", " + value.z;
  49222. }
  49223. if (value instanceof BABYLON.Color3) {
  49224. return value.r + ", " + value.g + ", " + value.b;
  49225. }
  49226. if (value instanceof BABYLON.Color4) {
  49227. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  49228. }
  49229. return value; // string
  49230. };
  49231. /**
  49232. * Internal only
  49233. * @ignore
  49234. */
  49235. Action._GetTargetProperty = function (target) {
  49236. return {
  49237. name: "target",
  49238. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  49239. : target instanceof BABYLON.Light ? "LightProperties"
  49240. : target instanceof BABYLON.Camera ? "CameraProperties"
  49241. : "SceneProperties",
  49242. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  49243. };
  49244. };
  49245. return Action;
  49246. }());
  49247. BABYLON.Action = Action;
  49248. })(BABYLON || (BABYLON = {}));
  49249. //# sourceMappingURL=babylon.action.js.map
  49250. "use strict";
  49251. var BABYLON;
  49252. (function (BABYLON) {
  49253. /**
  49254. * ActionEvent is the event being sent when an action is triggered.
  49255. */
  49256. var ActionEvent = /** @class */ (function () {
  49257. /**
  49258. * @param source The mesh or sprite that triggered the action.
  49259. * @param pointerX The X mouse cursor position at the time of the event
  49260. * @param pointerY The Y mouse cursor position at the time of the event
  49261. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  49262. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  49263. */
  49264. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  49265. this.source = source;
  49266. this.pointerX = pointerX;
  49267. this.pointerY = pointerY;
  49268. this.meshUnderPointer = meshUnderPointer;
  49269. this.sourceEvent = sourceEvent;
  49270. this.additionalData = additionalData;
  49271. }
  49272. /**
  49273. * Helper function to auto-create an ActionEvent from a source mesh.
  49274. * @param source The source mesh that triggered the event
  49275. * @param evt {Event} The original (browser) event
  49276. */
  49277. ActionEvent.CreateNew = function (source, evt, additionalData) {
  49278. var scene = source.getScene();
  49279. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  49280. };
  49281. /**
  49282. * Helper function to auto-create an ActionEvent from a source mesh.
  49283. * @param source The source sprite that triggered the event
  49284. * @param scene Scene associated with the sprite
  49285. * @param evt {Event} The original (browser) event
  49286. */
  49287. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  49288. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  49289. };
  49290. /**
  49291. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  49292. * @param scene the scene where the event occurred
  49293. * @param evt {Event} The original (browser) event
  49294. */
  49295. ActionEvent.CreateNewFromScene = function (scene, evt) {
  49296. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  49297. };
  49298. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  49299. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  49300. };
  49301. return ActionEvent;
  49302. }());
  49303. BABYLON.ActionEvent = ActionEvent;
  49304. /**
  49305. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  49306. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  49307. */
  49308. var ActionManager = /** @class */ (function () {
  49309. function ActionManager(scene) {
  49310. // Members
  49311. this.actions = new Array();
  49312. this.hoverCursor = '';
  49313. this._scene = scene;
  49314. scene._actionManagers.push(this);
  49315. }
  49316. Object.defineProperty(ActionManager, "NothingTrigger", {
  49317. get: function () {
  49318. return ActionManager._NothingTrigger;
  49319. },
  49320. enumerable: true,
  49321. configurable: true
  49322. });
  49323. Object.defineProperty(ActionManager, "OnPickTrigger", {
  49324. get: function () {
  49325. return ActionManager._OnPickTrigger;
  49326. },
  49327. enumerable: true,
  49328. configurable: true
  49329. });
  49330. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  49331. get: function () {
  49332. return ActionManager._OnLeftPickTrigger;
  49333. },
  49334. enumerable: true,
  49335. configurable: true
  49336. });
  49337. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  49338. get: function () {
  49339. return ActionManager._OnRightPickTrigger;
  49340. },
  49341. enumerable: true,
  49342. configurable: true
  49343. });
  49344. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  49345. get: function () {
  49346. return ActionManager._OnCenterPickTrigger;
  49347. },
  49348. enumerable: true,
  49349. configurable: true
  49350. });
  49351. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  49352. get: function () {
  49353. return ActionManager._OnPickDownTrigger;
  49354. },
  49355. enumerable: true,
  49356. configurable: true
  49357. });
  49358. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  49359. get: function () {
  49360. return ActionManager._OnDoublePickTrigger;
  49361. },
  49362. enumerable: true,
  49363. configurable: true
  49364. });
  49365. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  49366. get: function () {
  49367. return ActionManager._OnPickUpTrigger;
  49368. },
  49369. enumerable: true,
  49370. configurable: true
  49371. });
  49372. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  49373. /// This trigger will only be raised if you also declared a OnPickDown
  49374. get: function () {
  49375. return ActionManager._OnPickOutTrigger;
  49376. },
  49377. enumerable: true,
  49378. configurable: true
  49379. });
  49380. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  49381. get: function () {
  49382. return ActionManager._OnLongPressTrigger;
  49383. },
  49384. enumerable: true,
  49385. configurable: true
  49386. });
  49387. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  49388. get: function () {
  49389. return ActionManager._OnPointerOverTrigger;
  49390. },
  49391. enumerable: true,
  49392. configurable: true
  49393. });
  49394. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  49395. get: function () {
  49396. return ActionManager._OnPointerOutTrigger;
  49397. },
  49398. enumerable: true,
  49399. configurable: true
  49400. });
  49401. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  49402. get: function () {
  49403. return ActionManager._OnEveryFrameTrigger;
  49404. },
  49405. enumerable: true,
  49406. configurable: true
  49407. });
  49408. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  49409. get: function () {
  49410. return ActionManager._OnIntersectionEnterTrigger;
  49411. },
  49412. enumerable: true,
  49413. configurable: true
  49414. });
  49415. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  49416. get: function () {
  49417. return ActionManager._OnIntersectionExitTrigger;
  49418. },
  49419. enumerable: true,
  49420. configurable: true
  49421. });
  49422. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  49423. get: function () {
  49424. return ActionManager._OnKeyDownTrigger;
  49425. },
  49426. enumerable: true,
  49427. configurable: true
  49428. });
  49429. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  49430. get: function () {
  49431. return ActionManager._OnKeyUpTrigger;
  49432. },
  49433. enumerable: true,
  49434. configurable: true
  49435. });
  49436. // Methods
  49437. ActionManager.prototype.dispose = function () {
  49438. var index = this._scene._actionManagers.indexOf(this);
  49439. for (var i = 0; i < this.actions.length; i++) {
  49440. var action = this.actions[i];
  49441. ActionManager.Triggers[action.trigger]--;
  49442. if (ActionManager.Triggers[action.trigger] === 0) {
  49443. delete ActionManager.Triggers[action.trigger];
  49444. }
  49445. }
  49446. if (index > -1) {
  49447. this._scene._actionManagers.splice(index, 1);
  49448. }
  49449. };
  49450. ActionManager.prototype.getScene = function () {
  49451. return this._scene;
  49452. };
  49453. /**
  49454. * Does this action manager handles actions of any of the given triggers
  49455. * @param {number[]} triggers - the triggers to be tested
  49456. * @return {boolean} whether one (or more) of the triggers is handeled
  49457. */
  49458. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  49459. for (var index = 0; index < this.actions.length; index++) {
  49460. var action = this.actions[index];
  49461. if (triggers.indexOf(action.trigger) > -1) {
  49462. return true;
  49463. }
  49464. }
  49465. return false;
  49466. };
  49467. /**
  49468. * Does this action manager handles actions of a given trigger
  49469. * @param {number} trigger - the trigger to be tested
  49470. * @return {boolean} whether the trigger is handeled
  49471. */
  49472. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  49473. for (var index = 0; index < this.actions.length; index++) {
  49474. var action = this.actions[index];
  49475. if (action.trigger === trigger) {
  49476. return true;
  49477. }
  49478. }
  49479. return false;
  49480. };
  49481. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  49482. /**
  49483. * Does this action manager has pointer triggers
  49484. * @return {boolean} whether or not it has pointer triggers
  49485. */
  49486. get: function () {
  49487. for (var index = 0; index < this.actions.length; index++) {
  49488. var action = this.actions[index];
  49489. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  49490. return true;
  49491. }
  49492. }
  49493. return false;
  49494. },
  49495. enumerable: true,
  49496. configurable: true
  49497. });
  49498. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  49499. /**
  49500. * Does this action manager has pick triggers
  49501. * @return {boolean} whether or not it has pick triggers
  49502. */
  49503. get: function () {
  49504. for (var index = 0; index < this.actions.length; index++) {
  49505. var action = this.actions[index];
  49506. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  49507. return true;
  49508. }
  49509. }
  49510. return false;
  49511. },
  49512. enumerable: true,
  49513. configurable: true
  49514. });
  49515. Object.defineProperty(ActionManager, "HasTriggers", {
  49516. /**
  49517. * Does exist one action manager with at least one trigger
  49518. * @return {boolean} whether or not it exists one action manager with one trigger
  49519. **/
  49520. get: function () {
  49521. for (var t in ActionManager.Triggers) {
  49522. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49523. return true;
  49524. }
  49525. }
  49526. return false;
  49527. },
  49528. enumerable: true,
  49529. configurable: true
  49530. });
  49531. Object.defineProperty(ActionManager, "HasPickTriggers", {
  49532. /**
  49533. * Does exist one action manager with at least one pick trigger
  49534. * @return {boolean} whether or not it exists one action manager with one pick trigger
  49535. **/
  49536. get: function () {
  49537. for (var t in ActionManager.Triggers) {
  49538. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49539. var t_int = parseInt(t);
  49540. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  49541. return true;
  49542. }
  49543. }
  49544. }
  49545. return false;
  49546. },
  49547. enumerable: true,
  49548. configurable: true
  49549. });
  49550. /**
  49551. * Does exist one action manager that handles actions of a given trigger
  49552. * @param {number} trigger - the trigger to be tested
  49553. * @return {boolean} whether the trigger is handeled by at least one action manager
  49554. **/
  49555. ActionManager.HasSpecificTrigger = function (trigger) {
  49556. for (var t in ActionManager.Triggers) {
  49557. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49558. var t_int = parseInt(t);
  49559. if (t_int === trigger) {
  49560. return true;
  49561. }
  49562. }
  49563. }
  49564. return false;
  49565. };
  49566. /**
  49567. * Registers an action to this action manager
  49568. * @param {BABYLON.Action} action - the action to be registered
  49569. * @return {BABYLON.Action} the action amended (prepared) after registration
  49570. */
  49571. ActionManager.prototype.registerAction = function (action) {
  49572. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  49573. if (this.getScene().actionManager !== this) {
  49574. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  49575. return null;
  49576. }
  49577. }
  49578. this.actions.push(action);
  49579. if (ActionManager.Triggers[action.trigger]) {
  49580. ActionManager.Triggers[action.trigger]++;
  49581. }
  49582. else {
  49583. ActionManager.Triggers[action.trigger] = 1;
  49584. }
  49585. action._actionManager = this;
  49586. action._prepare();
  49587. return action;
  49588. };
  49589. /**
  49590. * Unregisters an action to this action manager
  49591. * @param action The action to be unregistered
  49592. * @return whether the action has been unregistered
  49593. */
  49594. ActionManager.prototype.unregisterAction = function (action) {
  49595. var index = this.actions.indexOf(action);
  49596. if (index !== -1) {
  49597. this.actions.splice(index, 1);
  49598. ActionManager.Triggers[action.trigger] -= 1;
  49599. if (ActionManager.Triggers[action.trigger] === 0) {
  49600. delete ActionManager.Triggers[action.trigger];
  49601. }
  49602. delete action._actionManager;
  49603. return true;
  49604. }
  49605. return false;
  49606. };
  49607. /**
  49608. * Process a specific trigger
  49609. * @param {number} trigger - the trigger to process
  49610. * @param evt {BABYLON.ActionEvent} the event details to be processed
  49611. */
  49612. ActionManager.prototype.processTrigger = function (trigger, evt) {
  49613. for (var index = 0; index < this.actions.length; index++) {
  49614. var action = this.actions[index];
  49615. if (action.trigger === trigger) {
  49616. if (evt) {
  49617. if (trigger === ActionManager.OnKeyUpTrigger
  49618. || trigger === ActionManager.OnKeyDownTrigger) {
  49619. var parameter = action.getTriggerParameter();
  49620. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  49621. if (!parameter.toLowerCase) {
  49622. continue;
  49623. }
  49624. var lowerCase = parameter.toLowerCase();
  49625. if (lowerCase !== evt.sourceEvent.key) {
  49626. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  49627. var actualkey = String.fromCharCode(unicode).toLowerCase();
  49628. if (actualkey !== lowerCase) {
  49629. continue;
  49630. }
  49631. }
  49632. }
  49633. }
  49634. }
  49635. action._executeCurrent(evt);
  49636. }
  49637. }
  49638. };
  49639. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  49640. var properties = propertyPath.split(".");
  49641. for (var index = 0; index < properties.length - 1; index++) {
  49642. target = target[properties[index]];
  49643. }
  49644. return target;
  49645. };
  49646. ActionManager.prototype._getProperty = function (propertyPath) {
  49647. var properties = propertyPath.split(".");
  49648. return properties[properties.length - 1];
  49649. };
  49650. ActionManager.prototype.serialize = function (name) {
  49651. var root = {
  49652. children: new Array(),
  49653. name: name,
  49654. type: 3,
  49655. properties: new Array() // Empty for root but required
  49656. };
  49657. for (var i = 0; i < this.actions.length; i++) {
  49658. var triggerObject = {
  49659. type: 0,
  49660. children: new Array(),
  49661. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  49662. properties: new Array()
  49663. };
  49664. var triggerOptions = this.actions[i].triggerOptions;
  49665. if (triggerOptions && typeof triggerOptions !== "number") {
  49666. if (triggerOptions.parameter instanceof BABYLON.Node) {
  49667. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  49668. }
  49669. else {
  49670. var parameter = {};
  49671. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  49672. if (triggerOptions.parameter.mesh) {
  49673. parameter._meshId = triggerOptions.parameter.mesh.id;
  49674. }
  49675. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  49676. }
  49677. }
  49678. // Serialize child action, recursively
  49679. this.actions[i].serialize(triggerObject);
  49680. // Add serialized trigger
  49681. root.children.push(triggerObject);
  49682. }
  49683. return root;
  49684. };
  49685. ActionManager.Parse = function (parsedActions, object, scene) {
  49686. var actionManager = new ActionManager(scene);
  49687. if (object === null)
  49688. scene.actionManager = actionManager;
  49689. else
  49690. object.actionManager = actionManager;
  49691. // instanciate a new object
  49692. var instanciate = function (name, params) {
  49693. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  49694. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  49695. newInstance.constructor.apply(newInstance, params);
  49696. return newInstance;
  49697. };
  49698. var parseParameter = function (name, value, target, propertyPath) {
  49699. if (propertyPath === null) {
  49700. // String, boolean or float
  49701. var floatValue = parseFloat(value);
  49702. if (value === "true" || value === "false")
  49703. return value === "true";
  49704. else
  49705. return isNaN(floatValue) ? value : floatValue;
  49706. }
  49707. var effectiveTarget = propertyPath.split(".");
  49708. var values = value.split(",");
  49709. // Get effective Target
  49710. for (var i = 0; i < effectiveTarget.length; i++) {
  49711. target = target[effectiveTarget[i]];
  49712. }
  49713. // Return appropriate value with its type
  49714. if (typeof (target) === "boolean")
  49715. return values[0] === "true";
  49716. if (typeof (target) === "string")
  49717. return values[0];
  49718. // Parameters with multiple values such as Vector3 etc.
  49719. var split = new Array();
  49720. for (var i = 0; i < values.length; i++)
  49721. split.push(parseFloat(values[i]));
  49722. if (target instanceof BABYLON.Vector3)
  49723. return BABYLON.Vector3.FromArray(split);
  49724. if (target instanceof BABYLON.Vector4)
  49725. return BABYLON.Vector4.FromArray(split);
  49726. if (target instanceof BABYLON.Color3)
  49727. return BABYLON.Color3.FromArray(split);
  49728. if (target instanceof BABYLON.Color4)
  49729. return BABYLON.Color4.FromArray(split);
  49730. return parseFloat(values[0]);
  49731. };
  49732. // traverse graph per trigger
  49733. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  49734. if (combineArray === void 0) { combineArray = null; }
  49735. if (parsedAction.detached)
  49736. return;
  49737. var parameters = new Array();
  49738. var target = null;
  49739. var propertyPath = null;
  49740. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  49741. // Parameters
  49742. if (parsedAction.type === 2)
  49743. parameters.push(actionManager);
  49744. else
  49745. parameters.push(trigger);
  49746. if (combine) {
  49747. var actions = new Array();
  49748. for (var j = 0; j < parsedAction.combine.length; j++) {
  49749. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  49750. }
  49751. parameters.push(actions);
  49752. }
  49753. else {
  49754. for (var i = 0; i < parsedAction.properties.length; i++) {
  49755. var value = parsedAction.properties[i].value;
  49756. var name = parsedAction.properties[i].name;
  49757. var targetType = parsedAction.properties[i].targetType;
  49758. if (name === "target")
  49759. if (targetType !== null && targetType === "SceneProperties")
  49760. value = target = scene;
  49761. else
  49762. value = target = scene.getNodeByName(value);
  49763. else if (name === "parent")
  49764. value = scene.getNodeByName(value);
  49765. else if (name === "sound")
  49766. value = scene.getSoundByName(value);
  49767. else if (name !== "propertyPath") {
  49768. if (parsedAction.type === 2 && name === "operator")
  49769. value = BABYLON.ValueCondition[value];
  49770. else
  49771. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  49772. }
  49773. else {
  49774. propertyPath = value;
  49775. }
  49776. parameters.push(value);
  49777. }
  49778. }
  49779. if (combineArray === null) {
  49780. parameters.push(condition);
  49781. }
  49782. else {
  49783. parameters.push(null);
  49784. }
  49785. // If interpolate value action
  49786. if (parsedAction.name === "InterpolateValueAction") {
  49787. var param = parameters[parameters.length - 2];
  49788. parameters[parameters.length - 1] = param;
  49789. parameters[parameters.length - 2] = condition;
  49790. }
  49791. // Action or condition(s) and not CombineAction
  49792. var newAction = instanciate(parsedAction.name, parameters);
  49793. if (newAction instanceof BABYLON.Condition && condition !== null) {
  49794. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  49795. if (action)
  49796. action.then(nothing);
  49797. else
  49798. actionManager.registerAction(nothing);
  49799. action = nothing;
  49800. }
  49801. if (combineArray === null) {
  49802. if (newAction instanceof BABYLON.Condition) {
  49803. condition = newAction;
  49804. newAction = action;
  49805. }
  49806. else {
  49807. condition = null;
  49808. if (action)
  49809. action.then(newAction);
  49810. else
  49811. actionManager.registerAction(newAction);
  49812. }
  49813. }
  49814. else {
  49815. combineArray.push(newAction);
  49816. }
  49817. for (var i = 0; i < parsedAction.children.length; i++)
  49818. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  49819. };
  49820. // triggers
  49821. for (var i = 0; i < parsedActions.children.length; i++) {
  49822. var triggerParams;
  49823. var trigger = parsedActions.children[i];
  49824. if (trigger.properties.length > 0) {
  49825. var param = trigger.properties[0].value;
  49826. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  49827. if (value._meshId) {
  49828. value.mesh = scene.getMeshByID(value._meshId);
  49829. }
  49830. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  49831. }
  49832. else
  49833. triggerParams = ActionManager[trigger.name];
  49834. for (var j = 0; j < trigger.children.length; j++) {
  49835. if (!trigger.detached)
  49836. traverse(trigger.children[j], triggerParams, null, null);
  49837. }
  49838. }
  49839. };
  49840. ActionManager.GetTriggerName = function (trigger) {
  49841. switch (trigger) {
  49842. case 0: return "NothingTrigger";
  49843. case 1: return "OnPickTrigger";
  49844. case 2: return "OnLeftPickTrigger";
  49845. case 3: return "OnRightPickTrigger";
  49846. case 4: return "OnCenterPickTrigger";
  49847. case 5: return "OnPickDownTrigger";
  49848. case 6: return "OnPickUpTrigger";
  49849. case 7: return "OnLongPressTrigger";
  49850. case 8: return "OnPointerOverTrigger";
  49851. case 9: return "OnPointerOutTrigger";
  49852. case 10: return "OnEveryFrameTrigger";
  49853. case 11: return "OnIntersectionEnterTrigger";
  49854. case 12: return "OnIntersectionExitTrigger";
  49855. case 13: return "OnKeyDownTrigger";
  49856. case 14: return "OnKeyUpTrigger";
  49857. case 15: return "OnPickOutTrigger";
  49858. default: return "";
  49859. }
  49860. };
  49861. // Statics
  49862. ActionManager._NothingTrigger = 0;
  49863. ActionManager._OnPickTrigger = 1;
  49864. ActionManager._OnLeftPickTrigger = 2;
  49865. ActionManager._OnRightPickTrigger = 3;
  49866. ActionManager._OnCenterPickTrigger = 4;
  49867. ActionManager._OnPickDownTrigger = 5;
  49868. ActionManager._OnDoublePickTrigger = 6;
  49869. ActionManager._OnPickUpTrigger = 7;
  49870. ActionManager._OnLongPressTrigger = 8;
  49871. ActionManager._OnPointerOverTrigger = 9;
  49872. ActionManager._OnPointerOutTrigger = 10;
  49873. ActionManager._OnEveryFrameTrigger = 11;
  49874. ActionManager._OnIntersectionEnterTrigger = 12;
  49875. ActionManager._OnIntersectionExitTrigger = 13;
  49876. ActionManager._OnKeyDownTrigger = 14;
  49877. ActionManager._OnKeyUpTrigger = 15;
  49878. ActionManager._OnPickOutTrigger = 16;
  49879. ActionManager.Triggers = {};
  49880. return ActionManager;
  49881. }());
  49882. BABYLON.ActionManager = ActionManager;
  49883. })(BABYLON || (BABYLON = {}));
  49884. //# sourceMappingURL=babylon.actionManager.js.map
  49885. "use strict";
  49886. var BABYLON;
  49887. (function (BABYLON) {
  49888. var InterpolateValueAction = /** @class */ (function (_super) {
  49889. __extends(InterpolateValueAction, _super);
  49890. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  49891. if (duration === void 0) { duration = 1000; }
  49892. var _this = _super.call(this, triggerOptions, condition) || this;
  49893. _this.propertyPath = propertyPath;
  49894. _this.value = value;
  49895. _this.duration = duration;
  49896. _this.stopOtherAnimations = stopOtherAnimations;
  49897. _this.onInterpolationDone = onInterpolationDone;
  49898. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  49899. _this._target = _this._effectiveTarget = target;
  49900. return _this;
  49901. }
  49902. InterpolateValueAction.prototype._prepare = function () {
  49903. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49904. this._property = this._getProperty(this.propertyPath);
  49905. };
  49906. InterpolateValueAction.prototype.execute = function () {
  49907. var _this = this;
  49908. var scene = this._actionManager.getScene();
  49909. var keys = [
  49910. {
  49911. frame: 0,
  49912. value: this._effectiveTarget[this._property]
  49913. }, {
  49914. frame: 100,
  49915. value: this.value
  49916. }
  49917. ];
  49918. var dataType;
  49919. if (typeof this.value === "number") {
  49920. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  49921. }
  49922. else if (this.value instanceof BABYLON.Color3) {
  49923. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  49924. }
  49925. else if (this.value instanceof BABYLON.Vector3) {
  49926. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  49927. }
  49928. else if (this.value instanceof BABYLON.Matrix) {
  49929. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  49930. }
  49931. else if (this.value instanceof BABYLON.Quaternion) {
  49932. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  49933. }
  49934. else {
  49935. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  49936. return;
  49937. }
  49938. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  49939. animation.setKeys(keys);
  49940. if (this.stopOtherAnimations) {
  49941. scene.stopAnimation(this._effectiveTarget);
  49942. }
  49943. var wrapper = function () {
  49944. _this.onInterpolationDoneObservable.notifyObservers(_this);
  49945. if (_this.onInterpolationDone) {
  49946. _this.onInterpolationDone();
  49947. }
  49948. };
  49949. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  49950. };
  49951. InterpolateValueAction.prototype.serialize = function (parent) {
  49952. return _super.prototype._serialize.call(this, {
  49953. name: "InterpolateValueAction",
  49954. properties: [
  49955. BABYLON.Action._GetTargetProperty(this._target),
  49956. { name: "propertyPath", value: this.propertyPath },
  49957. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  49958. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  49959. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  49960. ]
  49961. }, parent);
  49962. };
  49963. return InterpolateValueAction;
  49964. }(BABYLON.Action));
  49965. BABYLON.InterpolateValueAction = InterpolateValueAction;
  49966. })(BABYLON || (BABYLON = {}));
  49967. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  49968. "use strict";
  49969. var BABYLON;
  49970. (function (BABYLON) {
  49971. var SwitchBooleanAction = /** @class */ (function (_super) {
  49972. __extends(SwitchBooleanAction, _super);
  49973. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  49974. var _this = _super.call(this, triggerOptions, condition) || this;
  49975. _this.propertyPath = propertyPath;
  49976. _this._target = _this._effectiveTarget = target;
  49977. return _this;
  49978. }
  49979. SwitchBooleanAction.prototype._prepare = function () {
  49980. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49981. this._property = this._getProperty(this.propertyPath);
  49982. };
  49983. SwitchBooleanAction.prototype.execute = function () {
  49984. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  49985. };
  49986. SwitchBooleanAction.prototype.serialize = function (parent) {
  49987. return _super.prototype._serialize.call(this, {
  49988. name: "SwitchBooleanAction",
  49989. properties: [
  49990. BABYLON.Action._GetTargetProperty(this._target),
  49991. { name: "propertyPath", value: this.propertyPath }
  49992. ]
  49993. }, parent);
  49994. };
  49995. return SwitchBooleanAction;
  49996. }(BABYLON.Action));
  49997. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  49998. var SetStateAction = /** @class */ (function (_super) {
  49999. __extends(SetStateAction, _super);
  50000. function SetStateAction(triggerOptions, target, value, condition) {
  50001. var _this = _super.call(this, triggerOptions, condition) || this;
  50002. _this.value = value;
  50003. _this._target = target;
  50004. return _this;
  50005. }
  50006. SetStateAction.prototype.execute = function () {
  50007. this._target.state = this.value;
  50008. };
  50009. SetStateAction.prototype.serialize = function (parent) {
  50010. return _super.prototype._serialize.call(this, {
  50011. name: "SetStateAction",
  50012. properties: [
  50013. BABYLON.Action._GetTargetProperty(this._target),
  50014. { name: "value", value: this.value }
  50015. ]
  50016. }, parent);
  50017. };
  50018. return SetStateAction;
  50019. }(BABYLON.Action));
  50020. BABYLON.SetStateAction = SetStateAction;
  50021. var SetValueAction = /** @class */ (function (_super) {
  50022. __extends(SetValueAction, _super);
  50023. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  50024. var _this = _super.call(this, triggerOptions, condition) || this;
  50025. _this.propertyPath = propertyPath;
  50026. _this.value = value;
  50027. _this._target = _this._effectiveTarget = target;
  50028. return _this;
  50029. }
  50030. SetValueAction.prototype._prepare = function () {
  50031. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  50032. this._property = this._getProperty(this.propertyPath);
  50033. };
  50034. SetValueAction.prototype.execute = function () {
  50035. this._effectiveTarget[this._property] = this.value;
  50036. if (this._target.markAsDirty) {
  50037. this._target.markAsDirty(this._property);
  50038. }
  50039. };
  50040. SetValueAction.prototype.serialize = function (parent) {
  50041. return _super.prototype._serialize.call(this, {
  50042. name: "SetValueAction",
  50043. properties: [
  50044. BABYLON.Action._GetTargetProperty(this._target),
  50045. { name: "propertyPath", value: this.propertyPath },
  50046. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  50047. ]
  50048. }, parent);
  50049. };
  50050. return SetValueAction;
  50051. }(BABYLON.Action));
  50052. BABYLON.SetValueAction = SetValueAction;
  50053. var IncrementValueAction = /** @class */ (function (_super) {
  50054. __extends(IncrementValueAction, _super);
  50055. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  50056. var _this = _super.call(this, triggerOptions, condition) || this;
  50057. _this.propertyPath = propertyPath;
  50058. _this.value = value;
  50059. _this._target = _this._effectiveTarget = target;
  50060. return _this;
  50061. }
  50062. IncrementValueAction.prototype._prepare = function () {
  50063. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  50064. this._property = this._getProperty(this.propertyPath);
  50065. if (typeof this._effectiveTarget[this._property] !== "number") {
  50066. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  50067. }
  50068. };
  50069. IncrementValueAction.prototype.execute = function () {
  50070. this._effectiveTarget[this._property] += this.value;
  50071. if (this._target.markAsDirty) {
  50072. this._target.markAsDirty(this._property);
  50073. }
  50074. };
  50075. IncrementValueAction.prototype.serialize = function (parent) {
  50076. return _super.prototype._serialize.call(this, {
  50077. name: "IncrementValueAction",
  50078. properties: [
  50079. BABYLON.Action._GetTargetProperty(this._target),
  50080. { name: "propertyPath", value: this.propertyPath },
  50081. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  50082. ]
  50083. }, parent);
  50084. };
  50085. return IncrementValueAction;
  50086. }(BABYLON.Action));
  50087. BABYLON.IncrementValueAction = IncrementValueAction;
  50088. var PlayAnimationAction = /** @class */ (function (_super) {
  50089. __extends(PlayAnimationAction, _super);
  50090. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  50091. var _this = _super.call(this, triggerOptions, condition) || this;
  50092. _this.from = from;
  50093. _this.to = to;
  50094. _this.loop = loop;
  50095. _this._target = target;
  50096. return _this;
  50097. }
  50098. PlayAnimationAction.prototype._prepare = function () {
  50099. };
  50100. PlayAnimationAction.prototype.execute = function () {
  50101. var scene = this._actionManager.getScene();
  50102. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  50103. };
  50104. PlayAnimationAction.prototype.serialize = function (parent) {
  50105. return _super.prototype._serialize.call(this, {
  50106. name: "PlayAnimationAction",
  50107. properties: [
  50108. BABYLON.Action._GetTargetProperty(this._target),
  50109. { name: "from", value: String(this.from) },
  50110. { name: "to", value: String(this.to) },
  50111. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  50112. ]
  50113. }, parent);
  50114. };
  50115. return PlayAnimationAction;
  50116. }(BABYLON.Action));
  50117. BABYLON.PlayAnimationAction = PlayAnimationAction;
  50118. var StopAnimationAction = /** @class */ (function (_super) {
  50119. __extends(StopAnimationAction, _super);
  50120. function StopAnimationAction(triggerOptions, target, condition) {
  50121. var _this = _super.call(this, triggerOptions, condition) || this;
  50122. _this._target = target;
  50123. return _this;
  50124. }
  50125. StopAnimationAction.prototype._prepare = function () {
  50126. };
  50127. StopAnimationAction.prototype.execute = function () {
  50128. var scene = this._actionManager.getScene();
  50129. scene.stopAnimation(this._target);
  50130. };
  50131. StopAnimationAction.prototype.serialize = function (parent) {
  50132. return _super.prototype._serialize.call(this, {
  50133. name: "StopAnimationAction",
  50134. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  50135. }, parent);
  50136. };
  50137. return StopAnimationAction;
  50138. }(BABYLON.Action));
  50139. BABYLON.StopAnimationAction = StopAnimationAction;
  50140. var DoNothingAction = /** @class */ (function (_super) {
  50141. __extends(DoNothingAction, _super);
  50142. function DoNothingAction(triggerOptions, condition) {
  50143. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  50144. return _super.call(this, triggerOptions, condition) || this;
  50145. }
  50146. DoNothingAction.prototype.execute = function () {
  50147. };
  50148. DoNothingAction.prototype.serialize = function (parent) {
  50149. return _super.prototype._serialize.call(this, {
  50150. name: "DoNothingAction",
  50151. properties: []
  50152. }, parent);
  50153. };
  50154. return DoNothingAction;
  50155. }(BABYLON.Action));
  50156. BABYLON.DoNothingAction = DoNothingAction;
  50157. var CombineAction = /** @class */ (function (_super) {
  50158. __extends(CombineAction, _super);
  50159. function CombineAction(triggerOptions, children, condition) {
  50160. var _this = _super.call(this, triggerOptions, condition) || this;
  50161. _this.children = children;
  50162. return _this;
  50163. }
  50164. CombineAction.prototype._prepare = function () {
  50165. for (var index = 0; index < this.children.length; index++) {
  50166. this.children[index]._actionManager = this._actionManager;
  50167. this.children[index]._prepare();
  50168. }
  50169. };
  50170. CombineAction.prototype.execute = function (evt) {
  50171. for (var index = 0; index < this.children.length; index++) {
  50172. this.children[index].execute(evt);
  50173. }
  50174. };
  50175. CombineAction.prototype.serialize = function (parent) {
  50176. var serializationObject = _super.prototype._serialize.call(this, {
  50177. name: "CombineAction",
  50178. properties: [],
  50179. combine: []
  50180. }, parent);
  50181. for (var i = 0; i < this.children.length; i++) {
  50182. serializationObject.combine.push(this.children[i].serialize(null));
  50183. }
  50184. return serializationObject;
  50185. };
  50186. return CombineAction;
  50187. }(BABYLON.Action));
  50188. BABYLON.CombineAction = CombineAction;
  50189. var ExecuteCodeAction = /** @class */ (function (_super) {
  50190. __extends(ExecuteCodeAction, _super);
  50191. function ExecuteCodeAction(triggerOptions, func, condition) {
  50192. var _this = _super.call(this, triggerOptions, condition) || this;
  50193. _this.func = func;
  50194. return _this;
  50195. }
  50196. ExecuteCodeAction.prototype.execute = function (evt) {
  50197. this.func(evt);
  50198. };
  50199. return ExecuteCodeAction;
  50200. }(BABYLON.Action));
  50201. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  50202. var SetParentAction = /** @class */ (function (_super) {
  50203. __extends(SetParentAction, _super);
  50204. function SetParentAction(triggerOptions, target, parent, condition) {
  50205. var _this = _super.call(this, triggerOptions, condition) || this;
  50206. _this._target = target;
  50207. _this._parent = parent;
  50208. return _this;
  50209. }
  50210. SetParentAction.prototype._prepare = function () {
  50211. };
  50212. SetParentAction.prototype.execute = function () {
  50213. if (this._target.parent === this._parent) {
  50214. return;
  50215. }
  50216. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  50217. invertParentWorldMatrix.invert();
  50218. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  50219. this._target.parent = this._parent;
  50220. };
  50221. SetParentAction.prototype.serialize = function (parent) {
  50222. return _super.prototype._serialize.call(this, {
  50223. name: "SetParentAction",
  50224. properties: [
  50225. BABYLON.Action._GetTargetProperty(this._target),
  50226. BABYLON.Action._GetTargetProperty(this._parent),
  50227. ]
  50228. }, parent);
  50229. };
  50230. return SetParentAction;
  50231. }(BABYLON.Action));
  50232. BABYLON.SetParentAction = SetParentAction;
  50233. var PlaySoundAction = /** @class */ (function (_super) {
  50234. __extends(PlaySoundAction, _super);
  50235. function PlaySoundAction(triggerOptions, sound, condition) {
  50236. var _this = _super.call(this, triggerOptions, condition) || this;
  50237. _this._sound = sound;
  50238. return _this;
  50239. }
  50240. PlaySoundAction.prototype._prepare = function () {
  50241. };
  50242. PlaySoundAction.prototype.execute = function () {
  50243. if (this._sound !== undefined)
  50244. this._sound.play();
  50245. };
  50246. PlaySoundAction.prototype.serialize = function (parent) {
  50247. return _super.prototype._serialize.call(this, {
  50248. name: "PlaySoundAction",
  50249. properties: [{ name: "sound", value: this._sound.name }]
  50250. }, parent);
  50251. };
  50252. return PlaySoundAction;
  50253. }(BABYLON.Action));
  50254. BABYLON.PlaySoundAction = PlaySoundAction;
  50255. var StopSoundAction = /** @class */ (function (_super) {
  50256. __extends(StopSoundAction, _super);
  50257. function StopSoundAction(triggerOptions, sound, condition) {
  50258. var _this = _super.call(this, triggerOptions, condition) || this;
  50259. _this._sound = sound;
  50260. return _this;
  50261. }
  50262. StopSoundAction.prototype._prepare = function () {
  50263. };
  50264. StopSoundAction.prototype.execute = function () {
  50265. if (this._sound !== undefined)
  50266. this._sound.stop();
  50267. };
  50268. StopSoundAction.prototype.serialize = function (parent) {
  50269. return _super.prototype._serialize.call(this, {
  50270. name: "StopSoundAction",
  50271. properties: [{ name: "sound", value: this._sound.name }]
  50272. }, parent);
  50273. };
  50274. return StopSoundAction;
  50275. }(BABYLON.Action));
  50276. BABYLON.StopSoundAction = StopSoundAction;
  50277. })(BABYLON || (BABYLON = {}));
  50278. //# sourceMappingURL=babylon.directActions.js.map
  50279. "use strict";
  50280. var BABYLON;
  50281. (function (BABYLON) {
  50282. var SpriteManager = /** @class */ (function () {
  50283. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  50284. if (epsilon === void 0) { epsilon = 0.01; }
  50285. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50286. this.name = name;
  50287. this.sprites = new Array();
  50288. this.renderingGroupId = 0;
  50289. this.layerMask = 0x0FFFFFFF;
  50290. this.fogEnabled = true;
  50291. this.isPickable = false;
  50292. /**
  50293. * An event triggered when the manager is disposed.
  50294. */
  50295. this.onDisposeObservable = new BABYLON.Observable();
  50296. this._vertexBuffers = {};
  50297. this._capacity = capacity;
  50298. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  50299. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50300. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50301. if (cellSize.width && cellSize.height) {
  50302. this.cellWidth = cellSize.width;
  50303. this.cellHeight = cellSize.height;
  50304. }
  50305. else if (cellSize !== undefined) {
  50306. this.cellWidth = cellSize;
  50307. this.cellHeight = cellSize;
  50308. }
  50309. else {
  50310. return;
  50311. }
  50312. this._epsilon = epsilon;
  50313. this._scene = scene;
  50314. this._scene.spriteManagers.push(this);
  50315. var indices = [];
  50316. var index = 0;
  50317. for (var count = 0; count < capacity; count++) {
  50318. indices.push(index);
  50319. indices.push(index + 1);
  50320. indices.push(index + 2);
  50321. indices.push(index);
  50322. indices.push(index + 2);
  50323. indices.push(index + 3);
  50324. index += 4;
  50325. }
  50326. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  50327. // VBO
  50328. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  50329. this._vertexData = new Float32Array(capacity * 16 * 4);
  50330. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  50331. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  50332. var options = this._buffer.createVertexBuffer("options", 4, 4);
  50333. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  50334. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  50335. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  50336. this._vertexBuffers["options"] = options;
  50337. this._vertexBuffers["cellInfo"] = cellInfo;
  50338. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  50339. // Effects
  50340. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  50341. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  50342. }
  50343. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  50344. set: function (callback) {
  50345. if (this._onDisposeObserver) {
  50346. this.onDisposeObservable.remove(this._onDisposeObserver);
  50347. }
  50348. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  50349. },
  50350. enumerable: true,
  50351. configurable: true
  50352. });
  50353. Object.defineProperty(SpriteManager.prototype, "texture", {
  50354. get: function () {
  50355. return this._spriteTexture;
  50356. },
  50357. set: function (value) {
  50358. this._spriteTexture = value;
  50359. },
  50360. enumerable: true,
  50361. configurable: true
  50362. });
  50363. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  50364. var arrayOffset = index * 16;
  50365. if (offsetX === 0)
  50366. offsetX = this._epsilon;
  50367. else if (offsetX === 1)
  50368. offsetX = 1 - this._epsilon;
  50369. if (offsetY === 0)
  50370. offsetY = this._epsilon;
  50371. else if (offsetY === 1)
  50372. offsetY = 1 - this._epsilon;
  50373. this._vertexData[arrayOffset] = sprite.position.x;
  50374. this._vertexData[arrayOffset + 1] = sprite.position.y;
  50375. this._vertexData[arrayOffset + 2] = sprite.position.z;
  50376. this._vertexData[arrayOffset + 3] = sprite.angle;
  50377. this._vertexData[arrayOffset + 4] = sprite.width;
  50378. this._vertexData[arrayOffset + 5] = sprite.height;
  50379. this._vertexData[arrayOffset + 6] = offsetX;
  50380. this._vertexData[arrayOffset + 7] = offsetY;
  50381. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  50382. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  50383. var offset = (sprite.cellIndex / rowSize) >> 0;
  50384. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  50385. this._vertexData[arrayOffset + 11] = offset;
  50386. // Color
  50387. this._vertexData[arrayOffset + 12] = sprite.color.r;
  50388. this._vertexData[arrayOffset + 13] = sprite.color.g;
  50389. this._vertexData[arrayOffset + 14] = sprite.color.b;
  50390. this._vertexData[arrayOffset + 15] = sprite.color.a;
  50391. };
  50392. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  50393. var count = Math.min(this._capacity, this.sprites.length);
  50394. var min = BABYLON.Vector3.Zero();
  50395. var max = BABYLON.Vector3.Zero();
  50396. var distance = Number.MAX_VALUE;
  50397. var currentSprite = null;
  50398. var cameraSpacePosition = BABYLON.Vector3.Zero();
  50399. var cameraView = camera.getViewMatrix();
  50400. for (var index = 0; index < count; index++) {
  50401. var sprite = this.sprites[index];
  50402. if (!sprite) {
  50403. continue;
  50404. }
  50405. if (predicate) {
  50406. if (!predicate(sprite)) {
  50407. continue;
  50408. }
  50409. }
  50410. else if (!sprite.isPickable) {
  50411. continue;
  50412. }
  50413. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  50414. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  50415. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  50416. if (ray.intersectsBoxMinMax(min, max)) {
  50417. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  50418. if (distance > currentDistance) {
  50419. distance = currentDistance;
  50420. currentSprite = sprite;
  50421. if (fastCheck) {
  50422. break;
  50423. }
  50424. }
  50425. }
  50426. }
  50427. if (currentSprite) {
  50428. var result = new BABYLON.PickingInfo();
  50429. result.hit = true;
  50430. result.pickedSprite = currentSprite;
  50431. result.distance = distance;
  50432. return result;
  50433. }
  50434. return null;
  50435. };
  50436. SpriteManager.prototype.render = function () {
  50437. // Check
  50438. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  50439. return;
  50440. var engine = this._scene.getEngine();
  50441. var baseSize = this._spriteTexture.getBaseSize();
  50442. // Sprites
  50443. var deltaTime = engine.getDeltaTime();
  50444. var max = Math.min(this._capacity, this.sprites.length);
  50445. var rowSize = baseSize.width / this.cellWidth;
  50446. var offset = 0;
  50447. for (var index = 0; index < max; index++) {
  50448. var sprite = this.sprites[index];
  50449. if (!sprite) {
  50450. continue;
  50451. }
  50452. sprite._animate(deltaTime);
  50453. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  50454. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  50455. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  50456. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  50457. }
  50458. this._buffer.update(this._vertexData);
  50459. // Render
  50460. var effect = this._effectBase;
  50461. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  50462. effect = this._effectFog;
  50463. }
  50464. engine.enableEffect(effect);
  50465. var viewMatrix = this._scene.getViewMatrix();
  50466. effect.setTexture("diffuseSampler", this._spriteTexture);
  50467. effect.setMatrix("view", viewMatrix);
  50468. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  50469. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  50470. // Fog
  50471. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  50472. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  50473. effect.setColor3("vFogColor", this._scene.fogColor);
  50474. }
  50475. // VBOs
  50476. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  50477. // Draw order
  50478. engine.setDepthFunctionToLessOrEqual();
  50479. effect.setBool("alphaTest", true);
  50480. engine.setColorWrite(false);
  50481. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  50482. engine.setColorWrite(true);
  50483. effect.setBool("alphaTest", false);
  50484. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  50485. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  50486. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  50487. };
  50488. SpriteManager.prototype.dispose = function () {
  50489. if (this._buffer) {
  50490. this._buffer.dispose();
  50491. this._buffer = null;
  50492. }
  50493. if (this._indexBuffer) {
  50494. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  50495. this._indexBuffer = null;
  50496. }
  50497. if (this._spriteTexture) {
  50498. this._spriteTexture.dispose();
  50499. this._spriteTexture = null;
  50500. }
  50501. // Remove from scene
  50502. var index = this._scene.spriteManagers.indexOf(this);
  50503. this._scene.spriteManagers.splice(index, 1);
  50504. // Callback
  50505. this.onDisposeObservable.notifyObservers(this);
  50506. this.onDisposeObservable.clear();
  50507. };
  50508. return SpriteManager;
  50509. }());
  50510. BABYLON.SpriteManager = SpriteManager;
  50511. })(BABYLON || (BABYLON = {}));
  50512. //# sourceMappingURL=babylon.spriteManager.js.map
  50513. "use strict";
  50514. var BABYLON;
  50515. (function (BABYLON) {
  50516. var Sprite = /** @class */ (function () {
  50517. function Sprite(name, manager) {
  50518. this.name = name;
  50519. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50520. this.width = 1.0;
  50521. this.height = 1.0;
  50522. this.angle = 0;
  50523. this.cellIndex = 0;
  50524. this.invertU = 0;
  50525. this.invertV = 0;
  50526. this.animations = new Array();
  50527. this.isPickable = false;
  50528. this._animationStarted = false;
  50529. this._loopAnimation = false;
  50530. this._fromIndex = 0;
  50531. this._toIndex = 0;
  50532. this._delay = 0;
  50533. this._direction = 1;
  50534. this._time = 0;
  50535. this._manager = manager;
  50536. this._manager.sprites.push(this);
  50537. this.position = BABYLON.Vector3.Zero();
  50538. }
  50539. Object.defineProperty(Sprite.prototype, "size", {
  50540. get: function () {
  50541. return this.width;
  50542. },
  50543. set: function (value) {
  50544. this.width = value;
  50545. this.height = value;
  50546. },
  50547. enumerable: true,
  50548. configurable: true
  50549. });
  50550. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  50551. this._fromIndex = from;
  50552. this._toIndex = to;
  50553. this._loopAnimation = loop;
  50554. this._delay = delay;
  50555. this._animationStarted = true;
  50556. this._direction = from < to ? 1 : -1;
  50557. this.cellIndex = from;
  50558. this._time = 0;
  50559. this._onAnimationEnd = onAnimationEnd;
  50560. };
  50561. Sprite.prototype.stopAnimation = function () {
  50562. this._animationStarted = false;
  50563. };
  50564. Sprite.prototype._animate = function (deltaTime) {
  50565. if (!this._animationStarted)
  50566. return;
  50567. this._time += deltaTime;
  50568. if (this._time > this._delay) {
  50569. this._time = this._time % this._delay;
  50570. this.cellIndex += this._direction;
  50571. if (this.cellIndex > this._toIndex) {
  50572. if (this._loopAnimation) {
  50573. this.cellIndex = this._fromIndex;
  50574. }
  50575. else {
  50576. this.cellIndex = this._toIndex;
  50577. this._animationStarted = false;
  50578. if (this._onAnimationEnd) {
  50579. this._onAnimationEnd();
  50580. }
  50581. if (this.disposeWhenFinishedAnimating) {
  50582. this.dispose();
  50583. }
  50584. }
  50585. }
  50586. }
  50587. };
  50588. Sprite.prototype.dispose = function () {
  50589. for (var i = 0; i < this._manager.sprites.length; i++) {
  50590. if (this._manager.sprites[i] == this) {
  50591. this._manager.sprites.splice(i, 1);
  50592. }
  50593. }
  50594. };
  50595. return Sprite;
  50596. }());
  50597. BABYLON.Sprite = Sprite;
  50598. })(BABYLON || (BABYLON = {}));
  50599. //# sourceMappingURL=babylon.sprite.js.map
  50600. "use strict";
  50601. var BABYLON;
  50602. (function (BABYLON) {
  50603. var IntersectionInfo = /** @class */ (function () {
  50604. function IntersectionInfo(bu, bv, distance) {
  50605. this.bu = bu;
  50606. this.bv = bv;
  50607. this.distance = distance;
  50608. this.faceId = 0;
  50609. this.subMeshId = 0;
  50610. }
  50611. return IntersectionInfo;
  50612. }());
  50613. BABYLON.IntersectionInfo = IntersectionInfo;
  50614. var PickingInfo = /** @class */ (function () {
  50615. function PickingInfo() {
  50616. this.hit = false;
  50617. this.distance = 0;
  50618. this.pickedPoint = null;
  50619. this.pickedMesh = null;
  50620. this.bu = 0;
  50621. this.bv = 0;
  50622. this.faceId = -1;
  50623. this.subMeshId = 0;
  50624. this.pickedSprite = null;
  50625. }
  50626. // Methods
  50627. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  50628. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  50629. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  50630. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  50631. return null;
  50632. }
  50633. var indices = this.pickedMesh.getIndices();
  50634. if (!indices) {
  50635. return null;
  50636. }
  50637. var result;
  50638. if (useVerticesNormals) {
  50639. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50640. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  50641. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  50642. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  50643. normal0 = normal0.scale(this.bu);
  50644. normal1 = normal1.scale(this.bv);
  50645. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  50646. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  50647. }
  50648. else {
  50649. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50650. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  50651. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  50652. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  50653. var p1p2 = vertex1.subtract(vertex2);
  50654. var p3p2 = vertex3.subtract(vertex2);
  50655. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  50656. }
  50657. if (useWorldCoordinates) {
  50658. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  50659. }
  50660. return BABYLON.Vector3.Normalize(result);
  50661. };
  50662. PickingInfo.prototype.getTextureCoordinates = function () {
  50663. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  50664. return null;
  50665. }
  50666. var indices = this.pickedMesh.getIndices();
  50667. if (!indices) {
  50668. return null;
  50669. }
  50670. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  50671. if (!uvs) {
  50672. return null;
  50673. }
  50674. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  50675. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  50676. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  50677. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  50678. uv1 = uv1.scale(this.bu);
  50679. uv2 = uv2.scale(this.bv);
  50680. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  50681. };
  50682. return PickingInfo;
  50683. }());
  50684. BABYLON.PickingInfo = PickingInfo;
  50685. })(BABYLON || (BABYLON = {}));
  50686. //# sourceMappingURL=babylon.pickingInfo.js.map
  50687. "use strict";
  50688. var BABYLON;
  50689. (function (BABYLON) {
  50690. var Ray = /** @class */ (function () {
  50691. function Ray(origin, direction, length) {
  50692. if (length === void 0) { length = Number.MAX_VALUE; }
  50693. this.origin = origin;
  50694. this.direction = direction;
  50695. this.length = length;
  50696. }
  50697. // Methods
  50698. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  50699. var d = 0.0;
  50700. var maxValue = Number.MAX_VALUE;
  50701. var inv;
  50702. var min;
  50703. var max;
  50704. var temp;
  50705. if (Math.abs(this.direction.x) < 0.0000001) {
  50706. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  50707. return false;
  50708. }
  50709. }
  50710. else {
  50711. inv = 1.0 / this.direction.x;
  50712. min = (minimum.x - this.origin.x) * inv;
  50713. max = (maximum.x - this.origin.x) * inv;
  50714. if (max === -Infinity) {
  50715. max = Infinity;
  50716. }
  50717. if (min > max) {
  50718. temp = min;
  50719. min = max;
  50720. max = temp;
  50721. }
  50722. d = Math.max(min, d);
  50723. maxValue = Math.min(max, maxValue);
  50724. if (d > maxValue) {
  50725. return false;
  50726. }
  50727. }
  50728. if (Math.abs(this.direction.y) < 0.0000001) {
  50729. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  50730. return false;
  50731. }
  50732. }
  50733. else {
  50734. inv = 1.0 / this.direction.y;
  50735. min = (minimum.y - this.origin.y) * inv;
  50736. max = (maximum.y - this.origin.y) * inv;
  50737. if (max === -Infinity) {
  50738. max = Infinity;
  50739. }
  50740. if (min > max) {
  50741. temp = min;
  50742. min = max;
  50743. max = temp;
  50744. }
  50745. d = Math.max(min, d);
  50746. maxValue = Math.min(max, maxValue);
  50747. if (d > maxValue) {
  50748. return false;
  50749. }
  50750. }
  50751. if (Math.abs(this.direction.z) < 0.0000001) {
  50752. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  50753. return false;
  50754. }
  50755. }
  50756. else {
  50757. inv = 1.0 / this.direction.z;
  50758. min = (minimum.z - this.origin.z) * inv;
  50759. max = (maximum.z - this.origin.z) * inv;
  50760. if (max === -Infinity) {
  50761. max = Infinity;
  50762. }
  50763. if (min > max) {
  50764. temp = min;
  50765. min = max;
  50766. max = temp;
  50767. }
  50768. d = Math.max(min, d);
  50769. maxValue = Math.min(max, maxValue);
  50770. if (d > maxValue) {
  50771. return false;
  50772. }
  50773. }
  50774. return true;
  50775. };
  50776. Ray.prototype.intersectsBox = function (box) {
  50777. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  50778. };
  50779. Ray.prototype.intersectsSphere = function (sphere) {
  50780. var x = sphere.center.x - this.origin.x;
  50781. var y = sphere.center.y - this.origin.y;
  50782. var z = sphere.center.z - this.origin.z;
  50783. var pyth = (x * x) + (y * y) + (z * z);
  50784. var rr = sphere.radius * sphere.radius;
  50785. if (pyth <= rr) {
  50786. return true;
  50787. }
  50788. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  50789. if (dot < 0.0) {
  50790. return false;
  50791. }
  50792. var temp = pyth - (dot * dot);
  50793. return temp <= rr;
  50794. };
  50795. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  50796. if (!this._edge1) {
  50797. this._edge1 = BABYLON.Vector3.Zero();
  50798. this._edge2 = BABYLON.Vector3.Zero();
  50799. this._pvec = BABYLON.Vector3.Zero();
  50800. this._tvec = BABYLON.Vector3.Zero();
  50801. this._qvec = BABYLON.Vector3.Zero();
  50802. }
  50803. vertex1.subtractToRef(vertex0, this._edge1);
  50804. vertex2.subtractToRef(vertex0, this._edge2);
  50805. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  50806. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  50807. if (det === 0) {
  50808. return null;
  50809. }
  50810. var invdet = 1 / det;
  50811. this.origin.subtractToRef(vertex0, this._tvec);
  50812. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  50813. if (bu < 0 || bu > 1.0) {
  50814. return null;
  50815. }
  50816. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  50817. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  50818. if (bv < 0 || bu + bv > 1.0) {
  50819. return null;
  50820. }
  50821. //check if the distance is longer than the predefined length.
  50822. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  50823. if (distance > this.length) {
  50824. return null;
  50825. }
  50826. return new BABYLON.IntersectionInfo(bu, bv, distance);
  50827. };
  50828. Ray.prototype.intersectsPlane = function (plane) {
  50829. var distance;
  50830. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  50831. if (Math.abs(result1) < 9.99999997475243E-07) {
  50832. return null;
  50833. }
  50834. else {
  50835. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  50836. distance = (-plane.d - result2) / result1;
  50837. if (distance < 0.0) {
  50838. if (distance < -9.99999997475243E-07) {
  50839. return null;
  50840. }
  50841. else {
  50842. return 0;
  50843. }
  50844. }
  50845. return distance;
  50846. }
  50847. };
  50848. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  50849. var tm = BABYLON.Tmp.Matrix[0];
  50850. mesh.getWorldMatrix().invertToRef(tm);
  50851. if (this._tmpRay) {
  50852. Ray.TransformToRef(this, tm, this._tmpRay);
  50853. }
  50854. else {
  50855. this._tmpRay = Ray.Transform(this, tm);
  50856. }
  50857. return mesh.intersects(this._tmpRay, fastCheck);
  50858. };
  50859. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  50860. if (results) {
  50861. results.length = 0;
  50862. }
  50863. else {
  50864. results = [];
  50865. }
  50866. for (var i = 0; i < meshes.length; i++) {
  50867. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  50868. if (pickInfo.hit) {
  50869. results.push(pickInfo);
  50870. }
  50871. }
  50872. results.sort(this._comparePickingInfo);
  50873. return results;
  50874. };
  50875. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  50876. if (pickingInfoA.distance < pickingInfoB.distance) {
  50877. return -1;
  50878. }
  50879. else if (pickingInfoA.distance > pickingInfoB.distance) {
  50880. return 1;
  50881. }
  50882. else {
  50883. return 0;
  50884. }
  50885. };
  50886. /**
  50887. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  50888. * @param sega the first point of the segment to test the intersection against
  50889. * @param segb the second point of the segment to test the intersection against
  50890. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  50891. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  50892. */
  50893. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  50894. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  50895. var u = segb.subtract(sega);
  50896. var v = rsegb.subtract(this.origin);
  50897. var w = sega.subtract(this.origin);
  50898. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  50899. var b = BABYLON.Vector3.Dot(u, v);
  50900. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  50901. var d = BABYLON.Vector3.Dot(u, w);
  50902. var e = BABYLON.Vector3.Dot(v, w);
  50903. var D = a * c - b * b; // always >= 0
  50904. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  50905. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  50906. // compute the line parameters of the two closest points
  50907. if (D < Ray.smallnum) {
  50908. sN = 0.0; // force using point P0 on segment S1
  50909. sD = 1.0; // to prevent possible division by 0.0 later
  50910. tN = e;
  50911. tD = c;
  50912. }
  50913. else {
  50914. sN = (b * e - c * d);
  50915. tN = (a * e - b * d);
  50916. if (sN < 0.0) {
  50917. sN = 0.0;
  50918. tN = e;
  50919. tD = c;
  50920. }
  50921. else if (sN > sD) {
  50922. sN = sD;
  50923. tN = e + b;
  50924. tD = c;
  50925. }
  50926. }
  50927. if (tN < 0.0) {
  50928. tN = 0.0;
  50929. // recompute sc for this edge
  50930. if (-d < 0.0) {
  50931. sN = 0.0;
  50932. }
  50933. else if (-d > a)
  50934. sN = sD;
  50935. else {
  50936. sN = -d;
  50937. sD = a;
  50938. }
  50939. }
  50940. else if (tN > tD) {
  50941. tN = tD;
  50942. // recompute sc for this edge
  50943. if ((-d + b) < 0.0) {
  50944. sN = 0;
  50945. }
  50946. else if ((-d + b) > a) {
  50947. sN = sD;
  50948. }
  50949. else {
  50950. sN = (-d + b);
  50951. sD = a;
  50952. }
  50953. }
  50954. // finally do the division to get sc and tc
  50955. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  50956. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  50957. // get the difference of the two closest points
  50958. var qtc = v.multiplyByFloats(tc, tc, tc);
  50959. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  50960. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  50961. if (isIntersected) {
  50962. return qtc.length();
  50963. }
  50964. return -1;
  50965. };
  50966. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50967. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  50968. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  50969. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  50970. this.direction.normalize();
  50971. return this;
  50972. };
  50973. // Statics
  50974. Ray.Zero = function () {
  50975. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  50976. };
  50977. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50978. var result = Ray.Zero();
  50979. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  50980. };
  50981. /**
  50982. * 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
  50983. * transformed to the given world matrix.
  50984. * @param origin The origin point
  50985. * @param end The end point
  50986. * @param world a matrix to transform the ray to. Default is the identity matrix.
  50987. */
  50988. Ray.CreateNewFromTo = function (origin, end, world) {
  50989. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  50990. var direction = end.subtract(origin);
  50991. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  50992. direction.normalize();
  50993. return Ray.Transform(new Ray(origin, direction, length), world);
  50994. };
  50995. Ray.Transform = function (ray, matrix) {
  50996. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  50997. Ray.TransformToRef(ray, matrix, result);
  50998. return result;
  50999. };
  51000. Ray.TransformToRef = function (ray, matrix, result) {
  51001. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  51002. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  51003. result.length = ray.length;
  51004. var dir = result.direction;
  51005. var len = dir.length();
  51006. if (!(len === 0 || len === 1)) {
  51007. var num = 1.0 / len;
  51008. dir.x *= num;
  51009. dir.y *= num;
  51010. dir.z *= num;
  51011. result.length *= len;
  51012. }
  51013. };
  51014. Ray.smallnum = 0.00000001;
  51015. Ray.rayl = 10e8;
  51016. return Ray;
  51017. }());
  51018. BABYLON.Ray = Ray;
  51019. })(BABYLON || (BABYLON = {}));
  51020. //# sourceMappingURL=babylon.ray.js.map
  51021. "use strict";
  51022. var BABYLON;
  51023. (function (BABYLON) {
  51024. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  51025. if (boxMin.x > sphereCenter.x + sphereRadius)
  51026. return false;
  51027. if (sphereCenter.x - sphereRadius > boxMax.x)
  51028. return false;
  51029. if (boxMin.y > sphereCenter.y + sphereRadius)
  51030. return false;
  51031. if (sphereCenter.y - sphereRadius > boxMax.y)
  51032. return false;
  51033. if (boxMin.z > sphereCenter.z + sphereRadius)
  51034. return false;
  51035. if (sphereCenter.z - sphereRadius > boxMax.z)
  51036. return false;
  51037. return true;
  51038. };
  51039. var getLowestRoot = (function () {
  51040. var result = { root: 0, found: false };
  51041. return function (a, b, c, maxR) {
  51042. result.root = 0;
  51043. result.found = false;
  51044. var determinant = b * b - 4.0 * a * c;
  51045. if (determinant < 0)
  51046. return result;
  51047. var sqrtD = Math.sqrt(determinant);
  51048. var r1 = (-b - sqrtD) / (2.0 * a);
  51049. var r2 = (-b + sqrtD) / (2.0 * a);
  51050. if (r1 > r2) {
  51051. var temp = r2;
  51052. r2 = r1;
  51053. r1 = temp;
  51054. }
  51055. if (r1 > 0 && r1 < maxR) {
  51056. result.root = r1;
  51057. result.found = true;
  51058. return result;
  51059. }
  51060. if (r2 > 0 && r2 < maxR) {
  51061. result.root = r2;
  51062. result.found = true;
  51063. return result;
  51064. }
  51065. return result;
  51066. };
  51067. })();
  51068. var Collider = /** @class */ (function () {
  51069. function Collider() {
  51070. this._collisionPoint = BABYLON.Vector3.Zero();
  51071. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  51072. this._tempVector = BABYLON.Vector3.Zero();
  51073. this._tempVector2 = BABYLON.Vector3.Zero();
  51074. this._tempVector3 = BABYLON.Vector3.Zero();
  51075. this._tempVector4 = BABYLON.Vector3.Zero();
  51076. this._edge = BABYLON.Vector3.Zero();
  51077. this._baseToVertex = BABYLON.Vector3.Zero();
  51078. this._destinationPoint = BABYLON.Vector3.Zero();
  51079. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  51080. this._displacementVector = BABYLON.Vector3.Zero();
  51081. this._radius = BABYLON.Vector3.One();
  51082. this._retry = 0;
  51083. this._basePointWorld = BABYLON.Vector3.Zero();
  51084. this._velocityWorld = BABYLON.Vector3.Zero();
  51085. this._normalizedVelocity = BABYLON.Vector3.Zero();
  51086. this._collisionMask = -1;
  51087. }
  51088. Object.defineProperty(Collider.prototype, "collisionMask", {
  51089. get: function () {
  51090. return this._collisionMask;
  51091. },
  51092. set: function (mask) {
  51093. this._collisionMask = !isNaN(mask) ? mask : -1;
  51094. },
  51095. enumerable: true,
  51096. configurable: true
  51097. });
  51098. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  51099. /**
  51100. * Gets the plane normal used to compute the sliding response (in local space)
  51101. */
  51102. get: function () {
  51103. return this._slidePlaneNormal;
  51104. },
  51105. enumerable: true,
  51106. configurable: true
  51107. });
  51108. // Methods
  51109. Collider.prototype._initialize = function (source, dir, e) {
  51110. this._velocity = dir;
  51111. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  51112. this._basePoint = source;
  51113. source.multiplyToRef(this._radius, this._basePointWorld);
  51114. dir.multiplyToRef(this._radius, this._velocityWorld);
  51115. this._velocityWorldLength = this._velocityWorld.length();
  51116. this._epsilon = e;
  51117. this.collisionFound = false;
  51118. };
  51119. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  51120. pa.subtractToRef(point, this._tempVector);
  51121. pb.subtractToRef(point, this._tempVector2);
  51122. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  51123. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  51124. if (d < 0)
  51125. return false;
  51126. pc.subtractToRef(point, this._tempVector3);
  51127. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  51128. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  51129. if (d < 0)
  51130. return false;
  51131. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  51132. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  51133. return d >= 0;
  51134. };
  51135. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  51136. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  51137. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  51138. if (distance > this._velocityWorldLength + max + sphereRadius) {
  51139. return false;
  51140. }
  51141. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  51142. return false;
  51143. return true;
  51144. };
  51145. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  51146. var t0;
  51147. var embeddedInPlane = false;
  51148. //defensive programming, actually not needed.
  51149. if (!trianglePlaneArray) {
  51150. trianglePlaneArray = [];
  51151. }
  51152. if (!trianglePlaneArray[faceIndex]) {
  51153. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  51154. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  51155. }
  51156. var trianglePlane = trianglePlaneArray[faceIndex];
  51157. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  51158. return;
  51159. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  51160. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  51161. if (normalDotVelocity == 0) {
  51162. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  51163. return;
  51164. embeddedInPlane = true;
  51165. t0 = 0;
  51166. }
  51167. else {
  51168. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  51169. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  51170. if (t0 > t1) {
  51171. var temp = t1;
  51172. t1 = t0;
  51173. t0 = temp;
  51174. }
  51175. if (t0 > 1.0 || t1 < 0.0)
  51176. return;
  51177. if (t0 < 0)
  51178. t0 = 0;
  51179. if (t0 > 1.0)
  51180. t0 = 1.0;
  51181. }
  51182. this._collisionPoint.copyFromFloats(0, 0, 0);
  51183. var found = false;
  51184. var t = 1.0;
  51185. if (!embeddedInPlane) {
  51186. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  51187. this._velocity.scaleToRef(t0, this._tempVector);
  51188. this._planeIntersectionPoint.addInPlace(this._tempVector);
  51189. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  51190. found = true;
  51191. t = t0;
  51192. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  51193. }
  51194. }
  51195. if (!found) {
  51196. var velocitySquaredLength = this._velocity.lengthSquared();
  51197. var a = velocitySquaredLength;
  51198. this._basePoint.subtractToRef(p1, this._tempVector);
  51199. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  51200. var c = this._tempVector.lengthSquared() - 1.0;
  51201. var lowestRoot = getLowestRoot(a, b, c, t);
  51202. if (lowestRoot.found) {
  51203. t = lowestRoot.root;
  51204. found = true;
  51205. this._collisionPoint.copyFrom(p1);
  51206. }
  51207. this._basePoint.subtractToRef(p2, this._tempVector);
  51208. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  51209. c = this._tempVector.lengthSquared() - 1.0;
  51210. lowestRoot = getLowestRoot(a, b, c, t);
  51211. if (lowestRoot.found) {
  51212. t = lowestRoot.root;
  51213. found = true;
  51214. this._collisionPoint.copyFrom(p2);
  51215. }
  51216. this._basePoint.subtractToRef(p3, this._tempVector);
  51217. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  51218. c = this._tempVector.lengthSquared() - 1.0;
  51219. lowestRoot = getLowestRoot(a, b, c, t);
  51220. if (lowestRoot.found) {
  51221. t = lowestRoot.root;
  51222. found = true;
  51223. this._collisionPoint.copyFrom(p3);
  51224. }
  51225. p2.subtractToRef(p1, this._edge);
  51226. p1.subtractToRef(this._basePoint, this._baseToVertex);
  51227. var edgeSquaredLength = this._edge.lengthSquared();
  51228. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  51229. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  51230. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  51231. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  51232. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  51233. lowestRoot = getLowestRoot(a, b, c, t);
  51234. if (lowestRoot.found) {
  51235. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  51236. if (f >= 0.0 && f <= 1.0) {
  51237. t = lowestRoot.root;
  51238. found = true;
  51239. this._edge.scaleInPlace(f);
  51240. p1.addToRef(this._edge, this._collisionPoint);
  51241. }
  51242. }
  51243. p3.subtractToRef(p2, this._edge);
  51244. p2.subtractToRef(this._basePoint, this._baseToVertex);
  51245. edgeSquaredLength = this._edge.lengthSquared();
  51246. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  51247. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  51248. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  51249. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  51250. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  51251. lowestRoot = getLowestRoot(a, b, c, t);
  51252. if (lowestRoot.found) {
  51253. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  51254. if (f >= 0.0 && f <= 1.0) {
  51255. t = lowestRoot.root;
  51256. found = true;
  51257. this._edge.scaleInPlace(f);
  51258. p2.addToRef(this._edge, this._collisionPoint);
  51259. }
  51260. }
  51261. p1.subtractToRef(p3, this._edge);
  51262. p3.subtractToRef(this._basePoint, this._baseToVertex);
  51263. edgeSquaredLength = this._edge.lengthSquared();
  51264. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  51265. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  51266. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  51267. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  51268. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  51269. lowestRoot = getLowestRoot(a, b, c, t);
  51270. if (lowestRoot.found) {
  51271. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  51272. if (f >= 0.0 && f <= 1.0) {
  51273. t = lowestRoot.root;
  51274. found = true;
  51275. this._edge.scaleInPlace(f);
  51276. p3.addToRef(this._edge, this._collisionPoint);
  51277. }
  51278. }
  51279. }
  51280. if (found) {
  51281. var distToCollision = t * this._velocity.length();
  51282. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  51283. if (!this.intersectionPoint) {
  51284. this.intersectionPoint = this._collisionPoint.clone();
  51285. }
  51286. else {
  51287. this.intersectionPoint.copyFrom(this._collisionPoint);
  51288. }
  51289. this._nearestDistance = distToCollision;
  51290. this.collisionFound = true;
  51291. }
  51292. }
  51293. };
  51294. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  51295. for (var i = indexStart; i < indexEnd; i += 3) {
  51296. var p1 = pts[indices[i] - decal];
  51297. var p2 = pts[indices[i + 1] - decal];
  51298. var p3 = pts[indices[i + 2] - decal];
  51299. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  51300. }
  51301. };
  51302. Collider.prototype._getResponse = function (pos, vel) {
  51303. pos.addToRef(vel, this._destinationPoint);
  51304. vel.scaleInPlace((this._nearestDistance / vel.length()));
  51305. this._basePoint.addToRef(vel, pos);
  51306. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  51307. this._slidePlaneNormal.normalize();
  51308. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  51309. pos.addInPlace(this._displacementVector);
  51310. this.intersectionPoint.addInPlace(this._displacementVector);
  51311. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  51312. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  51313. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  51314. };
  51315. return Collider;
  51316. }());
  51317. BABYLON.Collider = Collider;
  51318. })(BABYLON || (BABYLON = {}));
  51319. //# sourceMappingURL=babylon.collider.js.map
  51320. "use strict";
  51321. var BABYLON;
  51322. (function (BABYLON) {
  51323. //WebWorker code will be inserted to this variable.
  51324. BABYLON.CollisionWorker = "";
  51325. var WorkerTaskType;
  51326. (function (WorkerTaskType) {
  51327. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  51328. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  51329. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  51330. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  51331. var WorkerReplyType;
  51332. (function (WorkerReplyType) {
  51333. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  51334. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  51335. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  51336. var CollisionCoordinatorWorker = /** @class */ (function () {
  51337. function CollisionCoordinatorWorker() {
  51338. var _this = this;
  51339. this._scaledPosition = BABYLON.Vector3.Zero();
  51340. this._scaledVelocity = BABYLON.Vector3.Zero();
  51341. this.onMeshUpdated = function (transformNode) {
  51342. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  51343. };
  51344. this.onGeometryUpdated = function (geometry) {
  51345. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  51346. };
  51347. this._afterRender = function () {
  51348. if (!_this._init)
  51349. return;
  51350. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  51351. return;
  51352. }
  51353. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  51354. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  51355. if (_this._runningUpdated > 4) {
  51356. return;
  51357. }
  51358. ++_this._runningUpdated;
  51359. var payload = {
  51360. updatedMeshes: _this._addUpdateMeshesList,
  51361. updatedGeometries: _this._addUpdateGeometriesList,
  51362. removedGeometries: _this._toRemoveGeometryArray,
  51363. removedMeshes: _this._toRemoveMeshesArray
  51364. };
  51365. var message = {
  51366. payload: payload,
  51367. taskType: WorkerTaskType.UPDATE
  51368. };
  51369. var serializable = [];
  51370. for (var id in payload.updatedGeometries) {
  51371. if (payload.updatedGeometries.hasOwnProperty(id)) {
  51372. //prepare transferables
  51373. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  51374. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  51375. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  51376. }
  51377. }
  51378. _this._worker.postMessage(message, serializable);
  51379. _this._addUpdateMeshesList = {};
  51380. _this._addUpdateGeometriesList = {};
  51381. _this._toRemoveGeometryArray = [];
  51382. _this._toRemoveMeshesArray = [];
  51383. };
  51384. this._onMessageFromWorker = function (e) {
  51385. var returnData = e.data;
  51386. if (returnData.error != WorkerReplyType.SUCCESS) {
  51387. //TODO what errors can be returned from the worker?
  51388. BABYLON.Tools.Warn("error returned from worker!");
  51389. return;
  51390. }
  51391. switch (returnData.taskType) {
  51392. case WorkerTaskType.INIT:
  51393. _this._init = true;
  51394. //Update the worked with ALL of the scene's current state
  51395. _this._scene.meshes.forEach(function (mesh) {
  51396. _this.onMeshAdded(mesh);
  51397. });
  51398. _this._scene.getGeometries().forEach(function (geometry) {
  51399. _this.onGeometryAdded(geometry);
  51400. });
  51401. break;
  51402. case WorkerTaskType.UPDATE:
  51403. _this._runningUpdated--;
  51404. break;
  51405. case WorkerTaskType.COLLIDE:
  51406. var returnPayload = returnData.payload;
  51407. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  51408. return;
  51409. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  51410. if (callback) {
  51411. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  51412. if (mesh) {
  51413. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  51414. }
  51415. }
  51416. //cleanup
  51417. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  51418. break;
  51419. }
  51420. };
  51421. this._collisionsCallbackArray = [];
  51422. this._init = false;
  51423. this._runningUpdated = 0;
  51424. this._addUpdateMeshesList = {};
  51425. this._addUpdateGeometriesList = {};
  51426. this._toRemoveGeometryArray = [];
  51427. this._toRemoveMeshesArray = [];
  51428. }
  51429. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  51430. if (!this._init)
  51431. return;
  51432. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  51433. return;
  51434. position.divideToRef(collider._radius, this._scaledPosition);
  51435. displacement.divideToRef(collider._radius, this._scaledVelocity);
  51436. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  51437. var payload = {
  51438. collider: {
  51439. position: this._scaledPosition.asArray(),
  51440. velocity: this._scaledVelocity.asArray(),
  51441. radius: collider._radius.asArray()
  51442. },
  51443. collisionId: collisionIndex,
  51444. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  51445. maximumRetry: maximumRetry
  51446. };
  51447. var message = {
  51448. payload: payload,
  51449. taskType: WorkerTaskType.COLLIDE
  51450. };
  51451. this._worker.postMessage(message);
  51452. };
  51453. CollisionCoordinatorWorker.prototype.init = function (scene) {
  51454. this._scene = scene;
  51455. this._scene.registerAfterRender(this._afterRender);
  51456. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  51457. this._worker = new Worker(workerUrl);
  51458. this._worker.onmessage = this._onMessageFromWorker;
  51459. var message = {
  51460. payload: {},
  51461. taskType: WorkerTaskType.INIT
  51462. };
  51463. this._worker.postMessage(message);
  51464. };
  51465. CollisionCoordinatorWorker.prototype.destroy = function () {
  51466. this._scene.unregisterAfterRender(this._afterRender);
  51467. this._worker.terminate();
  51468. };
  51469. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  51470. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  51471. this.onMeshUpdated(mesh);
  51472. };
  51473. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  51474. this._toRemoveMeshesArray.push(mesh.uniqueId);
  51475. };
  51476. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  51477. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  51478. geometry.onGeometryUpdated = this.onGeometryUpdated;
  51479. this.onGeometryUpdated(geometry);
  51480. };
  51481. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  51482. this._toRemoveGeometryArray.push(geometry.id);
  51483. };
  51484. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  51485. var submeshes = [];
  51486. if (mesh.subMeshes) {
  51487. submeshes = mesh.subMeshes.map(function (sm, idx) {
  51488. var boundingInfo = sm.getBoundingInfo();
  51489. return {
  51490. position: idx,
  51491. verticesStart: sm.verticesStart,
  51492. verticesCount: sm.verticesCount,
  51493. indexStart: sm.indexStart,
  51494. indexCount: sm.indexCount,
  51495. hasMaterial: !!sm.getMaterial(),
  51496. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  51497. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  51498. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  51499. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  51500. };
  51501. });
  51502. }
  51503. var geometryId = null;
  51504. if (mesh instanceof BABYLON.Mesh) {
  51505. var geometry = mesh.geometry;
  51506. geometryId = geometry ? geometry.id : null;
  51507. }
  51508. else if (mesh instanceof BABYLON.InstancedMesh) {
  51509. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  51510. geometryId = geometry ? geometry.id : null;
  51511. }
  51512. var boundingInfo = mesh.getBoundingInfo();
  51513. return {
  51514. uniqueId: mesh.uniqueId,
  51515. id: mesh.id,
  51516. name: mesh.name,
  51517. geometryId: geometryId,
  51518. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  51519. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  51520. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  51521. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  51522. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  51523. subMeshes: submeshes,
  51524. checkCollisions: mesh.checkCollisions
  51525. };
  51526. };
  51527. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  51528. return {
  51529. id: geometry.id,
  51530. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  51531. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  51532. indices: new Uint32Array(geometry.getIndices() || []),
  51533. };
  51534. };
  51535. return CollisionCoordinatorWorker;
  51536. }());
  51537. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  51538. var CollisionCoordinatorLegacy = /** @class */ (function () {
  51539. function CollisionCoordinatorLegacy() {
  51540. this._scaledPosition = BABYLON.Vector3.Zero();
  51541. this._scaledVelocity = BABYLON.Vector3.Zero();
  51542. this._finalPosition = BABYLON.Vector3.Zero();
  51543. }
  51544. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  51545. position.divideToRef(collider._radius, this._scaledPosition);
  51546. displacement.divideToRef(collider._radius, this._scaledVelocity);
  51547. collider.collidedMesh = null;
  51548. collider._retry = 0;
  51549. collider._initialVelocity = this._scaledVelocity;
  51550. collider._initialPosition = this._scaledPosition;
  51551. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  51552. this._finalPosition.multiplyInPlace(collider._radius);
  51553. //run the callback
  51554. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  51555. };
  51556. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  51557. this._scene = scene;
  51558. };
  51559. CollisionCoordinatorLegacy.prototype.destroy = function () {
  51560. //Legacy need no destruction method.
  51561. };
  51562. //No update in legacy mode
  51563. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  51564. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  51565. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  51566. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  51567. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  51568. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  51569. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  51570. if (excludedMesh === void 0) { excludedMesh = null; }
  51571. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  51572. if (collider._retry >= maximumRetry) {
  51573. finalPosition.copyFrom(position);
  51574. return;
  51575. }
  51576. // Check if this is a mesh else camera or -1
  51577. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  51578. collider._initialize(position, velocity, closeDistance);
  51579. // Check all meshes
  51580. for (var index = 0; index < this._scene.meshes.length; index++) {
  51581. var mesh = this._scene.meshes[index];
  51582. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  51583. mesh._checkCollision(collider);
  51584. }
  51585. }
  51586. if (!collider.collisionFound) {
  51587. position.addToRef(velocity, finalPosition);
  51588. return;
  51589. }
  51590. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  51591. collider._getResponse(position, velocity);
  51592. }
  51593. if (velocity.length() <= closeDistance) {
  51594. finalPosition.copyFrom(position);
  51595. return;
  51596. }
  51597. collider._retry++;
  51598. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  51599. };
  51600. return CollisionCoordinatorLegacy;
  51601. }());
  51602. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  51603. })(BABYLON || (BABYLON = {}));
  51604. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  51605. "use strict";
  51606. var BABYLON;
  51607. (function (BABYLON) {
  51608. /**
  51609. * A particle represents one of the element emitted by a particle system.
  51610. * This is mainly define by its coordinates, direction, velocity and age.
  51611. */
  51612. var Particle = /** @class */ (function () {
  51613. /**
  51614. * Creates a new instance Particle
  51615. * @param particleSystem the particle system the particle belongs to
  51616. */
  51617. function Particle(
  51618. /**
  51619. * particleSystem the particle system the particle belongs to.
  51620. */
  51621. particleSystem) {
  51622. this.particleSystem = particleSystem;
  51623. /**
  51624. * The world position of the particle in the scene.
  51625. */
  51626. this.position = BABYLON.Vector3.Zero();
  51627. /**
  51628. * The world direction of the particle in the scene.
  51629. */
  51630. this.direction = BABYLON.Vector3.Zero();
  51631. /**
  51632. * The color of the particle.
  51633. */
  51634. this.color = new BABYLON.Color4(0, 0, 0, 0);
  51635. /**
  51636. * The color change of the particle per step.
  51637. */
  51638. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  51639. /**
  51640. * Defines how long will the life of the particle be.
  51641. */
  51642. this.lifeTime = 1.0;
  51643. /**
  51644. * The current age of the particle.
  51645. */
  51646. this.age = 0;
  51647. /**
  51648. * The current size of the particle.
  51649. */
  51650. this.size = 0;
  51651. /**
  51652. * The current angle of the particle.
  51653. */
  51654. this.angle = 0;
  51655. /**
  51656. * Defines how fast is the angle changing.
  51657. */
  51658. this.angularSpeed = 0;
  51659. /**
  51660. * Defines the cell index used by the particle to be rendered from a sprite.
  51661. */
  51662. this.cellIndex = 0;
  51663. this._currentFrameCounter = 0;
  51664. if (!this.particleSystem.isAnimationSheetEnabled) {
  51665. return;
  51666. }
  51667. this.updateCellInfoFromSystem();
  51668. }
  51669. Particle.prototype.updateCellInfoFromSystem = function () {
  51670. this.cellIndex = this.particleSystem.startSpriteCellID;
  51671. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  51672. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  51673. }
  51674. else {
  51675. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  51676. }
  51677. };
  51678. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  51679. // (ageOffset / scaledUpdateSpeed) / available cells
  51680. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  51681. this._currentFrameCounter += scaledUpdateSpeed;
  51682. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  51683. this._currentFrameCounter = 0;
  51684. this.cellIndex++;
  51685. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  51686. this.cellIndex = this.particleSystem.endSpriteCellID;
  51687. }
  51688. }
  51689. };
  51690. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  51691. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  51692. this.cellIndex++;
  51693. this._currentFrameCounter = 0;
  51694. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  51695. if (this.particleSystem.spriteCellLoop) {
  51696. this.cellIndex = this.particleSystem.startSpriteCellID;
  51697. }
  51698. else {
  51699. this.cellIndex = this.particleSystem.endSpriteCellID;
  51700. }
  51701. }
  51702. }
  51703. else {
  51704. this._currentFrameCounter++;
  51705. }
  51706. };
  51707. /**
  51708. * Copy the properties of particle to another one.
  51709. * @param other the particle to copy the information to.
  51710. */
  51711. Particle.prototype.copyTo = function (other) {
  51712. other.position.copyFrom(this.position);
  51713. other.direction.copyFrom(this.direction);
  51714. other.color.copyFrom(this.color);
  51715. other.colorStep.copyFrom(this.colorStep);
  51716. other.lifeTime = this.lifeTime;
  51717. other.age = this.age;
  51718. other.size = this.size;
  51719. other.angle = this.angle;
  51720. other.angularSpeed = this.angularSpeed;
  51721. other.particleSystem = this.particleSystem;
  51722. other.cellIndex = this.cellIndex;
  51723. };
  51724. return Particle;
  51725. }());
  51726. BABYLON.Particle = Particle;
  51727. })(BABYLON || (BABYLON = {}));
  51728. //# sourceMappingURL=babylon.particle.js.map
  51729. "use strict";
  51730. var BABYLON;
  51731. (function (BABYLON) {
  51732. /**
  51733. * This represents a particle system in Babylon.
  51734. * 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.
  51735. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  51736. * @example https://doc.babylonjs.com/babylon101/particles
  51737. */
  51738. var ParticleSystem = /** @class */ (function () {
  51739. /**
  51740. * Instantiates a particle system.
  51741. * 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.
  51742. * @param name The name of the particle system
  51743. * @param capacity The max number of particles alive at the same time
  51744. * @param scene The scene the particle system belongs to
  51745. * @param customEffect a custom effect used to change the way particles are rendered by default
  51746. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  51747. * @param epsilon Offset used to render the particles
  51748. */
  51749. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  51750. if (customEffect === void 0) { customEffect = null; }
  51751. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  51752. if (epsilon === void 0) { epsilon = 0.01; }
  51753. var _this = this;
  51754. /**
  51755. * List of animations used by the particle system.
  51756. */
  51757. this.animations = [];
  51758. /**
  51759. * The rendering group used by the Particle system to chose when to render.
  51760. */
  51761. this.renderingGroupId = 0;
  51762. /**
  51763. * The emitter represents the Mesh or position we are attaching the particle system to.
  51764. */
  51765. this.emitter = null;
  51766. /**
  51767. * The maximum number of particles to emit per frame
  51768. */
  51769. this.emitRate = 10;
  51770. /**
  51771. * If you want to launch only a few particles at once, that can be done, as well.
  51772. */
  51773. this.manualEmitCount = -1;
  51774. /**
  51775. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  51776. */
  51777. this.updateSpeed = 0.01;
  51778. /**
  51779. * The amount of time the particle system is running (depends of the overall update speed).
  51780. */
  51781. this.targetStopDuration = 0;
  51782. /**
  51783. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  51784. */
  51785. this.disposeOnStop = false;
  51786. /**
  51787. * Minimum power of emitting particles.
  51788. */
  51789. this.minEmitPower = 1;
  51790. /**
  51791. * Maximum power of emitting particles.
  51792. */
  51793. this.maxEmitPower = 1;
  51794. /**
  51795. * Minimum life time of emitting particles.
  51796. */
  51797. this.minLifeTime = 1;
  51798. /**
  51799. * Maximum life time of emitting particles.
  51800. */
  51801. this.maxLifeTime = 1;
  51802. /**
  51803. * Minimum Size of emitting particles.
  51804. */
  51805. this.minSize = 1;
  51806. /**
  51807. * Maximum Size of emitting particles.
  51808. */
  51809. this.maxSize = 1;
  51810. /**
  51811. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  51812. */
  51813. this.minAngularSpeed = 0;
  51814. /**
  51815. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  51816. */
  51817. this.maxAngularSpeed = 0;
  51818. /**
  51819. * The layer mask we are rendering the particles through.
  51820. */
  51821. this.layerMask = 0x0FFFFFFF;
  51822. /**
  51823. * This can help using your own shader to render the particle system.
  51824. * The according effect will be created
  51825. */
  51826. this.customShader = null;
  51827. /**
  51828. * By default particle system starts as soon as they are created. This prevents the
  51829. * automatic start to happen and let you decide when to start emitting particles.
  51830. */
  51831. this.preventAutoStart = false;
  51832. /**
  51833. * Callback triggered when the particle animation is ending.
  51834. */
  51835. this.onAnimationEnd = null;
  51836. /**
  51837. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  51838. */
  51839. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  51840. /**
  51841. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  51842. * to override the particles.
  51843. */
  51844. this.forceDepthWrite = false;
  51845. /**
  51846. * You can use gravity if you want to give an orientation to your particles.
  51847. */
  51848. this.gravity = BABYLON.Vector3.Zero();
  51849. /**
  51850. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51851. */
  51852. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51853. /**
  51854. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51855. */
  51856. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51857. /**
  51858. * Color the particle will have at the end of its lifetime.
  51859. */
  51860. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  51861. /**
  51862. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  51863. */
  51864. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51865. /**
  51866. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  51867. */
  51868. this.spriteCellLoop = true;
  51869. /**
  51870. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  51871. */
  51872. this.spriteCellChangeSpeed = 0;
  51873. /**
  51874. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  51875. */
  51876. this.startSpriteCellID = 0;
  51877. /**
  51878. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  51879. */
  51880. this.endSpriteCellID = 0;
  51881. /**
  51882. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  51883. */
  51884. this.spriteCellWidth = 0;
  51885. /**
  51886. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  51887. */
  51888. this.spriteCellHeight = 0;
  51889. /**
  51890. * An event triggered when the system is disposed.
  51891. */
  51892. this.onDisposeObservable = new BABYLON.Observable();
  51893. this._particles = new Array();
  51894. this._stockParticles = new Array();
  51895. this._newPartsExcess = 0;
  51896. this._vertexBuffers = {};
  51897. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  51898. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  51899. this._scaledDirection = BABYLON.Vector3.Zero();
  51900. this._scaledGravity = BABYLON.Vector3.Zero();
  51901. this._currentRenderId = -1;
  51902. this._started = false;
  51903. this._stopped = false;
  51904. this._actualFrame = 0;
  51905. this._vertexBufferSize = 11;
  51906. // start of sub system methods
  51907. /**
  51908. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  51909. * Its lifetime will start back at 0.
  51910. */
  51911. this.recycleParticle = function (particle) {
  51912. var lastParticle = _this._particles.pop();
  51913. if (lastParticle !== particle) {
  51914. lastParticle.copyTo(particle);
  51915. }
  51916. _this._stockParticles.push(lastParticle);
  51917. };
  51918. this._createParticle = function () {
  51919. var particle;
  51920. if (_this._stockParticles.length !== 0) {
  51921. particle = _this._stockParticles.pop();
  51922. particle.age = 0;
  51923. particle.cellIndex = _this.startSpriteCellID;
  51924. }
  51925. else {
  51926. particle = new BABYLON.Particle(_this);
  51927. }
  51928. return particle;
  51929. };
  51930. this._emitFromParticle = function (particle) {
  51931. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  51932. return;
  51933. }
  51934. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  51935. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  51936. subSystem._rootParticleSystem = _this;
  51937. _this.activeSubSystems.push(subSystem);
  51938. subSystem.start();
  51939. };
  51940. this._appendParticleVertexes = null;
  51941. this.id = name;
  51942. this.name = name;
  51943. this._capacity = capacity;
  51944. this._epsilon = epsilon;
  51945. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  51946. if (isAnimationSheetEnabled) {
  51947. this._vertexBufferSize = 12;
  51948. }
  51949. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51950. this._customEffect = customEffect;
  51951. scene.particleSystems.push(this);
  51952. this._createIndexBuffer();
  51953. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  51954. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  51955. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  51956. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  51957. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  51958. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  51959. if (this._isAnimationSheetEnabled) {
  51960. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  51961. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  51962. }
  51963. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  51964. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  51965. this._vertexBuffers["options"] = options;
  51966. // Default emitter type
  51967. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  51968. this.updateFunction = function (particles) {
  51969. for (var index = 0; index < particles.length; index++) {
  51970. var particle = particles[index];
  51971. particle.age += _this._scaledUpdateSpeed;
  51972. if (particle.age >= particle.lifeTime) {
  51973. _this._emitFromParticle(particle);
  51974. _this.recycleParticle(particle);
  51975. index--;
  51976. continue;
  51977. }
  51978. else {
  51979. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  51980. particle.color.addInPlace(_this._scaledColorStep);
  51981. if (particle.color.a < 0)
  51982. particle.color.a = 0;
  51983. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  51984. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  51985. particle.position.addInPlace(_this._scaledDirection);
  51986. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  51987. particle.direction.addInPlace(_this._scaledGravity);
  51988. if (_this._isAnimationSheetEnabled) {
  51989. particle.updateCellIndex(_this._scaledUpdateSpeed);
  51990. }
  51991. }
  51992. }
  51993. };
  51994. }
  51995. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  51996. /**
  51997. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51998. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51999. */
  52000. get: function () {
  52001. if (this.particleEmitterType.direction1) {
  52002. return this.particleEmitterType.direction1;
  52003. }
  52004. return BABYLON.Vector3.Zero();
  52005. },
  52006. set: function (value) {
  52007. if (this.particleEmitterType.direction1) {
  52008. this.particleEmitterType.direction1 = value;
  52009. }
  52010. },
  52011. enumerable: true,
  52012. configurable: true
  52013. });
  52014. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  52015. /**
  52016. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52017. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52018. */
  52019. get: function () {
  52020. if (this.particleEmitterType.direction2) {
  52021. return this.particleEmitterType.direction2;
  52022. }
  52023. return BABYLON.Vector3.Zero();
  52024. },
  52025. set: function (value) {
  52026. if (this.particleEmitterType.direction2) {
  52027. this.particleEmitterType.direction2 = value;
  52028. }
  52029. },
  52030. enumerable: true,
  52031. configurable: true
  52032. });
  52033. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  52034. /**
  52035. * 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.
  52036. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52037. */
  52038. get: function () {
  52039. if (this.particleEmitterType.minEmitBox) {
  52040. return this.particleEmitterType.minEmitBox;
  52041. }
  52042. return BABYLON.Vector3.Zero();
  52043. },
  52044. set: function (value) {
  52045. if (this.particleEmitterType.minEmitBox) {
  52046. this.particleEmitterType.minEmitBox = value;
  52047. }
  52048. },
  52049. enumerable: true,
  52050. configurable: true
  52051. });
  52052. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  52053. /**
  52054. * 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.
  52055. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52056. */
  52057. get: function () {
  52058. if (this.particleEmitterType.maxEmitBox) {
  52059. return this.particleEmitterType.maxEmitBox;
  52060. }
  52061. return BABYLON.Vector3.Zero();
  52062. },
  52063. set: function (value) {
  52064. if (this.particleEmitterType.maxEmitBox) {
  52065. this.particleEmitterType.maxEmitBox = value;
  52066. }
  52067. },
  52068. enumerable: true,
  52069. configurable: true
  52070. });
  52071. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  52072. /**
  52073. * Sets a callback that will be triggered when the system is disposed.
  52074. */
  52075. set: function (callback) {
  52076. if (this._onDisposeObserver) {
  52077. this.onDisposeObservable.remove(this._onDisposeObserver);
  52078. }
  52079. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  52080. },
  52081. enumerable: true,
  52082. configurable: true
  52083. });
  52084. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  52085. /**
  52086. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  52087. */
  52088. get: function () {
  52089. return this._isAnimationSheetEnabled;
  52090. },
  52091. enumerable: true,
  52092. configurable: true
  52093. });
  52094. Object.defineProperty(ParticleSystem.prototype, "particles", {
  52095. //end of Sub-emitter
  52096. /**
  52097. * Gets the current list of active particles
  52098. */
  52099. get: function () {
  52100. return this._particles;
  52101. },
  52102. enumerable: true,
  52103. configurable: true
  52104. });
  52105. /**
  52106. * Returns the string "ParticleSystem"
  52107. * @returns a string containing the class name
  52108. */
  52109. ParticleSystem.prototype.getClassName = function () {
  52110. return "ParticleSystem";
  52111. };
  52112. ParticleSystem.prototype._createIndexBuffer = function () {
  52113. var indices = [];
  52114. var index = 0;
  52115. for (var count = 0; count < this._capacity; count++) {
  52116. indices.push(index);
  52117. indices.push(index + 1);
  52118. indices.push(index + 2);
  52119. indices.push(index);
  52120. indices.push(index + 2);
  52121. indices.push(index + 3);
  52122. index += 4;
  52123. }
  52124. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  52125. };
  52126. /**
  52127. * Gets the maximum number of particles active at the same time.
  52128. * @returns The max number of active particles.
  52129. */
  52130. ParticleSystem.prototype.getCapacity = function () {
  52131. return this._capacity;
  52132. };
  52133. /**
  52134. * Gets Wether there are still active particles in the system.
  52135. * @returns True if it is alive, otherwise false.
  52136. */
  52137. ParticleSystem.prototype.isAlive = function () {
  52138. return this._alive;
  52139. };
  52140. /**
  52141. * Gets Wether the system has been started.
  52142. * @returns True if it has been started, otherwise false.
  52143. */
  52144. ParticleSystem.prototype.isStarted = function () {
  52145. return this._started;
  52146. };
  52147. /**
  52148. * Starts the particle system and begins to emit.
  52149. */
  52150. ParticleSystem.prototype.start = function () {
  52151. this._started = true;
  52152. this._stopped = false;
  52153. this._actualFrame = 0;
  52154. if (this.subEmitters && this.subEmitters.length != 0) {
  52155. this.activeSubSystems = new Array();
  52156. }
  52157. };
  52158. /**
  52159. * Stops the particle system.
  52160. * @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.
  52161. */
  52162. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  52163. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  52164. this._stopped = true;
  52165. if (stopSubEmitters) {
  52166. this._stopSubEmitters();
  52167. }
  52168. };
  52169. // animation sheet
  52170. /**
  52171. * Remove all active particles
  52172. */
  52173. ParticleSystem.prototype.reset = function () {
  52174. this._stockParticles = [];
  52175. this._particles = [];
  52176. };
  52177. /**
  52178. * @ignore (for internal use only)
  52179. */
  52180. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  52181. var offset = index * this._vertexBufferSize;
  52182. this._vertexData[offset] = particle.position.x;
  52183. this._vertexData[offset + 1] = particle.position.y;
  52184. this._vertexData[offset + 2] = particle.position.z;
  52185. this._vertexData[offset + 3] = particle.color.r;
  52186. this._vertexData[offset + 4] = particle.color.g;
  52187. this._vertexData[offset + 5] = particle.color.b;
  52188. this._vertexData[offset + 6] = particle.color.a;
  52189. this._vertexData[offset + 7] = particle.angle;
  52190. this._vertexData[offset + 8] = particle.size;
  52191. this._vertexData[offset + 9] = offsetX;
  52192. this._vertexData[offset + 10] = offsetY;
  52193. };
  52194. /**
  52195. * @ignore (for internal use only)
  52196. */
  52197. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  52198. if (offsetX === 0)
  52199. offsetX = this._epsilon;
  52200. else if (offsetX === 1)
  52201. offsetX = 1 - this._epsilon;
  52202. if (offsetY === 0)
  52203. offsetY = this._epsilon;
  52204. else if (offsetY === 1)
  52205. offsetY = 1 - this._epsilon;
  52206. var offset = index * this._vertexBufferSize;
  52207. this._vertexData[offset] = particle.position.x;
  52208. this._vertexData[offset + 1] = particle.position.y;
  52209. this._vertexData[offset + 2] = particle.position.z;
  52210. this._vertexData[offset + 3] = particle.color.r;
  52211. this._vertexData[offset + 4] = particle.color.g;
  52212. this._vertexData[offset + 5] = particle.color.b;
  52213. this._vertexData[offset + 6] = particle.color.a;
  52214. this._vertexData[offset + 7] = particle.angle;
  52215. this._vertexData[offset + 8] = particle.size;
  52216. this._vertexData[offset + 9] = offsetX;
  52217. this._vertexData[offset + 10] = offsetY;
  52218. this._vertexData[offset + 11] = particle.cellIndex;
  52219. };
  52220. ParticleSystem.prototype._stopSubEmitters = function () {
  52221. if (!this.activeSubSystems) {
  52222. return;
  52223. }
  52224. this.activeSubSystems.forEach(function (subSystem) {
  52225. subSystem.stop(true);
  52226. });
  52227. this.activeSubSystems = new Array();
  52228. };
  52229. ParticleSystem.prototype._removeFromRoot = function () {
  52230. if (!this._rootParticleSystem) {
  52231. return;
  52232. }
  52233. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  52234. if (index !== -1) {
  52235. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  52236. }
  52237. };
  52238. // end of sub system methods
  52239. ParticleSystem.prototype._update = function (newParticles) {
  52240. // Update current
  52241. this._alive = this._particles.length > 0;
  52242. this.updateFunction(this._particles);
  52243. // Add new ones
  52244. var worldMatrix;
  52245. if (this.emitter.position) {
  52246. var emitterMesh = this.emitter;
  52247. worldMatrix = emitterMesh.getWorldMatrix();
  52248. }
  52249. else {
  52250. var emitterPosition = this.emitter;
  52251. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  52252. }
  52253. var particle;
  52254. for (var index = 0; index < newParticles; index++) {
  52255. if (this._particles.length === this._capacity) {
  52256. break;
  52257. }
  52258. particle = this._createParticle();
  52259. this._particles.push(particle);
  52260. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  52261. if (this.startPositionFunction) {
  52262. this.startPositionFunction(worldMatrix, particle.position, particle);
  52263. }
  52264. else {
  52265. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  52266. }
  52267. if (this.startDirectionFunction) {
  52268. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  52269. }
  52270. else {
  52271. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  52272. }
  52273. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  52274. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  52275. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  52276. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  52277. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  52278. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  52279. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  52280. }
  52281. };
  52282. ParticleSystem.prototype._getEffect = function () {
  52283. if (this._customEffect) {
  52284. return this._customEffect;
  52285. }
  52286. ;
  52287. var defines = [];
  52288. if (this._scene.clipPlane) {
  52289. defines.push("#define CLIPPLANE");
  52290. }
  52291. if (this._isAnimationSheetEnabled) {
  52292. defines.push("#define ANIMATESHEET");
  52293. }
  52294. // Effect
  52295. var join = defines.join("\n");
  52296. if (this._cachedDefines !== join) {
  52297. this._cachedDefines = join;
  52298. var attributesNamesOrOptions;
  52299. var effectCreationOption;
  52300. if (this._isAnimationSheetEnabled) {
  52301. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  52302. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  52303. }
  52304. else {
  52305. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  52306. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  52307. }
  52308. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  52309. }
  52310. return this._effect;
  52311. };
  52312. /**
  52313. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  52314. */
  52315. ParticleSystem.prototype.animate = function () {
  52316. if (!this._started)
  52317. return;
  52318. var effect = this._getEffect();
  52319. // Check
  52320. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  52321. return;
  52322. if (this._currentRenderId === this._scene.getRenderId()) {
  52323. return;
  52324. }
  52325. this._currentRenderId = this._scene.getRenderId();
  52326. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  52327. // determine the number of particles we need to create
  52328. var newParticles;
  52329. if (this.manualEmitCount > -1) {
  52330. newParticles = this.manualEmitCount;
  52331. this._newPartsExcess = 0;
  52332. this.manualEmitCount = 0;
  52333. }
  52334. else {
  52335. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  52336. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  52337. }
  52338. if (this._newPartsExcess > 1.0) {
  52339. newParticles += this._newPartsExcess >> 0;
  52340. this._newPartsExcess -= this._newPartsExcess >> 0;
  52341. }
  52342. this._alive = false;
  52343. if (!this._stopped) {
  52344. this._actualFrame += this._scaledUpdateSpeed;
  52345. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  52346. this.stop();
  52347. }
  52348. else {
  52349. newParticles = 0;
  52350. }
  52351. this._update(newParticles);
  52352. // Stopped?
  52353. if (this._stopped) {
  52354. if (!this._alive) {
  52355. this._started = false;
  52356. if (this.onAnimationEnd) {
  52357. this.onAnimationEnd();
  52358. }
  52359. if (this.disposeOnStop) {
  52360. this._scene._toBeDisposed.push(this);
  52361. }
  52362. }
  52363. }
  52364. // Animation sheet
  52365. if (this._isAnimationSheetEnabled) {
  52366. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  52367. }
  52368. else {
  52369. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  52370. }
  52371. // Update VBO
  52372. var offset = 0;
  52373. for (var index = 0; index < this._particles.length; index++) {
  52374. var particle = this._particles[index];
  52375. this._appendParticleVertexes(offset, particle);
  52376. offset += 4;
  52377. }
  52378. if (this._vertexBuffer) {
  52379. this._vertexBuffer.update(this._vertexData);
  52380. }
  52381. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  52382. this.stop();
  52383. }
  52384. };
  52385. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  52386. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  52387. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  52388. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  52389. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  52390. };
  52391. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  52392. this._appendParticleVertex(offset++, particle, 0, 0);
  52393. this._appendParticleVertex(offset++, particle, 1, 0);
  52394. this._appendParticleVertex(offset++, particle, 1, 1);
  52395. this._appendParticleVertex(offset++, particle, 0, 1);
  52396. };
  52397. /**
  52398. * Rebuilds the particle system.
  52399. */
  52400. ParticleSystem.prototype.rebuild = function () {
  52401. this._createIndexBuffer();
  52402. if (this._vertexBuffer) {
  52403. this._vertexBuffer._rebuild();
  52404. }
  52405. };
  52406. /**
  52407. * Is this system ready to be used/rendered
  52408. * @return true if the system is ready
  52409. */
  52410. ParticleSystem.prototype.isReady = function () {
  52411. var effect = this._getEffect();
  52412. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  52413. return false;
  52414. }
  52415. return true;
  52416. };
  52417. /**
  52418. * Renders the particle system in its current state.
  52419. * @returns the current number of particles
  52420. */
  52421. ParticleSystem.prototype.render = function () {
  52422. var effect = this._getEffect();
  52423. // Check
  52424. if (!this.isReady() || !this._particles.length) {
  52425. return 0;
  52426. }
  52427. var engine = this._scene.getEngine();
  52428. // Render
  52429. engine.enableEffect(effect);
  52430. engine.setState(false);
  52431. var viewMatrix = this._scene.getViewMatrix();
  52432. effect.setTexture("diffuseSampler", this.particleTexture);
  52433. effect.setMatrix("view", viewMatrix);
  52434. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  52435. if (this._isAnimationSheetEnabled && this.particleTexture) {
  52436. var baseSize = this.particleTexture.getBaseSize();
  52437. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  52438. }
  52439. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  52440. if (this._scene.clipPlane) {
  52441. var clipPlane = this._scene.clipPlane;
  52442. var invView = viewMatrix.clone();
  52443. invView.invert();
  52444. effect.setMatrix("invView", invView);
  52445. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  52446. }
  52447. // VBOs
  52448. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  52449. // Draw order
  52450. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  52451. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  52452. }
  52453. else {
  52454. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  52455. }
  52456. if (this.forceDepthWrite) {
  52457. engine.setDepthWrite(true);
  52458. }
  52459. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  52460. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52461. return this._particles.length;
  52462. };
  52463. /**
  52464. * Disposes the particle system and free the associated resources
  52465. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  52466. */
  52467. ParticleSystem.prototype.dispose = function (disposeTexture) {
  52468. if (disposeTexture === void 0) { disposeTexture = true; }
  52469. if (this._vertexBuffer) {
  52470. this._vertexBuffer.dispose();
  52471. this._vertexBuffer = null;
  52472. }
  52473. if (this._indexBuffer) {
  52474. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  52475. this._indexBuffer = null;
  52476. }
  52477. if (disposeTexture && this.particleTexture) {
  52478. this.particleTexture.dispose();
  52479. this.particleTexture = null;
  52480. }
  52481. this._removeFromRoot();
  52482. // Remove from scene
  52483. var index = this._scene.particleSystems.indexOf(this);
  52484. if (index > -1) {
  52485. this._scene.particleSystems.splice(index, 1);
  52486. }
  52487. // Callback
  52488. this.onDisposeObservable.notifyObservers(this);
  52489. this.onDisposeObservable.clear();
  52490. };
  52491. /**
  52492. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  52493. * @param radius The radius of the sphere to emit from
  52494. * @returns the emitter
  52495. */
  52496. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  52497. if (radius === void 0) { radius = 1; }
  52498. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  52499. this.particleEmitterType = particleEmitter;
  52500. return particleEmitter;
  52501. };
  52502. /**
  52503. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  52504. * @param radius The radius of the sphere to emit from
  52505. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  52506. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  52507. * @returns the emitter
  52508. */
  52509. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  52510. if (radius === void 0) { radius = 1; }
  52511. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  52512. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  52513. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  52514. this.particleEmitterType = particleEmitter;
  52515. return particleEmitter;
  52516. };
  52517. /**
  52518. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  52519. * @param radius The radius of the cone to emit from
  52520. * @param angle The base angle of the cone
  52521. * @returns the emitter
  52522. */
  52523. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  52524. if (radius === void 0) { radius = 1; }
  52525. if (angle === void 0) { angle = Math.PI / 4; }
  52526. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  52527. this.particleEmitterType = particleEmitter;
  52528. return particleEmitter;
  52529. };
  52530. // 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.
  52531. /**
  52532. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  52533. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  52534. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  52535. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  52536. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  52537. * @returns the emitter
  52538. */
  52539. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  52540. var particleEmitter = new BABYLON.BoxParticleEmitter();
  52541. this.particleEmitterType = particleEmitter;
  52542. this.direction1 = direction1;
  52543. this.direction2 = direction2;
  52544. this.minEmitBox = minEmitBox;
  52545. this.maxEmitBox = maxEmitBox;
  52546. return particleEmitter;
  52547. };
  52548. // Clone
  52549. /**
  52550. * Clones the particle system.
  52551. * @param name The name of the cloned object
  52552. * @param newEmitter The new emitter to use
  52553. * @returns the cloned particle system
  52554. */
  52555. ParticleSystem.prototype.clone = function (name, newEmitter) {
  52556. var custom = null;
  52557. var program = null;
  52558. if (this.customShader != null) {
  52559. program = this.customShader;
  52560. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  52561. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  52562. }
  52563. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  52564. result.customShader = program;
  52565. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  52566. if (newEmitter === undefined) {
  52567. newEmitter = this.emitter;
  52568. }
  52569. result.emitter = newEmitter;
  52570. if (this.particleTexture) {
  52571. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  52572. }
  52573. if (!this.preventAutoStart) {
  52574. result.start();
  52575. }
  52576. return result;
  52577. };
  52578. /**
  52579. * Serializes the particle system to a JSON object.
  52580. * @returns the JSON object
  52581. */
  52582. ParticleSystem.prototype.serialize = function () {
  52583. var serializationObject = {};
  52584. serializationObject.name = this.name;
  52585. serializationObject.id = this.id;
  52586. // Emitter
  52587. if (this.emitter.position) {
  52588. var emitterMesh = this.emitter;
  52589. serializationObject.emitterId = emitterMesh.id;
  52590. }
  52591. else {
  52592. var emitterPosition = this.emitter;
  52593. serializationObject.emitter = emitterPosition.asArray();
  52594. }
  52595. serializationObject.capacity = this.getCapacity();
  52596. if (this.particleTexture) {
  52597. serializationObject.textureName = this.particleTexture.name;
  52598. }
  52599. // Animations
  52600. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  52601. // Particle system
  52602. serializationObject.minAngularSpeed = this.minAngularSpeed;
  52603. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  52604. serializationObject.minSize = this.minSize;
  52605. serializationObject.maxSize = this.maxSize;
  52606. serializationObject.minEmitPower = this.minEmitPower;
  52607. serializationObject.maxEmitPower = this.maxEmitPower;
  52608. serializationObject.minLifeTime = this.minLifeTime;
  52609. serializationObject.maxLifeTime = this.maxLifeTime;
  52610. serializationObject.emitRate = this.emitRate;
  52611. serializationObject.minEmitBox = this.minEmitBox.asArray();
  52612. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  52613. serializationObject.gravity = this.gravity.asArray();
  52614. serializationObject.direction1 = this.direction1.asArray();
  52615. serializationObject.direction2 = this.direction2.asArray();
  52616. serializationObject.color1 = this.color1.asArray();
  52617. serializationObject.color2 = this.color2.asArray();
  52618. serializationObject.colorDead = this.colorDead.asArray();
  52619. serializationObject.updateSpeed = this.updateSpeed;
  52620. serializationObject.targetStopDuration = this.targetStopDuration;
  52621. serializationObject.textureMask = this.textureMask.asArray();
  52622. serializationObject.blendMode = this.blendMode;
  52623. serializationObject.customShader = this.customShader;
  52624. serializationObject.preventAutoStart = this.preventAutoStart;
  52625. serializationObject.startSpriteCellID = this.startSpriteCellID;
  52626. serializationObject.endSpriteCellID = this.endSpriteCellID;
  52627. serializationObject.spriteCellLoop = this.spriteCellLoop;
  52628. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  52629. serializationObject.spriteCellWidth = this.spriteCellWidth;
  52630. serializationObject.spriteCellHeight = this.spriteCellHeight;
  52631. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  52632. // Emitter
  52633. if (this.particleEmitterType) {
  52634. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  52635. }
  52636. return serializationObject;
  52637. };
  52638. /**
  52639. * Parses a JSON object to create a particle system.
  52640. * @param parsedParticleSystem The JSON object to parse
  52641. * @param scene The scene to create the particle system in
  52642. * @param rootUrl The root url to use to load external dependencies like texture
  52643. * @returns the Parsed particle system
  52644. */
  52645. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  52646. var name = parsedParticleSystem.name;
  52647. var custom = null;
  52648. var program = null;
  52649. if (parsedParticleSystem.customShader) {
  52650. program = parsedParticleSystem.customShader;
  52651. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  52652. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  52653. }
  52654. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  52655. particleSystem.customShader = program;
  52656. if (parsedParticleSystem.id) {
  52657. particleSystem.id = parsedParticleSystem.id;
  52658. }
  52659. // Auto start
  52660. if (parsedParticleSystem.preventAutoStart) {
  52661. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  52662. }
  52663. // Texture
  52664. if (parsedParticleSystem.textureName) {
  52665. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  52666. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  52667. }
  52668. // Emitter
  52669. if (parsedParticleSystem.emitterId) {
  52670. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  52671. }
  52672. else {
  52673. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  52674. }
  52675. // Animations
  52676. if (parsedParticleSystem.animations) {
  52677. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  52678. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  52679. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  52680. }
  52681. }
  52682. if (parsedParticleSystem.autoAnimate) {
  52683. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  52684. }
  52685. // Particle system
  52686. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  52687. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  52688. particleSystem.minSize = parsedParticleSystem.minSize;
  52689. particleSystem.maxSize = parsedParticleSystem.maxSize;
  52690. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  52691. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  52692. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  52693. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  52694. particleSystem.emitRate = parsedParticleSystem.emitRate;
  52695. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  52696. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  52697. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  52698. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  52699. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  52700. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  52701. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  52702. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  52703. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  52704. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  52705. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  52706. particleSystem.blendMode = parsedParticleSystem.blendMode;
  52707. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  52708. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  52709. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  52710. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  52711. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  52712. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  52713. if (!particleSystem.preventAutoStart) {
  52714. particleSystem.start();
  52715. }
  52716. return particleSystem;
  52717. };
  52718. /**
  52719. * Source color is added to the destination color without alpha affecting the result.
  52720. */
  52721. ParticleSystem.BLENDMODE_ONEONE = 0;
  52722. /**
  52723. * Blend current color and particle color using particle’s alpha.
  52724. */
  52725. ParticleSystem.BLENDMODE_STANDARD = 1;
  52726. return ParticleSystem;
  52727. }());
  52728. BABYLON.ParticleSystem = ParticleSystem;
  52729. })(BABYLON || (BABYLON = {}));
  52730. //# sourceMappingURL=babylon.particleSystem.js.map
  52731. "use strict";
  52732. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  52733. "use strict";
  52734. var BABYLON;
  52735. (function (BABYLON) {
  52736. /**
  52737. * Particle emitter emitting particles from the inside of a box.
  52738. * It emits the particles randomly between 2 given directions.
  52739. */
  52740. var BoxParticleEmitter = /** @class */ (function () {
  52741. /**
  52742. * Creates a new instance BoxParticleEmitter
  52743. */
  52744. function BoxParticleEmitter() {
  52745. /**
  52746. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52747. */
  52748. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  52749. /**
  52750. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52751. */
  52752. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  52753. /**
  52754. * 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.
  52755. */
  52756. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  52757. /**
  52758. * 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.
  52759. */
  52760. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  52761. }
  52762. /**
  52763. * Called by the particle System when the direction is computed for the created particle.
  52764. * @param emitPower is the power of the particle (speed)
  52765. * @param worldMatrix is the world matrix of the particle system
  52766. * @param directionToUpdate is the direction vector to update with the result
  52767. * @param particle is the particle we are computed the direction for
  52768. */
  52769. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52770. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  52771. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  52772. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  52773. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  52774. };
  52775. /**
  52776. * Called by the particle System when the position is computed for the created particle.
  52777. * @param worldMatrix is the world matrix of the particle system
  52778. * @param positionToUpdate is the position vector to update with the result
  52779. * @param particle is the particle we are computed the position for
  52780. */
  52781. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52782. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  52783. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  52784. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  52785. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52786. };
  52787. /**
  52788. * Clones the current emitter and returns a copy of it
  52789. * @returns the new emitter
  52790. */
  52791. BoxParticleEmitter.prototype.clone = function () {
  52792. var newOne = new BoxParticleEmitter();
  52793. BABYLON.Tools.DeepCopy(this, newOne);
  52794. return newOne;
  52795. };
  52796. /**
  52797. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52798. * @param effect defines the update shader
  52799. */
  52800. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  52801. effect.setVector3("direction1", this.direction1);
  52802. effect.setVector3("direction2", this.direction2);
  52803. effect.setVector3("minEmitBox", this.minEmitBox);
  52804. effect.setVector3("maxEmitBox", this.maxEmitBox);
  52805. };
  52806. /**
  52807. * Returns a string to use to update the GPU particles update shader
  52808. * @returns a string containng the defines string
  52809. */
  52810. BoxParticleEmitter.prototype.getEffectDefines = function () {
  52811. return "#define BOXEMITTER";
  52812. };
  52813. /**
  52814. * Returns the string "BoxEmitter"
  52815. * @returns a string containing the class name
  52816. */
  52817. BoxParticleEmitter.prototype.getClassName = function () {
  52818. return "BoxEmitter";
  52819. };
  52820. /**
  52821. * Serializes the particle system to a JSON object.
  52822. * @returns the JSON object
  52823. */
  52824. BoxParticleEmitter.prototype.serialize = function () {
  52825. var serializationObject = {};
  52826. serializationObject.type = this.getClassName();
  52827. serializationObject.direction1 = this.direction1.asArray();
  52828. ;
  52829. serializationObject.direction2 = this.direction2.asArray();
  52830. ;
  52831. serializationObject.minEmitBox = this.minEmitBox.asArray();
  52832. ;
  52833. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  52834. ;
  52835. return serializationObject;
  52836. };
  52837. /**
  52838. * Parse properties from a JSON object
  52839. * @param serializationObject defines the JSON object
  52840. */
  52841. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  52842. this.direction1.copyFrom(serializationObject.direction1);
  52843. this.direction2.copyFrom(serializationObject.direction2);
  52844. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  52845. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  52846. };
  52847. return BoxParticleEmitter;
  52848. }());
  52849. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  52850. })(BABYLON || (BABYLON = {}));
  52851. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  52852. "use strict";
  52853. var BABYLON;
  52854. (function (BABYLON) {
  52855. /**
  52856. * Particle emitter emitting particles from the inside of a cone.
  52857. * It emits the particles alongside the cone volume from the base to the particle.
  52858. * The emission direction might be randomized.
  52859. */
  52860. var ConeParticleEmitter = /** @class */ (function () {
  52861. /**
  52862. * Creates a new instance ConeParticleEmitter
  52863. * @param radius the radius of the emission cone (1 by default)
  52864. * @param angles the cone base angle (PI by default)
  52865. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52866. */
  52867. function ConeParticleEmitter(radius,
  52868. /**
  52869. * The radius of the emission cone.
  52870. */
  52871. angle,
  52872. /**
  52873. * The cone base angle.
  52874. */
  52875. directionRandomizer) {
  52876. if (radius === void 0) { radius = 1; }
  52877. if (angle === void 0) { angle = Math.PI; }
  52878. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52879. this.angle = angle;
  52880. this.directionRandomizer = directionRandomizer;
  52881. this.radius = radius;
  52882. }
  52883. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  52884. /**
  52885. * Gets the radius of the emission cone.
  52886. */
  52887. get: function () {
  52888. return this._radius;
  52889. },
  52890. /**
  52891. * Sets the radius of the emission cone.
  52892. */
  52893. set: function (value) {
  52894. this._radius = value;
  52895. if (this.angle !== 0) {
  52896. this._height = value / Math.tan(this.angle / 2);
  52897. }
  52898. else {
  52899. this._height = 1;
  52900. }
  52901. },
  52902. enumerable: true,
  52903. configurable: true
  52904. });
  52905. /**
  52906. * Called by the particle System when the direction is computed for the created particle.
  52907. * @param emitPower is the power of the particle (speed)
  52908. * @param worldMatrix is the world matrix of the particle system
  52909. * @param directionToUpdate is the direction vector to update with the result
  52910. * @param particle is the particle we are computed the direction for
  52911. */
  52912. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52913. if (this.angle === 0) {
  52914. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  52915. }
  52916. else {
  52917. // measure the direction Vector from the emitter to the particle.
  52918. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52919. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52920. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52921. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52922. direction.x += randX;
  52923. direction.y += randY;
  52924. direction.z += randZ;
  52925. direction.normalize();
  52926. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52927. }
  52928. };
  52929. /**
  52930. * Called by the particle System when the position is computed for the created particle.
  52931. * @param worldMatrix is the world matrix of the particle system
  52932. * @param positionToUpdate is the position vector to update with the result
  52933. * @param particle is the particle we are computed the position for
  52934. */
  52935. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52936. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  52937. var h = BABYLON.Scalar.RandomRange(0, 1);
  52938. // Better distribution in a cone at normal angles.
  52939. h = 1 - h * h;
  52940. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  52941. radius = radius * h;
  52942. var randX = radius * Math.sin(s);
  52943. var randZ = radius * Math.cos(s);
  52944. var randY = h * this._height;
  52945. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52946. };
  52947. /**
  52948. * Clones the current emitter and returns a copy of it
  52949. * @returns the new emitter
  52950. */
  52951. ConeParticleEmitter.prototype.clone = function () {
  52952. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  52953. BABYLON.Tools.DeepCopy(this, newOne);
  52954. return newOne;
  52955. };
  52956. /**
  52957. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52958. * @param effect defines the update shader
  52959. */
  52960. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  52961. effect.setFloat("radius", this.radius);
  52962. effect.setFloat("angle", this.angle);
  52963. effect.setFloat("height", this._height);
  52964. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52965. };
  52966. /**
  52967. * Returns a string to use to update the GPU particles update shader
  52968. * @returns a string containng the defines string
  52969. */
  52970. ConeParticleEmitter.prototype.getEffectDefines = function () {
  52971. return "#define CONEEMITTER";
  52972. };
  52973. /**
  52974. * Returns the string "BoxEmitter"
  52975. * @returns a string containing the class name
  52976. */
  52977. ConeParticleEmitter.prototype.getClassName = function () {
  52978. return "ConeEmitter";
  52979. };
  52980. /**
  52981. * Serializes the particle system to a JSON object.
  52982. * @returns the JSON object
  52983. */
  52984. ConeParticleEmitter.prototype.serialize = function () {
  52985. var serializationObject = {};
  52986. serializationObject.type = this.getClassName();
  52987. serializationObject.radius = this.radius;
  52988. serializationObject.angle = this.angle;
  52989. serializationObject.directionRandomizer = this.directionRandomizer;
  52990. return serializationObject;
  52991. };
  52992. /**
  52993. * Parse properties from a JSON object
  52994. * @param serializationObject defines the JSON object
  52995. */
  52996. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  52997. this.radius = serializationObject.radius;
  52998. this.angle = serializationObject.angle;
  52999. this.directionRandomizer = serializationObject.directionRandomizer;
  53000. };
  53001. return ConeParticleEmitter;
  53002. }());
  53003. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  53004. })(BABYLON || (BABYLON = {}));
  53005. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  53006. "use strict";
  53007. var BABYLON;
  53008. (function (BABYLON) {
  53009. /**
  53010. * Particle emitter emitting particles from the inside of a sphere.
  53011. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  53012. */
  53013. var SphereParticleEmitter = /** @class */ (function () {
  53014. /**
  53015. * Creates a new instance SphereParticleEmitter
  53016. * @param radius the radius of the emission sphere (1 by default)
  53017. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  53018. */
  53019. function SphereParticleEmitter(
  53020. /**
  53021. * The radius of the emission sphere.
  53022. */
  53023. radius,
  53024. /**
  53025. * How much to randomize the particle direction [0-1].
  53026. */
  53027. directionRandomizer) {
  53028. if (radius === void 0) { radius = 1; }
  53029. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  53030. this.radius = radius;
  53031. this.directionRandomizer = directionRandomizer;
  53032. }
  53033. /**
  53034. * Called by the particle System when the direction is computed for the created particle.
  53035. * @param emitPower is the power of the particle (speed)
  53036. * @param worldMatrix is the world matrix of the particle system
  53037. * @param directionToUpdate is the direction vector to update with the result
  53038. * @param particle is the particle we are computed the direction for
  53039. */
  53040. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  53041. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  53042. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  53043. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  53044. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  53045. direction.x += randX;
  53046. direction.y += randY;
  53047. direction.z += randZ;
  53048. direction.normalize();
  53049. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  53050. };
  53051. /**
  53052. * Called by the particle System when the position is computed for the created particle.
  53053. * @param worldMatrix is the world matrix of the particle system
  53054. * @param positionToUpdate is the position vector to update with the result
  53055. * @param particle is the particle we are computed the position for
  53056. */
  53057. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  53058. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  53059. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  53060. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  53061. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  53062. var randY = randRadius * Math.cos(theta);
  53063. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  53064. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  53065. };
  53066. /**
  53067. * Clones the current emitter and returns a copy of it
  53068. * @returns the new emitter
  53069. */
  53070. SphereParticleEmitter.prototype.clone = function () {
  53071. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  53072. BABYLON.Tools.DeepCopy(this, newOne);
  53073. return newOne;
  53074. };
  53075. /**
  53076. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  53077. * @param effect defines the update shader
  53078. */
  53079. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  53080. effect.setFloat("radius", this.radius);
  53081. effect.setFloat("directionRandomizer", this.directionRandomizer);
  53082. };
  53083. /**
  53084. * Returns a string to use to update the GPU particles update shader
  53085. * @returns a string containng the defines string
  53086. */
  53087. SphereParticleEmitter.prototype.getEffectDefines = function () {
  53088. return "#define SPHEREEMITTER";
  53089. };
  53090. /**
  53091. * Returns the string "SphereParticleEmitter"
  53092. * @returns a string containing the class name
  53093. */
  53094. SphereParticleEmitter.prototype.getClassName = function () {
  53095. return "SphereParticleEmitter";
  53096. };
  53097. /**
  53098. * Serializes the particle system to a JSON object.
  53099. * @returns the JSON object
  53100. */
  53101. SphereParticleEmitter.prototype.serialize = function () {
  53102. var serializationObject = {};
  53103. serializationObject.type = this.getClassName();
  53104. serializationObject.radius = this.radius;
  53105. serializationObject.directionRandomizer = this.directionRandomizer;
  53106. return serializationObject;
  53107. };
  53108. /**
  53109. * Parse properties from a JSON object
  53110. * @param serializationObject defines the JSON object
  53111. */
  53112. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  53113. this.radius = serializationObject.radius;
  53114. this.directionRandomizer = serializationObject.directionRandomizer;
  53115. };
  53116. return SphereParticleEmitter;
  53117. }());
  53118. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  53119. /**
  53120. * Particle emitter emitting particles from the inside of a sphere.
  53121. * It emits the particles randomly between two vectors.
  53122. */
  53123. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  53124. __extends(SphereDirectedParticleEmitter, _super);
  53125. /**
  53126. * Creates a new instance SphereDirectedParticleEmitter
  53127. * @param radius the radius of the emission sphere (1 by default)
  53128. * @param direction1 the min limit of the emission direction (up vector by default)
  53129. * @param direction2 the max limit of the emission direction (up vector by default)
  53130. */
  53131. function SphereDirectedParticleEmitter(radius,
  53132. /**
  53133. * The min limit of the emission direction.
  53134. */
  53135. direction1,
  53136. /**
  53137. * The max limit of the emission direction.
  53138. */
  53139. direction2) {
  53140. if (radius === void 0) { radius = 1; }
  53141. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  53142. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  53143. var _this = _super.call(this, radius) || this;
  53144. _this.direction1 = direction1;
  53145. _this.direction2 = direction2;
  53146. return _this;
  53147. }
  53148. /**
  53149. * Called by the particle System when the direction is computed for the created particle.
  53150. * @param emitPower is the power of the particle (speed)
  53151. * @param worldMatrix is the world matrix of the particle system
  53152. * @param directionToUpdate is the direction vector to update with the result
  53153. * @param particle is the particle we are computed the direction for
  53154. */
  53155. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  53156. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  53157. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  53158. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  53159. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  53160. };
  53161. /**
  53162. * Clones the current emitter and returns a copy of it
  53163. * @returns the new emitter
  53164. */
  53165. SphereDirectedParticleEmitter.prototype.clone = function () {
  53166. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  53167. BABYLON.Tools.DeepCopy(this, newOne);
  53168. return newOne;
  53169. };
  53170. /**
  53171. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  53172. * @param effect defines the update shader
  53173. */
  53174. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  53175. effect.setFloat("radius", this.radius);
  53176. effect.setVector3("direction1", this.direction1);
  53177. effect.setVector3("direction2", this.direction2);
  53178. };
  53179. /**
  53180. * Returns a string to use to update the GPU particles update shader
  53181. * @returns a string containng the defines string
  53182. */
  53183. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  53184. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  53185. };
  53186. /**
  53187. * Returns the string "SphereDirectedParticleEmitter"
  53188. * @returns a string containing the class name
  53189. */
  53190. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  53191. return "SphereDirectedParticleEmitter";
  53192. };
  53193. /**
  53194. * Serializes the particle system to a JSON object.
  53195. * @returns the JSON object
  53196. */
  53197. SphereDirectedParticleEmitter.prototype.serialize = function () {
  53198. var serializationObject = _super.prototype.serialize.call(this);
  53199. ;
  53200. serializationObject.direction1 = this.direction1.asArray();
  53201. ;
  53202. serializationObject.direction2 = this.direction2.asArray();
  53203. ;
  53204. return serializationObject;
  53205. };
  53206. /**
  53207. * Parse properties from a JSON object
  53208. * @param serializationObject defines the JSON object
  53209. */
  53210. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  53211. _super.prototype.parse.call(this, serializationObject);
  53212. this.direction1.copyFrom(serializationObject.direction1);
  53213. this.direction2.copyFrom(serializationObject.direction2);
  53214. };
  53215. return SphereDirectedParticleEmitter;
  53216. }(SphereParticleEmitter));
  53217. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  53218. })(BABYLON || (BABYLON = {}));
  53219. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  53220. "use strict";
  53221. var __assign = (this && this.__assign) || Object.assign || function(t) {
  53222. for (var s, i = 1, n = arguments.length; i < n; i++) {
  53223. s = arguments[i];
  53224. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  53225. t[p] = s[p];
  53226. }
  53227. return t;
  53228. };
  53229. var BABYLON;
  53230. (function (BABYLON) {
  53231. /**
  53232. * This represents a GPU particle system in Babylon
  53233. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  53234. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  53235. */
  53236. var GPUParticleSystem = /** @class */ (function () {
  53237. /**
  53238. * Instantiates a GPU particle system.
  53239. * 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.
  53240. * @param name The name of the particle system
  53241. * @param capacity The max number of particles alive at the same time
  53242. * @param scene The scene the particle system belongs to
  53243. */
  53244. function GPUParticleSystem(name, options, scene) {
  53245. /**
  53246. * The emitter represents the Mesh or position we are attaching the particle system to.
  53247. */
  53248. this.emitter = null;
  53249. /**
  53250. * The rendering group used by the Particle system to chose when to render.
  53251. */
  53252. this.renderingGroupId = 0;
  53253. /**
  53254. * The layer mask we are rendering the particles through.
  53255. */
  53256. this.layerMask = 0x0FFFFFFF;
  53257. this._targetIndex = 0;
  53258. this._currentRenderId = -1;
  53259. this._started = false;
  53260. this._stopped = false;
  53261. this._timeDelta = 0;
  53262. this._attributesStrideSize = 14;
  53263. this._actualFrame = 0;
  53264. /**
  53265. * List of animations used by the particle system.
  53266. */
  53267. this.animations = [];
  53268. /**
  53269. * An event triggered when the system is disposed.
  53270. */
  53271. this.onDisposeObservable = new BABYLON.Observable();
  53272. /**
  53273. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  53274. */
  53275. this.updateSpeed = 0.01;
  53276. /**
  53277. * The amount of time the particle system is running (depends of the overall update speed).
  53278. */
  53279. this.targetStopDuration = 0;
  53280. /**
  53281. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  53282. */
  53283. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  53284. /**
  53285. * Minimum life time of emitting particles.
  53286. */
  53287. this.minLifeTime = 1;
  53288. /**
  53289. * Maximum life time of emitting particles.
  53290. */
  53291. this.maxLifeTime = 1;
  53292. /**
  53293. * Minimum Size of emitting particles.
  53294. */
  53295. this.minSize = 1;
  53296. /**
  53297. * Maximum Size of emitting particles.
  53298. */
  53299. this.maxSize = 1;
  53300. /**
  53301. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  53302. */
  53303. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53304. /**
  53305. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  53306. */
  53307. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53308. /**
  53309. * Color the particle will have at the end of its lifetime.
  53310. */
  53311. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  53312. /**
  53313. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  53314. */
  53315. this.emitRate = 100;
  53316. /**
  53317. * You can use gravity if you want to give an orientation to your particles.
  53318. */
  53319. this.gravity = BABYLON.Vector3.Zero();
  53320. /**
  53321. * Minimum power of emitting particles.
  53322. */
  53323. this.minEmitPower = 1;
  53324. /**
  53325. * Maximum power of emitting particles.
  53326. */
  53327. this.maxEmitPower = 1;
  53328. /**
  53329. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  53330. * to override the particles.
  53331. */
  53332. this.forceDepthWrite = false;
  53333. this.id = name;
  53334. this.name = name;
  53335. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53336. this._engine = this._scene.getEngine();
  53337. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  53338. this._capacity = fullOptions.capacity;
  53339. this._activeCount = fullOptions.capacity;
  53340. this._currentActiveCount = 0;
  53341. this._scene.particleSystems.push(this);
  53342. this._updateEffectOptions = {
  53343. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  53344. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  53345. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  53346. uniformBuffersNames: [],
  53347. samplers: ["randomSampler"],
  53348. defines: "",
  53349. fallbacks: null,
  53350. onCompiled: null,
  53351. onError: null,
  53352. indexParameters: null,
  53353. maxSimultaneousLights: 0,
  53354. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  53355. };
  53356. // Random data
  53357. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  53358. var d = [];
  53359. for (var i = 0; i < maxTextureSize; ++i) {
  53360. d.push(Math.random());
  53361. d.push(Math.random());
  53362. d.push(Math.random());
  53363. d.push(Math.random());
  53364. }
  53365. this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA32F, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  53366. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  53367. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  53368. this._randomTextureSize = maxTextureSize;
  53369. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  53370. }
  53371. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  53372. /**
  53373. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  53374. */
  53375. get: function () {
  53376. if (!BABYLON.Engine.LastCreatedEngine) {
  53377. return false;
  53378. }
  53379. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  53380. },
  53381. enumerable: true,
  53382. configurable: true
  53383. });
  53384. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  53385. /**
  53386. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  53387. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53388. */
  53389. get: function () {
  53390. if (this.particleEmitterType.direction1) {
  53391. return this.particleEmitterType.direction1;
  53392. }
  53393. return BABYLON.Vector3.Zero();
  53394. },
  53395. set: function (value) {
  53396. if (this.particleEmitterType.direction1) {
  53397. this.particleEmitterType.direction1 = value;
  53398. }
  53399. },
  53400. enumerable: true,
  53401. configurable: true
  53402. });
  53403. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  53404. /**
  53405. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  53406. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53407. */
  53408. get: function () {
  53409. if (this.particleEmitterType.direction2) {
  53410. return this.particleEmitterType.direction2;
  53411. }
  53412. return BABYLON.Vector3.Zero();
  53413. },
  53414. set: function (value) {
  53415. if (this.particleEmitterType.direction2) {
  53416. this.particleEmitterType.direction2 = value;
  53417. }
  53418. },
  53419. enumerable: true,
  53420. configurable: true
  53421. });
  53422. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  53423. /**
  53424. * 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.
  53425. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53426. */
  53427. get: function () {
  53428. if (this.particleEmitterType.minEmitBox) {
  53429. return this.particleEmitterType.minEmitBox;
  53430. }
  53431. return BABYLON.Vector3.Zero();
  53432. },
  53433. set: function (value) {
  53434. if (this.particleEmitterType.minEmitBox) {
  53435. this.particleEmitterType.minEmitBox = value;
  53436. }
  53437. },
  53438. enumerable: true,
  53439. configurable: true
  53440. });
  53441. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  53442. /**
  53443. * 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.
  53444. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53445. */
  53446. get: function () {
  53447. if (this.particleEmitterType.maxEmitBox) {
  53448. return this.particleEmitterType.maxEmitBox;
  53449. }
  53450. return BABYLON.Vector3.Zero();
  53451. },
  53452. set: function (value) {
  53453. if (this.particleEmitterType.maxEmitBox) {
  53454. this.particleEmitterType.maxEmitBox = value;
  53455. }
  53456. },
  53457. enumerable: true,
  53458. configurable: true
  53459. });
  53460. /**
  53461. * Gets the maximum number of particles active at the same time.
  53462. * @returns The max number of active particles.
  53463. */
  53464. GPUParticleSystem.prototype.getCapacity = function () {
  53465. return this._capacity;
  53466. };
  53467. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  53468. /**
  53469. * Gets or set the number of active particles
  53470. */
  53471. get: function () {
  53472. return this._activeCount;
  53473. },
  53474. set: function (value) {
  53475. this._activeCount = Math.min(value, this._capacity);
  53476. },
  53477. enumerable: true,
  53478. configurable: true
  53479. });
  53480. /**
  53481. * Is this system ready to be used/rendered
  53482. * @return true if the system is ready
  53483. */
  53484. GPUParticleSystem.prototype.isReady = function () {
  53485. if (!this._updateEffect) {
  53486. this._recreateUpdateEffect();
  53487. this._recreateRenderEffect();
  53488. return false;
  53489. }
  53490. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  53491. return false;
  53492. }
  53493. return true;
  53494. };
  53495. /**
  53496. * Gets Wether the system has been started.
  53497. * @returns True if it has been started, otherwise false.
  53498. */
  53499. GPUParticleSystem.prototype.isStarted = function () {
  53500. return this._started;
  53501. };
  53502. /**
  53503. * Starts the particle system and begins to emit.
  53504. */
  53505. GPUParticleSystem.prototype.start = function () {
  53506. this._started = true;
  53507. this._stopped = false;
  53508. };
  53509. /**
  53510. * Stops the particle system.
  53511. */
  53512. GPUParticleSystem.prototype.stop = function () {
  53513. this._stopped = true;
  53514. };
  53515. /**
  53516. * Remove all active particles
  53517. */
  53518. GPUParticleSystem.prototype.reset = function () {
  53519. this._releaseBuffers();
  53520. this._releaseVAOs();
  53521. this._currentActiveCount = 0;
  53522. this._targetIndex = 0;
  53523. };
  53524. /**
  53525. * Returns the string "GPUParticleSystem"
  53526. * @returns a string containing the class name
  53527. */
  53528. GPUParticleSystem.prototype.getClassName = function () {
  53529. return "GPUParticleSystem";
  53530. };
  53531. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  53532. var updateVertexBuffers = {};
  53533. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  53534. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  53535. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  53536. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  53537. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  53538. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  53539. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  53540. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  53541. this._engine.bindArrayBuffer(null);
  53542. return vao;
  53543. };
  53544. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  53545. var renderVertexBuffers = {};
  53546. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  53547. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  53548. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  53549. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  53550. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  53551. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  53552. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  53553. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  53554. this._engine.bindArrayBuffer(null);
  53555. return vao;
  53556. };
  53557. GPUParticleSystem.prototype._initialize = function (force) {
  53558. if (force === void 0) { force = false; }
  53559. if (this._buffer0 && !force) {
  53560. return;
  53561. }
  53562. var engine = this._scene.getEngine();
  53563. var data = new Array();
  53564. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  53565. // position
  53566. data.push(0.0);
  53567. data.push(0.0);
  53568. data.push(0.0);
  53569. // Age and life
  53570. data.push(0.0); // create the particle as a dead one to create a new one at start
  53571. data.push(0.0);
  53572. // Seed
  53573. data.push(Math.random());
  53574. // Size
  53575. data.push(0.0);
  53576. // color
  53577. data.push(0.0);
  53578. data.push(0.0);
  53579. data.push(0.0);
  53580. data.push(0.0);
  53581. // direction
  53582. data.push(0.0);
  53583. data.push(0.0);
  53584. data.push(0.0);
  53585. }
  53586. // Sprite data
  53587. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  53588. -0.5, 0.5, 0, 1,
  53589. -0.5, -0.5, 0, 0,
  53590. 0.5, -0.5, 1, 0]);
  53591. // Buffers
  53592. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  53593. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  53594. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  53595. // Update VAO
  53596. this._updateVAO = [];
  53597. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  53598. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  53599. // Render VAO
  53600. this._renderVAO = [];
  53601. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  53602. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  53603. // Links
  53604. this._sourceBuffer = this._buffer0;
  53605. this._targetBuffer = this._buffer1;
  53606. };
  53607. /** @ignore */
  53608. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  53609. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  53610. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  53611. return;
  53612. }
  53613. this._updateEffectOptions.defines = defines;
  53614. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  53615. };
  53616. /** @ignore */
  53617. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  53618. var defines = "";
  53619. if (this._scene.clipPlane) {
  53620. defines = "\n#define CLIPPLANE";
  53621. }
  53622. if (this._renderEffect && this._renderEffect.defines === defines) {
  53623. return;
  53624. }
  53625. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  53626. };
  53627. /**
  53628. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  53629. */
  53630. GPUParticleSystem.prototype.animate = function () {
  53631. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  53632. this._actualFrame += this._timeDelta;
  53633. if (!this._stopped) {
  53634. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  53635. this.stop();
  53636. }
  53637. }
  53638. };
  53639. /**
  53640. * Renders the particle system in its current state.
  53641. * @returns the current number of particles
  53642. */
  53643. GPUParticleSystem.prototype.render = function () {
  53644. if (!this._started) {
  53645. return 0;
  53646. }
  53647. this._recreateUpdateEffect();
  53648. this._recreateRenderEffect();
  53649. if (!this.isReady()) {
  53650. return 0;
  53651. }
  53652. if (this._currentRenderId === this._scene.getRenderId()) {
  53653. return 0;
  53654. }
  53655. this._currentRenderId = this._scene.getRenderId();
  53656. // Get everything ready to render
  53657. this._initialize();
  53658. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  53659. // Enable update effect
  53660. this._engine.enableEffect(this._updateEffect);
  53661. this._engine.setState(false);
  53662. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  53663. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  53664. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  53665. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  53666. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  53667. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  53668. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  53669. this._updateEffect.setDirectColor4("color1", this.color1);
  53670. this._updateEffect.setDirectColor4("color2", this.color2);
  53671. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  53672. this._updateEffect.setVector3("gravity", this.gravity);
  53673. if (this.particleEmitterType) {
  53674. this.particleEmitterType.applyToShader(this._updateEffect);
  53675. }
  53676. var emitterWM;
  53677. if (this.emitter.position) {
  53678. var emitterMesh = this.emitter;
  53679. emitterWM = emitterMesh.getWorldMatrix();
  53680. }
  53681. else {
  53682. var emitterPosition = this.emitter;
  53683. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  53684. }
  53685. this._updateEffect.setMatrix("emitterWM", emitterWM);
  53686. // Bind source VAO
  53687. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  53688. // Update
  53689. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  53690. this._engine.setRasterizerState(false);
  53691. this._engine.beginTransformFeedback();
  53692. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  53693. this._engine.endTransformFeedback();
  53694. this._engine.setRasterizerState(true);
  53695. this._engine.bindTransformFeedbackBuffer(null);
  53696. // Enable render effect
  53697. this._engine.enableEffect(this._renderEffect);
  53698. var viewMatrix = this._scene.getViewMatrix();
  53699. this._renderEffect.setMatrix("view", viewMatrix);
  53700. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  53701. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  53702. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  53703. if (this._scene.clipPlane) {
  53704. var clipPlane = this._scene.clipPlane;
  53705. var invView = viewMatrix.clone();
  53706. invView.invert();
  53707. this._renderEffect.setMatrix("invView", invView);
  53708. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  53709. }
  53710. // Draw order
  53711. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  53712. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  53713. }
  53714. else {
  53715. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53716. }
  53717. if (this.forceDepthWrite) {
  53718. this._engine.setDepthWrite(true);
  53719. }
  53720. // Bind source VAO
  53721. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  53722. // Render
  53723. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  53724. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53725. // Switch VAOs
  53726. this._targetIndex++;
  53727. if (this._targetIndex === 2) {
  53728. this._targetIndex = 0;
  53729. }
  53730. // Switch buffers
  53731. var tmpBuffer = this._sourceBuffer;
  53732. this._sourceBuffer = this._targetBuffer;
  53733. this._targetBuffer = tmpBuffer;
  53734. return this._currentActiveCount;
  53735. };
  53736. /**
  53737. * Rebuilds the particle system
  53738. */
  53739. GPUParticleSystem.prototype.rebuild = function () {
  53740. this._initialize(true);
  53741. };
  53742. GPUParticleSystem.prototype._releaseBuffers = function () {
  53743. if (this._buffer0) {
  53744. this._buffer0.dispose();
  53745. this._buffer0 = null;
  53746. }
  53747. if (this._buffer1) {
  53748. this._buffer1.dispose();
  53749. this._buffer1 = null;
  53750. }
  53751. if (this._spriteBuffer) {
  53752. this._spriteBuffer.dispose();
  53753. this._spriteBuffer = null;
  53754. }
  53755. };
  53756. GPUParticleSystem.prototype._releaseVAOs = function () {
  53757. if (!this._updateVAO) {
  53758. return;
  53759. }
  53760. for (var index = 0; index < this._updateVAO.length; index++) {
  53761. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  53762. }
  53763. this._updateVAO = [];
  53764. for (var index = 0; index < this._renderVAO.length; index++) {
  53765. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  53766. }
  53767. this._renderVAO = [];
  53768. };
  53769. /**
  53770. * Disposes the particle system and free the associated resources
  53771. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  53772. */
  53773. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  53774. if (disposeTexture === void 0) { disposeTexture = true; }
  53775. var index = this._scene.particleSystems.indexOf(this);
  53776. if (index > -1) {
  53777. this._scene.particleSystems.splice(index, 1);
  53778. }
  53779. this._releaseBuffers();
  53780. this._releaseVAOs();
  53781. if (this._randomTexture) {
  53782. this._randomTexture.dispose();
  53783. this._randomTexture = null;
  53784. }
  53785. if (disposeTexture && this.particleTexture) {
  53786. this.particleTexture.dispose();
  53787. this.particleTexture = null;
  53788. }
  53789. // Callback
  53790. this.onDisposeObservable.notifyObservers(this);
  53791. this.onDisposeObservable.clear();
  53792. };
  53793. /**
  53794. * Clones the particle system.
  53795. * @param name The name of the cloned object
  53796. * @param newEmitter The new emitter to use
  53797. * @returns the cloned particle system
  53798. */
  53799. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  53800. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  53801. BABYLON.Tools.DeepCopy(this, result);
  53802. if (newEmitter === undefined) {
  53803. newEmitter = this.emitter;
  53804. }
  53805. result.emitter = newEmitter;
  53806. if (this.particleTexture) {
  53807. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  53808. }
  53809. return result;
  53810. };
  53811. /**
  53812. * Serializes the particle system to a JSON object.
  53813. * @returns the JSON object
  53814. */
  53815. GPUParticleSystem.prototype.serialize = function () {
  53816. var serializationObject = {};
  53817. serializationObject.name = this.name;
  53818. serializationObject.id = this.id;
  53819. // Emitter
  53820. if (this.emitter.position) {
  53821. var emitterMesh = this.emitter;
  53822. serializationObject.emitterId = emitterMesh.id;
  53823. }
  53824. else {
  53825. var emitterPosition = this.emitter;
  53826. serializationObject.emitter = emitterPosition.asArray();
  53827. }
  53828. serializationObject.capacity = this.getCapacity();
  53829. if (this.particleTexture) {
  53830. serializationObject.textureName = this.particleTexture.name;
  53831. }
  53832. // Animations
  53833. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  53834. // Particle system
  53835. serializationObject.activeParticleCount = this.activeParticleCount;
  53836. serializationObject.randomTextureSize = this._randomTextureSize;
  53837. serializationObject.minSize = this.minSize;
  53838. serializationObject.maxSize = this.maxSize;
  53839. serializationObject.minEmitPower = this.minEmitPower;
  53840. serializationObject.maxEmitPower = this.maxEmitPower;
  53841. serializationObject.minLifeTime = this.minLifeTime;
  53842. serializationObject.maxLifeTime = this.maxLifeTime;
  53843. serializationObject.emitRate = this.emitRate;
  53844. serializationObject.gravity = this.gravity.asArray();
  53845. serializationObject.color1 = this.color1.asArray();
  53846. serializationObject.color2 = this.color2.asArray();
  53847. serializationObject.colorDead = this.colorDead.asArray();
  53848. serializationObject.updateSpeed = this.updateSpeed;
  53849. serializationObject.targetStopDuration = this.targetStopDuration;
  53850. serializationObject.blendMode = this.blendMode;
  53851. // Emitter
  53852. if (this.particleEmitterType) {
  53853. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  53854. }
  53855. return serializationObject;
  53856. };
  53857. /**
  53858. * Parses a JSON object to create a GPU particle system.
  53859. * @param parsedParticleSystem The JSON object to parse
  53860. * @param scene The scene to create the particle system in
  53861. * @param rootUrl The root url to use to load external dependencies like texture
  53862. * @returns the parsed GPU particle system
  53863. */
  53864. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  53865. var name = parsedParticleSystem.name;
  53866. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  53867. if (parsedParticleSystem.id) {
  53868. particleSystem.id = parsedParticleSystem.id;
  53869. }
  53870. // Texture
  53871. if (parsedParticleSystem.textureName) {
  53872. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  53873. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  53874. }
  53875. // Emitter
  53876. if (parsedParticleSystem.emitterId) {
  53877. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  53878. }
  53879. else {
  53880. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  53881. }
  53882. // Animations
  53883. if (parsedParticleSystem.animations) {
  53884. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  53885. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  53886. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  53887. }
  53888. }
  53889. // Particle system
  53890. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  53891. particleSystem.minSize = parsedParticleSystem.minSize;
  53892. particleSystem.maxSize = parsedParticleSystem.maxSize;
  53893. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  53894. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  53895. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  53896. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  53897. particleSystem.emitRate = parsedParticleSystem.emitRate;
  53898. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  53899. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  53900. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  53901. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  53902. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  53903. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  53904. particleSystem.blendMode = parsedParticleSystem.blendMode;
  53905. // Emitter
  53906. if (parsedParticleSystem.particleEmitterType) {
  53907. var emitterType = void 0;
  53908. switch (parsedParticleSystem.particleEmitterType.type) {
  53909. case "SphereEmitter":
  53910. emitterType = new BABYLON.SphereParticleEmitter();
  53911. break;
  53912. case "SphereDirectedParticleEmitter":
  53913. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  53914. break;
  53915. case "ConeEmitter":
  53916. emitterType = new BABYLON.ConeParticleEmitter();
  53917. break;
  53918. case "BoxEmitter":
  53919. default:
  53920. emitterType = new BABYLON.BoxParticleEmitter();
  53921. break;
  53922. }
  53923. emitterType.parse(parsedParticleSystem.particleEmitterType);
  53924. particleSystem.particleEmitterType = emitterType;
  53925. }
  53926. return particleSystem;
  53927. };
  53928. return GPUParticleSystem;
  53929. }());
  53930. BABYLON.GPUParticleSystem = GPUParticleSystem;
  53931. })(BABYLON || (BABYLON = {}));
  53932. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  53933. "use strict";
  53934. var BABYLON;
  53935. (function (BABYLON) {
  53936. /**
  53937. * Represents one particle of a solid particle system.
  53938. */
  53939. var SolidParticle = /** @class */ (function () {
  53940. /**
  53941. * Creates a Solid Particle object.
  53942. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  53943. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  53944. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  53945. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  53946. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  53947. * @param shapeId (integer) is the model shape identifier in the SPS.
  53948. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  53949. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  53950. */
  53951. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  53952. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  53953. /**
  53954. * particle global index
  53955. */
  53956. this.idx = 0;
  53957. /**
  53958. * The color of the particle
  53959. */
  53960. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53961. /**
  53962. * The world space position of the particle.
  53963. */
  53964. this.position = BABYLON.Vector3.Zero();
  53965. /**
  53966. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  53967. */
  53968. this.rotation = BABYLON.Vector3.Zero();
  53969. /**
  53970. * The scaling of the particle.
  53971. */
  53972. this.scaling = BABYLON.Vector3.One();
  53973. /**
  53974. * The uvs of the particle.
  53975. */
  53976. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  53977. /**
  53978. * The current speed of the particle.
  53979. */
  53980. this.velocity = BABYLON.Vector3.Zero();
  53981. /**
  53982. * The pivot point in the particle local space.
  53983. */
  53984. this.pivot = BABYLON.Vector3.Zero();
  53985. /**
  53986. * Must the particle be translated from its pivot point in its local space ?
  53987. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  53988. * Default : false
  53989. */
  53990. this.translateFromPivot = false;
  53991. /**
  53992. * Is the particle active or not ?
  53993. */
  53994. this.alive = true;
  53995. /**
  53996. * Is the particle visible or not ?
  53997. */
  53998. this.isVisible = true;
  53999. /**
  54000. * Index of this particle in the global "positions" array (Internal use)
  54001. */
  54002. this._pos = 0;
  54003. /**
  54004. * Index of this particle in the global "indices" array (Internal use)
  54005. */
  54006. this._ind = 0;
  54007. /**
  54008. * ModelShape id of this particle
  54009. */
  54010. this.shapeId = 0;
  54011. /**
  54012. * Index of the particle in its shape id (Internal use)
  54013. */
  54014. this.idxInShape = 0;
  54015. /**
  54016. * Still set as invisible in order to skip useless computations (Internal use)
  54017. */
  54018. this._stillInvisible = false;
  54019. /**
  54020. * Last computed particle rotation matrix
  54021. */
  54022. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  54023. /**
  54024. * Parent particle Id, if any.
  54025. * Default null.
  54026. */
  54027. this.parentId = null;
  54028. /**
  54029. * Internal global position in the SPS.
  54030. */
  54031. this._globalPosition = BABYLON.Vector3.Zero();
  54032. this.idx = particleIndex;
  54033. this._pos = positionIndex;
  54034. this._ind = indiceIndex;
  54035. this._model = model;
  54036. this.shapeId = shapeId;
  54037. this.idxInShape = idxInShape;
  54038. this._sps = sps;
  54039. if (modelBoundingInfo) {
  54040. this._modelBoundingInfo = modelBoundingInfo;
  54041. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  54042. }
  54043. }
  54044. Object.defineProperty(SolidParticle.prototype, "scale", {
  54045. /**
  54046. * Legacy support, changed scale to scaling
  54047. */
  54048. get: function () {
  54049. return this.scaling;
  54050. },
  54051. /**
  54052. * Legacy support, changed scale to scaling
  54053. */
  54054. set: function (scale) {
  54055. this.scaling = scale;
  54056. },
  54057. enumerable: true,
  54058. configurable: true
  54059. });
  54060. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  54061. /**
  54062. * Legacy support, changed quaternion to rotationQuaternion
  54063. */
  54064. get: function () {
  54065. return this.rotationQuaternion;
  54066. },
  54067. /**
  54068. * Legacy support, changed quaternion to rotationQuaternion
  54069. */
  54070. set: function (q) {
  54071. this.rotationQuaternion = q;
  54072. },
  54073. enumerable: true,
  54074. configurable: true
  54075. });
  54076. /**
  54077. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  54078. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  54079. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  54080. * @returns true if it intersects
  54081. */
  54082. SolidParticle.prototype.intersectsMesh = function (target) {
  54083. if (!this._boundingInfo || !target._boundingInfo) {
  54084. return false;
  54085. }
  54086. if (this._sps._bSphereOnly) {
  54087. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  54088. }
  54089. return this._boundingInfo.intersects(target._boundingInfo, false);
  54090. };
  54091. return SolidParticle;
  54092. }());
  54093. BABYLON.SolidParticle = SolidParticle;
  54094. /**
  54095. * Represents the shape of the model used by one particle of a solid particle system.
  54096. * SPS internal tool, don't use it manually.
  54097. */
  54098. var ModelShape = /** @class */ (function () {
  54099. /**
  54100. * 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.
  54101. * SPS internal tool, don't use it manually.
  54102. * @ignore
  54103. */
  54104. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  54105. /**
  54106. * length of the shape in the model indices array (internal use)
  54107. */
  54108. this._indicesLength = 0;
  54109. this.shapeID = id;
  54110. this._shape = shape;
  54111. this._indicesLength = indicesLength;
  54112. this._shapeUV = shapeUV;
  54113. this._positionFunction = posFunction;
  54114. this._vertexFunction = vtxFunction;
  54115. }
  54116. return ModelShape;
  54117. }());
  54118. BABYLON.ModelShape = ModelShape;
  54119. /**
  54120. * Represents a Depth Sorted Particle in the solid particle system.
  54121. */
  54122. var DepthSortedParticle = /** @class */ (function () {
  54123. function DepthSortedParticle() {
  54124. /**
  54125. * Index of the particle in the "indices" array
  54126. */
  54127. this.ind = 0;
  54128. /**
  54129. * Length of the particle shape in the "indices" array
  54130. */
  54131. this.indicesLength = 0;
  54132. /**
  54133. * Squared distance from the particle to the camera
  54134. */
  54135. this.sqDistance = 0.0;
  54136. }
  54137. return DepthSortedParticle;
  54138. }());
  54139. BABYLON.DepthSortedParticle = DepthSortedParticle;
  54140. })(BABYLON || (BABYLON = {}));
  54141. //# sourceMappingURL=babylon.solidParticle.js.map
  54142. "use strict";
  54143. var BABYLON;
  54144. (function (BABYLON) {
  54145. /**
  54146. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  54147. *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.
  54148. * The SPS is also a particle system. It provides some methods to manage the particles.
  54149. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  54150. *
  54151. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  54152. */
  54153. var SolidParticleSystem = /** @class */ (function () {
  54154. /**
  54155. * Creates a SPS (Solid Particle System) object.
  54156. * @param name (String) is the SPS name, this will be the underlying mesh name.
  54157. * @param scene (Scene) is the scene in which the SPS is added.
  54158. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  54159. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  54160. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  54161. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  54162. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  54163. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  54164. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  54165. */
  54166. function SolidParticleSystem(name, scene, options) {
  54167. /**
  54168. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  54169. * Example : var p = SPS.particles[i];
  54170. */
  54171. this.particles = new Array();
  54172. /**
  54173. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  54174. */
  54175. this.nbParticles = 0;
  54176. /**
  54177. * If the particles must ever face the camera (default false). Useful for planar particles.
  54178. */
  54179. this.billboard = false;
  54180. /**
  54181. * Recompute normals when adding a shape
  54182. */
  54183. this.recomputeNormals = true;
  54184. /**
  54185. * This a counter ofr your own usage. It's not set by any SPS functions.
  54186. */
  54187. this.counter = 0;
  54188. /**
  54189. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  54190. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  54191. */
  54192. this.vars = {};
  54193. /**
  54194. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  54195. */
  54196. this._bSphereOnly = false;
  54197. /**
  54198. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  54199. */
  54200. this._bSphereRadiusFactor = 1.0;
  54201. this._positions = new Array();
  54202. this._indices = new Array();
  54203. this._normals = new Array();
  54204. this._colors = new Array();
  54205. this._uvs = new Array();
  54206. this._index = 0; // indices index
  54207. this._updatable = true;
  54208. this._pickable = false;
  54209. this._isVisibilityBoxLocked = false;
  54210. this._alwaysVisible = false;
  54211. this._depthSort = false;
  54212. this._shapeCounter = 0;
  54213. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  54214. this._color = new BABYLON.Color4(0, 0, 0, 0);
  54215. this._computeParticleColor = true;
  54216. this._computeParticleTexture = true;
  54217. this._computeParticleRotation = true;
  54218. this._computeParticleVertex = false;
  54219. this._computeBoundingBox = false;
  54220. this._depthSortParticles = true;
  54221. this._cam_axisZ = BABYLON.Vector3.Zero();
  54222. this._cam_axisY = BABYLON.Vector3.Zero();
  54223. this._cam_axisX = BABYLON.Vector3.Zero();
  54224. this._axisZ = BABYLON.Axis.Z;
  54225. this._camDir = BABYLON.Vector3.Zero();
  54226. this._camInvertedPosition = BABYLON.Vector3.Zero();
  54227. this._rotMatrix = new BABYLON.Matrix();
  54228. this._invertMatrix = new BABYLON.Matrix();
  54229. this._rotated = BABYLON.Vector3.Zero();
  54230. this._quaternion = new BABYLON.Quaternion();
  54231. this._vertex = BABYLON.Vector3.Zero();
  54232. this._normal = BABYLON.Vector3.Zero();
  54233. this._yaw = 0.0;
  54234. this._pitch = 0.0;
  54235. this._roll = 0.0;
  54236. this._halfroll = 0.0;
  54237. this._halfpitch = 0.0;
  54238. this._halfyaw = 0.0;
  54239. this._sinRoll = 0.0;
  54240. this._cosRoll = 0.0;
  54241. this._sinPitch = 0.0;
  54242. this._cosPitch = 0.0;
  54243. this._sinYaw = 0.0;
  54244. this._cosYaw = 0.0;
  54245. this._mustUnrotateFixedNormals = false;
  54246. this._minimum = BABYLON.Vector3.Zero();
  54247. this._maximum = BABYLON.Vector3.Zero();
  54248. this._minBbox = BABYLON.Vector3.Zero();
  54249. this._maxBbox = BABYLON.Vector3.Zero();
  54250. this._particlesIntersect = false;
  54251. this._depthSortFunction = function (p1, p2) {
  54252. return (p2.sqDistance - p1.sqDistance);
  54253. };
  54254. this._needs32Bits = false;
  54255. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  54256. this._scaledPivot = BABYLON.Vector3.Zero();
  54257. this._particleHasParent = false;
  54258. this.name = name;
  54259. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  54260. this._camera = scene.activeCamera;
  54261. this._pickable = options ? options.isPickable : false;
  54262. this._depthSort = options ? options.enableDepthSort : false;
  54263. this._particlesIntersect = options ? options.particleIntersection : false;
  54264. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  54265. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  54266. if (options && options.updatable) {
  54267. this._updatable = options.updatable;
  54268. }
  54269. else {
  54270. this._updatable = true;
  54271. }
  54272. if (this._pickable) {
  54273. this.pickedParticles = [];
  54274. }
  54275. if (this._depthSort) {
  54276. this.depthSortedParticles = [];
  54277. }
  54278. }
  54279. /**
  54280. * Builds the SPS underlying mesh. Returns a standard Mesh.
  54281. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  54282. * @returns the created mesh
  54283. */
  54284. SolidParticleSystem.prototype.buildMesh = function () {
  54285. if (this.nbParticles === 0) {
  54286. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  54287. this.addShape(triangle, 1);
  54288. triangle.dispose();
  54289. }
  54290. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  54291. this._positions32 = new Float32Array(this._positions);
  54292. this._uvs32 = new Float32Array(this._uvs);
  54293. this._colors32 = new Float32Array(this._colors);
  54294. if (this.recomputeNormals) {
  54295. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  54296. }
  54297. this._normals32 = new Float32Array(this._normals);
  54298. this._fixedNormal32 = new Float32Array(this._normals);
  54299. if (this._mustUnrotateFixedNormals) {
  54300. this._unrotateFixedNormals();
  54301. }
  54302. var vertexData = new BABYLON.VertexData();
  54303. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  54304. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  54305. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  54306. if (this._uvs32) {
  54307. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  54308. ;
  54309. }
  54310. if (this._colors32) {
  54311. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  54312. }
  54313. var mesh = new BABYLON.Mesh(this.name, this._scene);
  54314. vertexData.applyToMesh(mesh, this._updatable);
  54315. this.mesh = mesh;
  54316. this.mesh.isPickable = this._pickable;
  54317. // free memory
  54318. if (!this._depthSort) {
  54319. this._indices = null;
  54320. }
  54321. this._positions = null;
  54322. this._normals = null;
  54323. this._uvs = null;
  54324. this._colors = null;
  54325. if (!this._updatable) {
  54326. this.particles.length = 0;
  54327. }
  54328. return mesh;
  54329. };
  54330. /**
  54331. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  54332. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  54333. * Thus the particles generated from `digest()` have their property `position` set yet.
  54334. * @param mesh ( Mesh ) is the mesh to be digested
  54335. * @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
  54336. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  54337. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  54338. * @returns the current SPS
  54339. */
  54340. SolidParticleSystem.prototype.digest = function (mesh, options) {
  54341. var size = (options && options.facetNb) || 1;
  54342. var number = (options && options.number) || 0;
  54343. var delta = (options && options.delta) || 0;
  54344. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54345. var meshInd = mesh.getIndices();
  54346. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54347. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54348. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54349. var f = 0; // facet counter
  54350. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  54351. // compute size from number
  54352. if (number) {
  54353. number = (number > totalFacets) ? totalFacets : number;
  54354. size = Math.round(totalFacets / number);
  54355. delta = 0;
  54356. }
  54357. else {
  54358. size = (size > totalFacets) ? totalFacets : size;
  54359. }
  54360. var facetPos = []; // submesh positions
  54361. var facetInd = []; // submesh indices
  54362. var facetUV = []; // submesh UV
  54363. var facetCol = []; // submesh colors
  54364. var barycenter = BABYLON.Vector3.Zero();
  54365. var sizeO = size;
  54366. while (f < totalFacets) {
  54367. size = sizeO + Math.floor((1 + delta) * Math.random());
  54368. if (f > totalFacets - size) {
  54369. size = totalFacets - f;
  54370. }
  54371. // reset temp arrays
  54372. facetPos.length = 0;
  54373. facetInd.length = 0;
  54374. facetUV.length = 0;
  54375. facetCol.length = 0;
  54376. // iterate over "size" facets
  54377. var fi = 0;
  54378. for (var j = f * 3; j < (f + size) * 3; j++) {
  54379. facetInd.push(fi);
  54380. var i = meshInd[j];
  54381. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  54382. if (meshUV) {
  54383. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  54384. }
  54385. if (meshCol) {
  54386. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  54387. }
  54388. fi++;
  54389. }
  54390. // create a model shape for each single particle
  54391. var idx = this.nbParticles;
  54392. var shape = this._posToShape(facetPos);
  54393. var shapeUV = this._uvsToShapeUV(facetUV);
  54394. // compute the barycenter of the shape
  54395. var v;
  54396. for (v = 0; v < shape.length; v++) {
  54397. barycenter.addInPlace(shape[v]);
  54398. }
  54399. barycenter.scaleInPlace(1 / shape.length);
  54400. // shift the shape from its barycenter to the origin
  54401. for (v = 0; v < shape.length; v++) {
  54402. shape[v].subtractInPlace(barycenter);
  54403. }
  54404. var bInfo;
  54405. if (this._particlesIntersect) {
  54406. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  54407. }
  54408. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  54409. // add the particle in the SPS
  54410. var currentPos = this._positions.length;
  54411. var currentInd = this._indices.length;
  54412. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  54413. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  54414. // initialize the particle position
  54415. this.particles[this.nbParticles].position.addInPlace(barycenter);
  54416. this._index += shape.length;
  54417. idx++;
  54418. this.nbParticles++;
  54419. this._shapeCounter++;
  54420. f += size;
  54421. }
  54422. return this;
  54423. };
  54424. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  54425. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  54426. var index = 0;
  54427. var idx = 0;
  54428. for (var p = 0; p < this.particles.length; p++) {
  54429. this._particle = this.particles[p];
  54430. this._shape = this._particle._model._shape;
  54431. if (this._particle.rotationQuaternion) {
  54432. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  54433. }
  54434. else {
  54435. this._yaw = this._particle.rotation.y;
  54436. this._pitch = this._particle.rotation.x;
  54437. this._roll = this._particle.rotation.z;
  54438. this._quaternionRotationYPR();
  54439. }
  54440. this._quaternionToRotationMatrix();
  54441. this._rotMatrix.invertToRef(this._invertMatrix);
  54442. for (var pt = 0; pt < this._shape.length; pt++) {
  54443. idx = index + pt * 3;
  54444. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  54445. this._fixedNormal32[idx] = this._normal.x;
  54446. this._fixedNormal32[idx + 1] = this._normal.y;
  54447. this._fixedNormal32[idx + 2] = this._normal.z;
  54448. }
  54449. index = idx + 3;
  54450. }
  54451. };
  54452. //reset copy
  54453. SolidParticleSystem.prototype._resetCopy = function () {
  54454. this._copy.position.x = 0;
  54455. this._copy.position.y = 0;
  54456. this._copy.position.z = 0;
  54457. this._copy.rotation.x = 0;
  54458. this._copy.rotation.y = 0;
  54459. this._copy.rotation.z = 0;
  54460. this._copy.rotationQuaternion = null;
  54461. this._copy.scaling.x = 1.0;
  54462. this._copy.scaling.y = 1.0;
  54463. this._copy.scaling.z = 1.0;
  54464. this._copy.uvs.x = 0;
  54465. this._copy.uvs.y = 0;
  54466. this._copy.uvs.z = 1.0;
  54467. this._copy.uvs.w = 1.0;
  54468. this._copy.color = null;
  54469. this._copy.translateFromPivot = false;
  54470. };
  54471. // _meshBuilder : inserts the shape model in the global SPS mesh
  54472. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  54473. var i;
  54474. var u = 0;
  54475. var c = 0;
  54476. var n = 0;
  54477. this._resetCopy();
  54478. if (options && options.positionFunction) {
  54479. options.positionFunction(this._copy, idx, idxInShape);
  54480. this._mustUnrotateFixedNormals = true;
  54481. }
  54482. if (this._copy.rotationQuaternion) {
  54483. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  54484. }
  54485. else {
  54486. this._yaw = this._copy.rotation.y;
  54487. this._pitch = this._copy.rotation.x;
  54488. this._roll = this._copy.rotation.z;
  54489. this._quaternionRotationYPR();
  54490. }
  54491. this._quaternionToRotationMatrix();
  54492. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  54493. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  54494. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  54495. if (this._copy.translateFromPivot) {
  54496. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  54497. }
  54498. else {
  54499. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  54500. }
  54501. for (i = 0; i < shape.length; i++) {
  54502. this._vertex.x = shape[i].x;
  54503. this._vertex.y = shape[i].y;
  54504. this._vertex.z = shape[i].z;
  54505. if (options && options.vertexFunction) {
  54506. options.vertexFunction(this._copy, this._vertex, i);
  54507. }
  54508. this._vertex.x *= this._copy.scaling.x;
  54509. this._vertex.y *= this._copy.scaling.y;
  54510. this._vertex.z *= this._copy.scaling.z;
  54511. this._vertex.x -= this._scaledPivot.x;
  54512. this._vertex.y -= this._scaledPivot.y;
  54513. this._vertex.z -= this._scaledPivot.z;
  54514. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  54515. this._rotated.addInPlace(this._pivotBackTranslation);
  54516. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  54517. if (meshUV) {
  54518. 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);
  54519. u += 2;
  54520. }
  54521. if (this._copy.color) {
  54522. this._color = this._copy.color;
  54523. }
  54524. else if (meshCol && meshCol[c] !== undefined) {
  54525. this._color.r = meshCol[c];
  54526. this._color.g = meshCol[c + 1];
  54527. this._color.b = meshCol[c + 2];
  54528. this._color.a = meshCol[c + 3];
  54529. }
  54530. else {
  54531. this._color.r = 1.0;
  54532. this._color.g = 1.0;
  54533. this._color.b = 1.0;
  54534. this._color.a = 1.0;
  54535. }
  54536. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  54537. c += 4;
  54538. if (!this.recomputeNormals && meshNor) {
  54539. this._normal.x = meshNor[n];
  54540. this._normal.y = meshNor[n + 1];
  54541. this._normal.z = meshNor[n + 2];
  54542. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  54543. normals.push(this._normal.x, this._normal.y, this._normal.z);
  54544. n += 3;
  54545. }
  54546. }
  54547. for (i = 0; i < meshInd.length; i++) {
  54548. var current_ind = p + meshInd[i];
  54549. indices.push(current_ind);
  54550. if (current_ind > 65535) {
  54551. this._needs32Bits = true;
  54552. }
  54553. }
  54554. if (this._pickable) {
  54555. var nbfaces = meshInd.length / 3;
  54556. for (i = 0; i < nbfaces; i++) {
  54557. this.pickedParticles.push({ idx: idx, faceId: i });
  54558. }
  54559. }
  54560. if (this._depthSort) {
  54561. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  54562. }
  54563. return this._copy;
  54564. };
  54565. // returns a shape array from positions array
  54566. SolidParticleSystem.prototype._posToShape = function (positions) {
  54567. var shape = [];
  54568. for (var i = 0; i < positions.length; i += 3) {
  54569. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  54570. }
  54571. return shape;
  54572. };
  54573. // returns a shapeUV array from a Vector4 uvs
  54574. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  54575. var shapeUV = [];
  54576. if (uvs) {
  54577. for (var i = 0; i < uvs.length; i++)
  54578. shapeUV.push(uvs[i]);
  54579. }
  54580. return shapeUV;
  54581. };
  54582. // adds a new particle object in the particles array
  54583. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  54584. if (bInfo === void 0) { bInfo = null; }
  54585. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  54586. this.particles.push(sp);
  54587. return sp;
  54588. };
  54589. /**
  54590. * Adds some particles to the SPS from the model shape. Returns the shape id.
  54591. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  54592. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  54593. * @param nb (positive integer) the number of particles to be created from this model
  54594. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  54595. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  54596. * @returns the number of shapes in the system
  54597. */
  54598. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  54599. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54600. var meshInd = mesh.getIndices();
  54601. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54602. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54603. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54604. var bbInfo;
  54605. if (this._particlesIntersect) {
  54606. bbInfo = mesh.getBoundingInfo();
  54607. }
  54608. var shape = this._posToShape(meshPos);
  54609. var shapeUV = this._uvsToShapeUV(meshUV);
  54610. var posfunc = options ? options.positionFunction : null;
  54611. var vtxfunc = options ? options.vertexFunction : null;
  54612. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  54613. // particles
  54614. var sp;
  54615. var currentCopy;
  54616. var idx = this.nbParticles;
  54617. for (var i = 0; i < nb; i++) {
  54618. var currentPos = this._positions.length;
  54619. var currentInd = this._indices.length;
  54620. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  54621. if (this._updatable) {
  54622. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  54623. sp.position.copyFrom(currentCopy.position);
  54624. sp.rotation.copyFrom(currentCopy.rotation);
  54625. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  54626. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  54627. }
  54628. if (currentCopy.color && sp.color) {
  54629. sp.color.copyFrom(currentCopy.color);
  54630. }
  54631. sp.scaling.copyFrom(currentCopy.scaling);
  54632. sp.uvs.copyFrom(currentCopy.uvs);
  54633. }
  54634. this._index += shape.length;
  54635. idx++;
  54636. }
  54637. this.nbParticles += nb;
  54638. this._shapeCounter++;
  54639. return this._shapeCounter - 1;
  54640. };
  54641. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  54642. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  54643. this._resetCopy();
  54644. if (particle._model._positionFunction) {
  54645. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  54646. }
  54647. if (this._copy.rotationQuaternion) {
  54648. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  54649. }
  54650. else {
  54651. this._yaw = this._copy.rotation.y;
  54652. this._pitch = this._copy.rotation.x;
  54653. this._roll = this._copy.rotation.z;
  54654. this._quaternionRotationYPR();
  54655. }
  54656. this._quaternionToRotationMatrix();
  54657. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  54658. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  54659. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  54660. if (this._copy.translateFromPivot) {
  54661. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  54662. }
  54663. else {
  54664. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  54665. }
  54666. this._shape = particle._model._shape;
  54667. for (var pt = 0; pt < this._shape.length; pt++) {
  54668. this._vertex.x = this._shape[pt].x;
  54669. this._vertex.y = this._shape[pt].y;
  54670. this._vertex.z = this._shape[pt].z;
  54671. if (particle._model._vertexFunction) {
  54672. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  54673. }
  54674. this._vertex.x *= this._copy.scaling.x;
  54675. this._vertex.y *= this._copy.scaling.y;
  54676. this._vertex.z *= this._copy.scaling.z;
  54677. this._vertex.x -= this._scaledPivot.x;
  54678. this._vertex.y -= this._scaledPivot.y;
  54679. this._vertex.z -= this._scaledPivot.z;
  54680. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  54681. this._rotated.addInPlace(this._pivotBackTranslation);
  54682. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  54683. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  54684. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  54685. }
  54686. particle.position.x = 0.0;
  54687. particle.position.y = 0.0;
  54688. particle.position.z = 0.0;
  54689. particle.rotation.x = 0.0;
  54690. particle.rotation.y = 0.0;
  54691. particle.rotation.z = 0.0;
  54692. particle.rotationQuaternion = null;
  54693. particle.scaling.x = 1.0;
  54694. particle.scaling.y = 1.0;
  54695. particle.scaling.z = 1.0;
  54696. particle.uvs.x = 0.0;
  54697. particle.uvs.y = 0.0;
  54698. particle.uvs.z = 1.0;
  54699. particle.uvs.w = 1.0;
  54700. particle.pivot.x = 0.0;
  54701. particle.pivot.y = 0.0;
  54702. particle.pivot.z = 0.0;
  54703. particle.translateFromPivot = false;
  54704. particle.parentId = null;
  54705. };
  54706. /**
  54707. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  54708. * @returns the SPS.
  54709. */
  54710. SolidParticleSystem.prototype.rebuildMesh = function () {
  54711. for (var p = 0; p < this.particles.length; p++) {
  54712. this._rebuildParticle(this.particles[p]);
  54713. }
  54714. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54715. return this;
  54716. };
  54717. /**
  54718. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  54719. * This method calls `updateParticle()` for each particle of the SPS.
  54720. * For an animated SPS, it is usually called within the render loop.
  54721. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  54722. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  54723. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  54724. * @returns the SPS.
  54725. */
  54726. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  54727. if (start === void 0) { start = 0; }
  54728. if (end === void 0) { end = this.nbParticles - 1; }
  54729. if (update === void 0) { update = true; }
  54730. if (!this._updatable) {
  54731. return this;
  54732. }
  54733. // custom beforeUpdate
  54734. this.beforeUpdateParticles(start, end, update);
  54735. this._cam_axisX.x = 1.0;
  54736. this._cam_axisX.y = 0.0;
  54737. this._cam_axisX.z = 0.0;
  54738. this._cam_axisY.x = 0.0;
  54739. this._cam_axisY.y = 1.0;
  54740. this._cam_axisY.z = 0.0;
  54741. this._cam_axisZ.x = 0.0;
  54742. this._cam_axisZ.y = 0.0;
  54743. this._cam_axisZ.z = 1.0;
  54744. // cases when the World Matrix is to be computed first
  54745. if (this.billboard || this._depthSort) {
  54746. this.mesh.computeWorldMatrix(true);
  54747. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  54748. }
  54749. // if the particles will always face the camera
  54750. if (this.billboard) {
  54751. // compute the camera position and un-rotate it by the current mesh rotation
  54752. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  54753. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  54754. this._cam_axisZ.normalize();
  54755. // same for camera up vector extracted from the cam view matrix
  54756. var view = this._camera.getViewMatrix(true);
  54757. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  54758. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  54759. this._cam_axisY.normalize();
  54760. this._cam_axisX.normalize();
  54761. }
  54762. // if depthSort, compute the camera global position in the mesh local system
  54763. if (this._depthSort) {
  54764. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  54765. }
  54766. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  54767. var idx = 0; // current position index in the global array positions32
  54768. var index = 0; // position start index in the global array positions32 of the current particle
  54769. var colidx = 0; // current color index in the global array colors32
  54770. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  54771. var uvidx = 0; // current uv index in the global array uvs32
  54772. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  54773. var pt = 0; // current index in the particle model shape
  54774. if (this.mesh.isFacetDataEnabled) {
  54775. this._computeBoundingBox = true;
  54776. }
  54777. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  54778. if (this._computeBoundingBox) {
  54779. if (start == 0 && end == this.nbParticles - 1) {
  54780. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  54781. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  54782. }
  54783. else {
  54784. if (this.mesh._boundingInfo) {
  54785. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  54786. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  54787. }
  54788. }
  54789. }
  54790. // particle loop
  54791. index = this.particles[start]._pos;
  54792. var vpos = (index / 3) | 0;
  54793. colorIndex = vpos * 4;
  54794. uvIndex = vpos * 2;
  54795. for (var p = start; p <= end; p++) {
  54796. this._particle = this.particles[p];
  54797. this._shape = this._particle._model._shape;
  54798. this._shapeUV = this._particle._model._shapeUV;
  54799. // call to custom user function to update the particle properties
  54800. this.updateParticle(this._particle);
  54801. // camera-particle distance for depth sorting
  54802. if (this._depthSort && this._depthSortParticles) {
  54803. var dsp = this.depthSortedParticles[p];
  54804. dsp.ind = this._particle._ind;
  54805. dsp.indicesLength = this._particle._model._indicesLength;
  54806. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  54807. }
  54808. // skip the computations for inactive or already invisible particles
  54809. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  54810. // increment indexes for the next particle
  54811. pt = this._shape.length;
  54812. index += pt * 3;
  54813. colorIndex += pt * 4;
  54814. uvIndex += pt * 2;
  54815. continue;
  54816. }
  54817. if (this._particle.isVisible) {
  54818. this._particle._stillInvisible = false; // un-mark permanent invisibility
  54819. this._particleHasParent = (this._particle.parentId !== null);
  54820. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  54821. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  54822. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  54823. // particle rotation matrix
  54824. if (this.billboard) {
  54825. this._particle.rotation.x = 0.0;
  54826. this._particle.rotation.y = 0.0;
  54827. }
  54828. if (this._computeParticleRotation || this.billboard) {
  54829. if (this._particle.rotationQuaternion) {
  54830. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  54831. }
  54832. else {
  54833. this._yaw = this._particle.rotation.y;
  54834. this._pitch = this._particle.rotation.x;
  54835. this._roll = this._particle.rotation.z;
  54836. this._quaternionRotationYPR();
  54837. }
  54838. this._quaternionToRotationMatrix();
  54839. }
  54840. if (this._particleHasParent) {
  54841. this._parent = this.particles[this._particle.parentId];
  54842. 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];
  54843. 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];
  54844. 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];
  54845. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  54846. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  54847. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  54848. if (this._computeParticleRotation || this.billboard) {
  54849. 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];
  54850. 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];
  54851. 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];
  54852. 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];
  54853. 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];
  54854. 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];
  54855. 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];
  54856. 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];
  54857. 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];
  54858. }
  54859. }
  54860. else {
  54861. this._particle._globalPosition.x = this._particle.position.x;
  54862. this._particle._globalPosition.y = this._particle.position.y;
  54863. this._particle._globalPosition.z = this._particle.position.z;
  54864. if (this._computeParticleRotation || this.billboard) {
  54865. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  54866. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  54867. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  54868. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  54869. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  54870. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  54871. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  54872. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  54873. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  54874. }
  54875. }
  54876. if (this._particle.translateFromPivot) {
  54877. this._pivotBackTranslation.x = 0.0;
  54878. this._pivotBackTranslation.y = 0.0;
  54879. this._pivotBackTranslation.z = 0.0;
  54880. }
  54881. else {
  54882. this._pivotBackTranslation.x = this._scaledPivot.x;
  54883. this._pivotBackTranslation.y = this._scaledPivot.y;
  54884. this._pivotBackTranslation.z = this._scaledPivot.z;
  54885. }
  54886. // particle vertex loop
  54887. for (pt = 0; pt < this._shape.length; pt++) {
  54888. idx = index + pt * 3;
  54889. colidx = colorIndex + pt * 4;
  54890. uvidx = uvIndex + pt * 2;
  54891. this._vertex.x = this._shape[pt].x;
  54892. this._vertex.y = this._shape[pt].y;
  54893. this._vertex.z = this._shape[pt].z;
  54894. if (this._computeParticleVertex) {
  54895. this.updateParticleVertex(this._particle, this._vertex, pt);
  54896. }
  54897. // positions
  54898. this._vertex.x *= this._particle.scaling.x;
  54899. this._vertex.y *= this._particle.scaling.y;
  54900. this._vertex.z *= this._particle.scaling.z;
  54901. this._vertex.x -= this._scaledPivot.x;
  54902. this._vertex.y -= this._scaledPivot.y;
  54903. this._vertex.z -= this._scaledPivot.z;
  54904. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  54905. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  54906. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  54907. this._rotated.x += this._pivotBackTranslation.x;
  54908. this._rotated.y += this._pivotBackTranslation.y;
  54909. this._rotated.z += this._pivotBackTranslation.z;
  54910. 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;
  54911. 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;
  54912. 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;
  54913. if (this._computeBoundingBox) {
  54914. if (this._positions32[idx] < this._minimum.x) {
  54915. this._minimum.x = this._positions32[idx];
  54916. }
  54917. if (this._positions32[idx] > this._maximum.x) {
  54918. this._maximum.x = this._positions32[idx];
  54919. }
  54920. if (this._positions32[idx + 1] < this._minimum.y) {
  54921. this._minimum.y = this._positions32[idx + 1];
  54922. }
  54923. if (this._positions32[idx + 1] > this._maximum.y) {
  54924. this._maximum.y = this._positions32[idx + 1];
  54925. }
  54926. if (this._positions32[idx + 2] < this._minimum.z) {
  54927. this._minimum.z = this._positions32[idx + 2];
  54928. }
  54929. if (this._positions32[idx + 2] > this._maximum.z) {
  54930. this._maximum.z = this._positions32[idx + 2];
  54931. }
  54932. }
  54933. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  54934. if (!this._computeParticleVertex) {
  54935. this._normal.x = this._fixedNormal32[idx];
  54936. this._normal.y = this._fixedNormal32[idx + 1];
  54937. this._normal.z = this._fixedNormal32[idx + 2];
  54938. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  54939. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  54940. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  54941. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  54942. 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;
  54943. 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;
  54944. }
  54945. if (this._computeParticleColor && this._particle.color) {
  54946. this._colors32[colidx] = this._particle.color.r;
  54947. this._colors32[colidx + 1] = this._particle.color.g;
  54948. this._colors32[colidx + 2] = this._particle.color.b;
  54949. this._colors32[colidx + 3] = this._particle.color.a;
  54950. }
  54951. if (this._computeParticleTexture) {
  54952. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54953. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54954. }
  54955. }
  54956. }
  54957. else {
  54958. this._particle._stillInvisible = true; // mark the particle as invisible
  54959. for (pt = 0; pt < this._shape.length; pt++) {
  54960. idx = index + pt * 3;
  54961. colidx = colorIndex + pt * 4;
  54962. uvidx = uvIndex + pt * 2;
  54963. this._positions32[idx] = 0.0;
  54964. this._positions32[idx + 1] = 0.0;
  54965. this._positions32[idx + 2] = 0.0;
  54966. this._normals32[idx] = 0.0;
  54967. this._normals32[idx + 1] = 0.0;
  54968. this._normals32[idx + 2] = 0.0;
  54969. if (this._computeParticleColor && this._particle.color) {
  54970. this._colors32[colidx] = this._particle.color.r;
  54971. this._colors32[colidx + 1] = this._particle.color.g;
  54972. this._colors32[colidx + 2] = this._particle.color.b;
  54973. this._colors32[colidx + 3] = this._particle.color.a;
  54974. }
  54975. if (this._computeParticleTexture) {
  54976. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54977. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54978. }
  54979. }
  54980. }
  54981. // if the particle intersections must be computed : update the bbInfo
  54982. if (this._particlesIntersect) {
  54983. var bInfo = this._particle._boundingInfo;
  54984. var bBox = bInfo.boundingBox;
  54985. var bSphere = bInfo.boundingSphere;
  54986. if (!this._bSphereOnly) {
  54987. // place, scale and rotate the particle bbox within the SPS local system, then update it
  54988. for (var b = 0; b < bBox.vectors.length; b++) {
  54989. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  54990. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  54991. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  54992. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  54993. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  54994. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  54995. 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;
  54996. 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;
  54997. 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;
  54998. }
  54999. bBox._update(this.mesh._worldMatrix);
  55000. }
  55001. // place and scale the particle bouding sphere in the SPS local system, then update it
  55002. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  55003. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  55004. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  55005. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  55006. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  55007. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  55008. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  55009. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  55010. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  55011. 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));
  55012. bSphere._update(this.mesh._worldMatrix);
  55013. }
  55014. // increment indexes for the next particle
  55015. index = idx + 3;
  55016. colorIndex = colidx + 4;
  55017. uvIndex = uvidx + 2;
  55018. }
  55019. // if the VBO must be updated
  55020. if (update) {
  55021. if (this._computeParticleColor) {
  55022. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  55023. }
  55024. if (this._computeParticleTexture) {
  55025. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  55026. }
  55027. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  55028. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  55029. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  55030. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  55031. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  55032. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  55033. for (var i = 0; i < this._normals32.length; i++) {
  55034. this._fixedNormal32[i] = this._normals32[i];
  55035. }
  55036. }
  55037. if (!this.mesh.areNormalsFrozen) {
  55038. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  55039. }
  55040. }
  55041. if (this._depthSort && this._depthSortParticles) {
  55042. this.depthSortedParticles.sort(this._depthSortFunction);
  55043. var dspl = this.depthSortedParticles.length;
  55044. var sorted = 0;
  55045. var lind = 0;
  55046. var sind = 0;
  55047. var sid = 0;
  55048. for (sorted = 0; sorted < dspl; sorted++) {
  55049. lind = this.depthSortedParticles[sorted].indicesLength;
  55050. sind = this.depthSortedParticles[sorted].ind;
  55051. for (var i = 0; i < lind; i++) {
  55052. this._indices32[sid] = this._indices[sind + i];
  55053. sid++;
  55054. }
  55055. }
  55056. this.mesh.updateIndices(this._indices32);
  55057. }
  55058. }
  55059. if (this._computeBoundingBox) {
  55060. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  55061. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  55062. }
  55063. this.afterUpdateParticles(start, end, update);
  55064. return this;
  55065. };
  55066. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  55067. this._halfroll = this._roll * 0.5;
  55068. this._halfpitch = this._pitch * 0.5;
  55069. this._halfyaw = this._yaw * 0.5;
  55070. this._sinRoll = Math.sin(this._halfroll);
  55071. this._cosRoll = Math.cos(this._halfroll);
  55072. this._sinPitch = Math.sin(this._halfpitch);
  55073. this._cosPitch = Math.cos(this._halfpitch);
  55074. this._sinYaw = Math.sin(this._halfyaw);
  55075. this._cosYaw = Math.cos(this._halfyaw);
  55076. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  55077. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  55078. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  55079. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  55080. };
  55081. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  55082. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  55083. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  55084. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  55085. this._rotMatrix.m[3] = 0;
  55086. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  55087. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  55088. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  55089. this._rotMatrix.m[7] = 0;
  55090. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  55091. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  55092. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  55093. this._rotMatrix.m[11] = 0;
  55094. this._rotMatrix.m[12] = 0;
  55095. this._rotMatrix.m[13] = 0;
  55096. this._rotMatrix.m[14] = 0;
  55097. this._rotMatrix.m[15] = 1.0;
  55098. };
  55099. /**
  55100. * Disposes the SPS.
  55101. */
  55102. SolidParticleSystem.prototype.dispose = function () {
  55103. this.mesh.dispose();
  55104. this.vars = null;
  55105. // drop references to internal big arrays for the GC
  55106. this._positions = null;
  55107. this._indices = null;
  55108. this._normals = null;
  55109. this._uvs = null;
  55110. this._colors = null;
  55111. this._indices32 = null;
  55112. this._positions32 = null;
  55113. this._normals32 = null;
  55114. this._fixedNormal32 = null;
  55115. this._uvs32 = null;
  55116. this._colors32 = null;
  55117. this.pickedParticles = null;
  55118. };
  55119. /**
  55120. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  55121. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55122. * @returns the SPS.
  55123. */
  55124. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  55125. if (!this._isVisibilityBoxLocked) {
  55126. this.mesh.refreshBoundingInfo();
  55127. }
  55128. return this;
  55129. };
  55130. /**
  55131. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  55132. * @param size the size (float) of the visibility box
  55133. * note : this doesn't lock the SPS mesh bounding box.
  55134. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55135. */
  55136. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  55137. var vis = size / 2;
  55138. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  55139. };
  55140. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  55141. /**
  55142. * Gets whether the SPS as always visible or not
  55143. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55144. */
  55145. get: function () {
  55146. return this._alwaysVisible;
  55147. },
  55148. /**
  55149. * Sets the SPS as always visible or not
  55150. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55151. */
  55152. set: function (val) {
  55153. this._alwaysVisible = val;
  55154. this.mesh.alwaysSelectAsActiveMesh = val;
  55155. },
  55156. enumerable: true,
  55157. configurable: true
  55158. });
  55159. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  55160. /**
  55161. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  55162. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55163. */
  55164. get: function () {
  55165. return this._isVisibilityBoxLocked;
  55166. },
  55167. /**
  55168. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  55169. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55170. */
  55171. set: function (val) {
  55172. this._isVisibilityBoxLocked = val;
  55173. var boundingInfo = this.mesh.getBoundingInfo();
  55174. boundingInfo.isLocked = val;
  55175. },
  55176. enumerable: true,
  55177. configurable: true
  55178. });
  55179. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  55180. /**
  55181. * Gets if `setParticles()` computes the particle rotations or not.
  55182. * Default value : true. The SPS is faster when it's set to false.
  55183. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  55184. */
  55185. get: function () {
  55186. return this._computeParticleRotation;
  55187. },
  55188. /**
  55189. * Tells to `setParticles()` to compute the particle rotations or not.
  55190. * Default value : true. The SPS is faster when it's set to false.
  55191. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  55192. */
  55193. set: function (val) {
  55194. this._computeParticleRotation = val;
  55195. },
  55196. enumerable: true,
  55197. configurable: true
  55198. });
  55199. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  55200. /**
  55201. * Gets if `setParticles()` computes the particle colors or not.
  55202. * Default value : true. The SPS is faster when it's set to false.
  55203. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  55204. */
  55205. get: function () {
  55206. return this._computeParticleColor;
  55207. },
  55208. /**
  55209. * Tells to `setParticles()` to compute the particle colors or not.
  55210. * Default value : true. The SPS is faster when it's set to false.
  55211. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  55212. */
  55213. set: function (val) {
  55214. this._computeParticleColor = val;
  55215. },
  55216. enumerable: true,
  55217. configurable: true
  55218. });
  55219. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  55220. /**
  55221. * Gets if `setParticles()` computes the particle textures or not.
  55222. * Default value : true. The SPS is faster when it's set to false.
  55223. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  55224. */
  55225. get: function () {
  55226. return this._computeParticleTexture;
  55227. },
  55228. set: function (val) {
  55229. this._computeParticleTexture = val;
  55230. },
  55231. enumerable: true,
  55232. configurable: true
  55233. });
  55234. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  55235. /**
  55236. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  55237. * Default value : false. The SPS is faster when it's set to false.
  55238. * Note : the particle custom vertex positions aren't stored values.
  55239. */
  55240. get: function () {
  55241. return this._computeParticleVertex;
  55242. },
  55243. /**
  55244. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  55245. * Default value : false. The SPS is faster when it's set to false.
  55246. * Note : the particle custom vertex positions aren't stored values.
  55247. */
  55248. set: function (val) {
  55249. this._computeParticleVertex = val;
  55250. },
  55251. enumerable: true,
  55252. configurable: true
  55253. });
  55254. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  55255. /**
  55256. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  55257. */
  55258. get: function () {
  55259. return this._computeBoundingBox;
  55260. },
  55261. /**
  55262. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  55263. */
  55264. set: function (val) {
  55265. this._computeBoundingBox = val;
  55266. },
  55267. enumerable: true,
  55268. configurable: true
  55269. });
  55270. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  55271. /**
  55272. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  55273. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  55274. * Default : `true`
  55275. */
  55276. get: function () {
  55277. return this._depthSortParticles;
  55278. },
  55279. /**
  55280. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  55281. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  55282. * Default : `true`
  55283. */
  55284. set: function (val) {
  55285. this._depthSortParticles = val;
  55286. },
  55287. enumerable: true,
  55288. configurable: true
  55289. });
  55290. // =======================================================================
  55291. // Particle behavior logic
  55292. // these following methods may be overwritten by the user to fit his needs
  55293. /**
  55294. * This function does nothing. It may be overwritten to set all the particle first values.
  55295. * The SPS doesn't call this function, you may have to call it by your own.
  55296. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55297. */
  55298. SolidParticleSystem.prototype.initParticles = function () {
  55299. };
  55300. /**
  55301. * This function does nothing. It may be overwritten to recycle a particle.
  55302. * The SPS doesn't call this function, you may have to call it by your own.
  55303. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55304. * @param particle The particle to recycle
  55305. * @returns the recycled particle
  55306. */
  55307. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  55308. return particle;
  55309. };
  55310. /**
  55311. * Updates a particle : this function should be overwritten by the user.
  55312. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  55313. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55314. * @example : just set a particle position or velocity and recycle conditions
  55315. * @param particle The particle to update
  55316. * @returns the updated particle
  55317. */
  55318. SolidParticleSystem.prototype.updateParticle = function (particle) {
  55319. return particle;
  55320. };
  55321. /**
  55322. * Updates a vertex of a particle : it can be overwritten by the user.
  55323. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  55324. * @param particle the current particle
  55325. * @param vertex the current index of the current particle
  55326. * @param pt the index of the current vertex in the particle shape
  55327. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  55328. * @example : just set a vertex particle position
  55329. * @returns the updated vertex
  55330. */
  55331. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  55332. return vertex;
  55333. };
  55334. /**
  55335. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  55336. * This does nothing and may be overwritten by the user.
  55337. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55338. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55339. * @param update the boolean update value actually passed to setParticles()
  55340. */
  55341. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  55342. };
  55343. /**
  55344. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  55345. * This will be passed three parameters.
  55346. * This does nothing and may be overwritten by the user.
  55347. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55348. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55349. * @param update the boolean update value actually passed to setParticles()
  55350. */
  55351. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  55352. };
  55353. return SolidParticleSystem;
  55354. }());
  55355. BABYLON.SolidParticleSystem = SolidParticleSystem;
  55356. })(BABYLON || (BABYLON = {}));
  55357. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  55358. "use strict";
  55359. var BABYLON;
  55360. (function (BABYLON) {
  55361. var ShaderMaterial = /** @class */ (function (_super) {
  55362. __extends(ShaderMaterial, _super);
  55363. function ShaderMaterial(name, scene, shaderPath, options) {
  55364. var _this = _super.call(this, name, scene) || this;
  55365. _this._textures = {};
  55366. _this._textureArrays = {};
  55367. _this._floats = {};
  55368. _this._ints = {};
  55369. _this._floatsArrays = {};
  55370. _this._colors3 = {};
  55371. _this._colors3Arrays = {};
  55372. _this._colors4 = {};
  55373. _this._vectors2 = {};
  55374. _this._vectors3 = {};
  55375. _this._vectors4 = {};
  55376. _this._matrices = {};
  55377. _this._matrices3x3 = {};
  55378. _this._matrices2x2 = {};
  55379. _this._vectors2Arrays = {};
  55380. _this._vectors3Arrays = {};
  55381. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  55382. _this._shaderPath = shaderPath;
  55383. options.needAlphaBlending = options.needAlphaBlending || false;
  55384. options.needAlphaTesting = options.needAlphaTesting || false;
  55385. options.attributes = options.attributes || ["position", "normal", "uv"];
  55386. options.uniforms = options.uniforms || ["worldViewProjection"];
  55387. options.uniformBuffers = options.uniformBuffers || [];
  55388. options.samplers = options.samplers || [];
  55389. options.defines = options.defines || [];
  55390. _this._options = options;
  55391. return _this;
  55392. }
  55393. ShaderMaterial.prototype.getClassName = function () {
  55394. return "ShaderMaterial";
  55395. };
  55396. ShaderMaterial.prototype.needAlphaBlending = function () {
  55397. return this._options.needAlphaBlending;
  55398. };
  55399. ShaderMaterial.prototype.needAlphaTesting = function () {
  55400. return this._options.needAlphaTesting;
  55401. };
  55402. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  55403. if (this._options.uniforms.indexOf(uniformName) === -1) {
  55404. this._options.uniforms.push(uniformName);
  55405. }
  55406. };
  55407. ShaderMaterial.prototype.setTexture = function (name, texture) {
  55408. if (this._options.samplers.indexOf(name) === -1) {
  55409. this._options.samplers.push(name);
  55410. }
  55411. this._textures[name] = texture;
  55412. return this;
  55413. };
  55414. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  55415. if (this._options.samplers.indexOf(name) === -1) {
  55416. this._options.samplers.push(name);
  55417. }
  55418. this._checkUniform(name);
  55419. this._textureArrays[name] = textures;
  55420. return this;
  55421. };
  55422. ShaderMaterial.prototype.setFloat = function (name, value) {
  55423. this._checkUniform(name);
  55424. this._floats[name] = value;
  55425. return this;
  55426. };
  55427. ShaderMaterial.prototype.setInt = function (name, value) {
  55428. this._checkUniform(name);
  55429. this._ints[name] = value;
  55430. return this;
  55431. };
  55432. ShaderMaterial.prototype.setFloats = function (name, value) {
  55433. this._checkUniform(name);
  55434. this._floatsArrays[name] = value;
  55435. return this;
  55436. };
  55437. ShaderMaterial.prototype.setColor3 = function (name, value) {
  55438. this._checkUniform(name);
  55439. this._colors3[name] = value;
  55440. return this;
  55441. };
  55442. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  55443. this._checkUniform(name);
  55444. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  55445. color.toArray(arr, arr.length);
  55446. return arr;
  55447. }, []);
  55448. return this;
  55449. };
  55450. ShaderMaterial.prototype.setColor4 = function (name, value) {
  55451. this._checkUniform(name);
  55452. this._colors4[name] = value;
  55453. return this;
  55454. };
  55455. ShaderMaterial.prototype.setVector2 = function (name, value) {
  55456. this._checkUniform(name);
  55457. this._vectors2[name] = value;
  55458. return this;
  55459. };
  55460. ShaderMaterial.prototype.setVector3 = function (name, value) {
  55461. this._checkUniform(name);
  55462. this._vectors3[name] = value;
  55463. return this;
  55464. };
  55465. ShaderMaterial.prototype.setVector4 = function (name, value) {
  55466. this._checkUniform(name);
  55467. this._vectors4[name] = value;
  55468. return this;
  55469. };
  55470. ShaderMaterial.prototype.setMatrix = function (name, value) {
  55471. this._checkUniform(name);
  55472. this._matrices[name] = value;
  55473. return this;
  55474. };
  55475. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  55476. this._checkUniform(name);
  55477. this._matrices3x3[name] = value;
  55478. return this;
  55479. };
  55480. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  55481. this._checkUniform(name);
  55482. this._matrices2x2[name] = value;
  55483. return this;
  55484. };
  55485. ShaderMaterial.prototype.setArray2 = function (name, value) {
  55486. this._checkUniform(name);
  55487. this._vectors2Arrays[name] = value;
  55488. return this;
  55489. };
  55490. ShaderMaterial.prototype.setArray3 = function (name, value) {
  55491. this._checkUniform(name);
  55492. this._vectors3Arrays[name] = value;
  55493. return this;
  55494. };
  55495. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  55496. if (!mesh) {
  55497. return true;
  55498. }
  55499. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  55500. return false;
  55501. }
  55502. return false;
  55503. };
  55504. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  55505. var scene = this.getScene();
  55506. var engine = scene.getEngine();
  55507. if (!this.checkReadyOnEveryCall) {
  55508. if (this._renderId === scene.getRenderId()) {
  55509. if (this._checkCache(scene, mesh, useInstances)) {
  55510. return true;
  55511. }
  55512. }
  55513. }
  55514. // Instances
  55515. var defines = [];
  55516. var attribs = [];
  55517. var fallbacks = new BABYLON.EffectFallbacks();
  55518. if (useInstances) {
  55519. defines.push("#define INSTANCES");
  55520. }
  55521. for (var index = 0; index < this._options.defines.length; index++) {
  55522. defines.push(this._options.defines[index]);
  55523. }
  55524. for (var index = 0; index < this._options.attributes.length; index++) {
  55525. attribs.push(this._options.attributes[index]);
  55526. }
  55527. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  55528. attribs.push(BABYLON.VertexBuffer.ColorKind);
  55529. defines.push("#define VERTEXCOLOR");
  55530. }
  55531. // Bones
  55532. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  55533. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  55534. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  55535. if (mesh.numBoneInfluencers > 4) {
  55536. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  55537. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  55538. }
  55539. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  55540. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  55541. fallbacks.addCPUSkinningFallback(0, mesh);
  55542. if (this._options.uniforms.indexOf("mBones") === -1) {
  55543. this._options.uniforms.push("mBones");
  55544. }
  55545. }
  55546. else {
  55547. defines.push("#define NUM_BONE_INFLUENCERS 0");
  55548. }
  55549. // Textures
  55550. for (var name in this._textures) {
  55551. if (!this._textures[name].isReady()) {
  55552. return false;
  55553. }
  55554. }
  55555. // Alpha test
  55556. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  55557. defines.push("#define ALPHATEST");
  55558. }
  55559. var previousEffect = this._effect;
  55560. var join = defines.join("\n");
  55561. this._effect = engine.createEffect(this._shaderPath, {
  55562. attributes: attribs,
  55563. uniformsNames: this._options.uniforms,
  55564. uniformBuffersNames: this._options.uniformBuffers,
  55565. samplers: this._options.samplers,
  55566. defines: join,
  55567. fallbacks: fallbacks,
  55568. onCompiled: this.onCompiled,
  55569. onError: this.onError
  55570. }, engine);
  55571. if (!this._effect.isReady()) {
  55572. return false;
  55573. }
  55574. if (previousEffect !== this._effect) {
  55575. scene.resetCachedMaterial();
  55576. }
  55577. this._renderId = scene.getRenderId();
  55578. return true;
  55579. };
  55580. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  55581. var scene = this.getScene();
  55582. if (!this._effect) {
  55583. return;
  55584. }
  55585. if (this._options.uniforms.indexOf("world") !== -1) {
  55586. this._effect.setMatrix("world", world);
  55587. }
  55588. if (this._options.uniforms.indexOf("worldView") !== -1) {
  55589. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  55590. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  55591. }
  55592. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  55593. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  55594. }
  55595. };
  55596. ShaderMaterial.prototype.bind = function (world, mesh) {
  55597. // Std values
  55598. this.bindOnlyWorldMatrix(world);
  55599. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  55600. if (this._options.uniforms.indexOf("view") !== -1) {
  55601. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  55602. }
  55603. if (this._options.uniforms.indexOf("projection") !== -1) {
  55604. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  55605. }
  55606. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  55607. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  55608. }
  55609. // Bones
  55610. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  55611. var name;
  55612. // Texture
  55613. for (name in this._textures) {
  55614. this._effect.setTexture(name, this._textures[name]);
  55615. }
  55616. // Texture arrays
  55617. for (name in this._textureArrays) {
  55618. this._effect.setTextureArray(name, this._textureArrays[name]);
  55619. }
  55620. // Int
  55621. for (name in this._ints) {
  55622. this._effect.setInt(name, this._ints[name]);
  55623. }
  55624. // Float
  55625. for (name in this._floats) {
  55626. this._effect.setFloat(name, this._floats[name]);
  55627. }
  55628. // Floats
  55629. for (name in this._floatsArrays) {
  55630. this._effect.setArray(name, this._floatsArrays[name]);
  55631. }
  55632. // Color3
  55633. for (name in this._colors3) {
  55634. this._effect.setColor3(name, this._colors3[name]);
  55635. }
  55636. for (name in this._colors3Arrays) {
  55637. this._effect.setArray3(name, this._colors3Arrays[name]);
  55638. }
  55639. // Color4
  55640. for (name in this._colors4) {
  55641. var color = this._colors4[name];
  55642. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  55643. }
  55644. // Vector2
  55645. for (name in this._vectors2) {
  55646. this._effect.setVector2(name, this._vectors2[name]);
  55647. }
  55648. // Vector3
  55649. for (name in this._vectors3) {
  55650. this._effect.setVector3(name, this._vectors3[name]);
  55651. }
  55652. // Vector4
  55653. for (name in this._vectors4) {
  55654. this._effect.setVector4(name, this._vectors4[name]);
  55655. }
  55656. // Matrix
  55657. for (name in this._matrices) {
  55658. this._effect.setMatrix(name, this._matrices[name]);
  55659. }
  55660. // Matrix 3x3
  55661. for (name in this._matrices3x3) {
  55662. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  55663. }
  55664. // Matrix 2x2
  55665. for (name in this._matrices2x2) {
  55666. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  55667. }
  55668. // Vector2Array
  55669. for (name in this._vectors2Arrays) {
  55670. this._effect.setArray2(name, this._vectors2Arrays[name]);
  55671. }
  55672. // Vector3Array
  55673. for (name in this._vectors3Arrays) {
  55674. this._effect.setArray3(name, this._vectors3Arrays[name]);
  55675. }
  55676. }
  55677. this._afterBind(mesh);
  55678. };
  55679. ShaderMaterial.prototype.getActiveTextures = function () {
  55680. var activeTextures = _super.prototype.getActiveTextures.call(this);
  55681. for (var name in this._textures) {
  55682. activeTextures.push(this._textures[name]);
  55683. }
  55684. for (var name in this._textureArrays) {
  55685. var array = this._textureArrays[name];
  55686. for (var index = 0; index < array.length; index++) {
  55687. activeTextures.push(array[index]);
  55688. }
  55689. }
  55690. return activeTextures;
  55691. };
  55692. ShaderMaterial.prototype.hasTexture = function (texture) {
  55693. if (_super.prototype.hasTexture.call(this, texture)) {
  55694. return true;
  55695. }
  55696. for (var name in this._textures) {
  55697. if (this._textures[name] === texture) {
  55698. return true;
  55699. }
  55700. }
  55701. for (var name in this._textureArrays) {
  55702. var array = this._textureArrays[name];
  55703. for (var index = 0; index < array.length; index++) {
  55704. if (array[index] === texture) {
  55705. return true;
  55706. }
  55707. }
  55708. }
  55709. return false;
  55710. };
  55711. ShaderMaterial.prototype.clone = function (name) {
  55712. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  55713. return newShaderMaterial;
  55714. };
  55715. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  55716. if (forceDisposeTextures) {
  55717. var name;
  55718. for (name in this._textures) {
  55719. this._textures[name].dispose();
  55720. }
  55721. for (name in this._textureArrays) {
  55722. var array = this._textureArrays[name];
  55723. for (var index = 0; index < array.length; index++) {
  55724. array[index].dispose();
  55725. }
  55726. }
  55727. }
  55728. this._textures = {};
  55729. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  55730. };
  55731. ShaderMaterial.prototype.serialize = function () {
  55732. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  55733. serializationObject.customType = "BABYLON.ShaderMaterial";
  55734. serializationObject.options = this._options;
  55735. serializationObject.shaderPath = this._shaderPath;
  55736. var name;
  55737. // Texture
  55738. serializationObject.textures = {};
  55739. for (name in this._textures) {
  55740. serializationObject.textures[name] = this._textures[name].serialize();
  55741. }
  55742. // Texture arrays
  55743. serializationObject.textureArrays = {};
  55744. for (name in this._textureArrays) {
  55745. serializationObject.textureArrays[name] = [];
  55746. var array = this._textureArrays[name];
  55747. for (var index = 0; index < array.length; index++) {
  55748. serializationObject.textureArrays[name].push(array[index].serialize());
  55749. }
  55750. }
  55751. // Float
  55752. serializationObject.floats = {};
  55753. for (name in this._floats) {
  55754. serializationObject.floats[name] = this._floats[name];
  55755. }
  55756. // Float s
  55757. serializationObject.FloatArrays = {};
  55758. for (name in this._floatsArrays) {
  55759. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  55760. }
  55761. // Color3
  55762. serializationObject.colors3 = {};
  55763. for (name in this._colors3) {
  55764. serializationObject.colors3[name] = this._colors3[name].asArray();
  55765. }
  55766. // Color3 array
  55767. serializationObject.colors3Arrays = {};
  55768. for (name in this._colors3Arrays) {
  55769. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  55770. }
  55771. // Color4
  55772. serializationObject.colors4 = {};
  55773. for (name in this._colors4) {
  55774. serializationObject.colors4[name] = this._colors4[name].asArray();
  55775. }
  55776. // Vector2
  55777. serializationObject.vectors2 = {};
  55778. for (name in this._vectors2) {
  55779. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  55780. }
  55781. // Vector3
  55782. serializationObject.vectors3 = {};
  55783. for (name in this._vectors3) {
  55784. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  55785. }
  55786. // Vector4
  55787. serializationObject.vectors4 = {};
  55788. for (name in this._vectors4) {
  55789. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  55790. }
  55791. // Matrix
  55792. serializationObject.matrices = {};
  55793. for (name in this._matrices) {
  55794. serializationObject.matrices[name] = this._matrices[name].asArray();
  55795. }
  55796. // Matrix 3x3
  55797. serializationObject.matrices3x3 = {};
  55798. for (name in this._matrices3x3) {
  55799. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  55800. }
  55801. // Matrix 2x2
  55802. serializationObject.matrices2x2 = {};
  55803. for (name in this._matrices2x2) {
  55804. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  55805. }
  55806. // Vector2Array
  55807. serializationObject.vectors2Arrays = {};
  55808. for (name in this._vectors2Arrays) {
  55809. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  55810. }
  55811. // Vector3Array
  55812. serializationObject.vectors3Arrays = {};
  55813. for (name in this._vectors3Arrays) {
  55814. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  55815. }
  55816. return serializationObject;
  55817. };
  55818. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  55819. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  55820. var name;
  55821. // Texture
  55822. for (name in source.textures) {
  55823. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  55824. }
  55825. // Texture arrays
  55826. for (name in source.textureArrays) {
  55827. var array = source.textureArrays[name];
  55828. var textureArray = new Array();
  55829. for (var index = 0; index < array.length; index++) {
  55830. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  55831. }
  55832. material.setTextureArray(name, textureArray);
  55833. }
  55834. // Float
  55835. for (name in source.floats) {
  55836. material.setFloat(name, source.floats[name]);
  55837. }
  55838. // Float s
  55839. for (name in source.floatsArrays) {
  55840. material.setFloats(name, source.floatsArrays[name]);
  55841. }
  55842. // Color3
  55843. for (name in source.colors3) {
  55844. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  55845. }
  55846. // Color3 arrays
  55847. for (name in source.colors3Arrays) {
  55848. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  55849. if (i % 3 === 0) {
  55850. arr.push([num]);
  55851. }
  55852. else {
  55853. arr[arr.length - 1].push(num);
  55854. }
  55855. return arr;
  55856. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  55857. material.setColor3Array(name, colors);
  55858. }
  55859. // Color4
  55860. for (name in source.colors4) {
  55861. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  55862. }
  55863. // Vector2
  55864. for (name in source.vectors2) {
  55865. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  55866. }
  55867. // Vector3
  55868. for (name in source.vectors3) {
  55869. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  55870. }
  55871. // Vector4
  55872. for (name in source.vectors4) {
  55873. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  55874. }
  55875. // Matrix
  55876. for (name in source.matrices) {
  55877. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  55878. }
  55879. // Matrix 3x3
  55880. for (name in source.matrices3x3) {
  55881. material.setMatrix3x3(name, source.matrices3x3[name]);
  55882. }
  55883. // Matrix 2x2
  55884. for (name in source.matrices2x2) {
  55885. material.setMatrix2x2(name, source.matrices2x2[name]);
  55886. }
  55887. // Vector2Array
  55888. for (name in source.vectors2Arrays) {
  55889. material.setArray2(name, source.vectors2Arrays[name]);
  55890. }
  55891. // Vector3Array
  55892. for (name in source.vectors3Arrays) {
  55893. material.setArray3(name, source.vectors3Arrays[name]);
  55894. }
  55895. return material;
  55896. };
  55897. return ShaderMaterial;
  55898. }(BABYLON.Material));
  55899. BABYLON.ShaderMaterial = ShaderMaterial;
  55900. })(BABYLON || (BABYLON = {}));
  55901. //# sourceMappingURL=babylon.shaderMaterial.js.map
  55902. "use strict";
  55903. var BABYLON;
  55904. (function (BABYLON) {
  55905. var GroundMesh = /** @class */ (function (_super) {
  55906. __extends(GroundMesh, _super);
  55907. function GroundMesh(name, scene) {
  55908. var _this = _super.call(this, name, scene) || this;
  55909. _this.generateOctree = false;
  55910. return _this;
  55911. }
  55912. GroundMesh.prototype.getClassName = function () {
  55913. return "GroundMesh";
  55914. };
  55915. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  55916. get: function () {
  55917. return Math.min(this._subdivisionsX, this._subdivisionsY);
  55918. },
  55919. enumerable: true,
  55920. configurable: true
  55921. });
  55922. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  55923. get: function () {
  55924. return this._subdivisionsX;
  55925. },
  55926. enumerable: true,
  55927. configurable: true
  55928. });
  55929. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  55930. get: function () {
  55931. return this._subdivisionsY;
  55932. },
  55933. enumerable: true,
  55934. configurable: true
  55935. });
  55936. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  55937. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  55938. this._subdivisionsX = chunksCount;
  55939. this._subdivisionsY = chunksCount;
  55940. this.subdivide(chunksCount);
  55941. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  55942. };
  55943. /**
  55944. * Returns a height (y) value in the Worl system :
  55945. * the ground altitude at the coordinates (x, z) expressed in the World system.
  55946. * Returns the ground y position if (x, z) are outside the ground surface.
  55947. */
  55948. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  55949. var world = this.getWorldMatrix();
  55950. var invMat = BABYLON.Tmp.Matrix[5];
  55951. world.invertToRef(invMat);
  55952. var tmpVect = BABYLON.Tmp.Vector3[8];
  55953. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  55954. x = tmpVect.x;
  55955. z = tmpVect.z;
  55956. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  55957. return this.position.y;
  55958. }
  55959. if (!this._heightQuads || this._heightQuads.length == 0) {
  55960. this._initHeightQuads();
  55961. this._computeHeightQuads();
  55962. }
  55963. var facet = this._getFacetAt(x, z);
  55964. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  55965. // return y in the World system
  55966. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  55967. return tmpVect.y;
  55968. };
  55969. /**
  55970. * Returns a normalized vector (Vector3) orthogonal to the ground
  55971. * at the ground coordinates (x, z) expressed in the World system.
  55972. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  55973. */
  55974. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  55975. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  55976. this.getNormalAtCoordinatesToRef(x, z, normal);
  55977. return normal;
  55978. };
  55979. /**
  55980. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  55981. * at the ground coordinates (x, z) expressed in the World system.
  55982. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  55983. * Returns the GroundMesh.
  55984. */
  55985. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  55986. var world = this.getWorldMatrix();
  55987. var tmpMat = BABYLON.Tmp.Matrix[5];
  55988. world.invertToRef(tmpMat);
  55989. var tmpVect = BABYLON.Tmp.Vector3[8];
  55990. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  55991. x = tmpVect.x;
  55992. z = tmpVect.z;
  55993. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  55994. return this;
  55995. }
  55996. if (!this._heightQuads || this._heightQuads.length == 0) {
  55997. this._initHeightQuads();
  55998. this._computeHeightQuads();
  55999. }
  56000. var facet = this._getFacetAt(x, z);
  56001. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  56002. return this;
  56003. };
  56004. /**
  56005. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  56006. * if the ground has been updated.
  56007. * This can be used in the render loop.
  56008. * Returns the GroundMesh.
  56009. */
  56010. GroundMesh.prototype.updateCoordinateHeights = function () {
  56011. if (!this._heightQuads || this._heightQuads.length == 0) {
  56012. this._initHeightQuads();
  56013. }
  56014. this._computeHeightQuads();
  56015. return this;
  56016. };
  56017. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  56018. GroundMesh.prototype._getFacetAt = function (x, z) {
  56019. // retrieve col and row from x, z coordinates in the ground local system
  56020. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  56021. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  56022. var quad = this._heightQuads[row * this._subdivisionsX + col];
  56023. var facet;
  56024. if (z < quad.slope.x * x + quad.slope.y) {
  56025. facet = quad.facet1;
  56026. }
  56027. else {
  56028. facet = quad.facet2;
  56029. }
  56030. return facet;
  56031. };
  56032. // Creates and populates the heightMap array with "facet" elements :
  56033. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  56034. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  56035. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  56036. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  56037. // Returns the GroundMesh.
  56038. GroundMesh.prototype._initHeightQuads = function () {
  56039. var subdivisionsX = this._subdivisionsX;
  56040. var subdivisionsY = this._subdivisionsY;
  56041. this._heightQuads = new Array();
  56042. for (var row = 0; row < subdivisionsY; row++) {
  56043. for (var col = 0; col < subdivisionsX; col++) {
  56044. 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) };
  56045. this._heightQuads[row * subdivisionsX + col] = quad;
  56046. }
  56047. }
  56048. return this;
  56049. };
  56050. // Compute each quad element values and update the the heightMap array :
  56051. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  56052. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  56053. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  56054. // Returns the GroundMesh.
  56055. GroundMesh.prototype._computeHeightQuads = function () {
  56056. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56057. if (!positions) {
  56058. return this;
  56059. }
  56060. var v1 = BABYLON.Tmp.Vector3[3];
  56061. var v2 = BABYLON.Tmp.Vector3[2];
  56062. var v3 = BABYLON.Tmp.Vector3[1];
  56063. var v4 = BABYLON.Tmp.Vector3[0];
  56064. var v1v2 = BABYLON.Tmp.Vector3[4];
  56065. var v1v3 = BABYLON.Tmp.Vector3[5];
  56066. var v1v4 = BABYLON.Tmp.Vector3[6];
  56067. var norm1 = BABYLON.Tmp.Vector3[7];
  56068. var norm2 = BABYLON.Tmp.Vector3[8];
  56069. var i = 0;
  56070. var j = 0;
  56071. var k = 0;
  56072. var cd = 0; // 2D slope coefficient : z = cd * x + h
  56073. var h = 0;
  56074. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  56075. var d2 = 0;
  56076. var subdivisionsX = this._subdivisionsX;
  56077. var subdivisionsY = this._subdivisionsY;
  56078. for (var row = 0; row < subdivisionsY; row++) {
  56079. for (var col = 0; col < subdivisionsX; col++) {
  56080. i = col * 3;
  56081. j = row * (subdivisionsX + 1) * 3;
  56082. k = (row + 1) * (subdivisionsX + 1) * 3;
  56083. v1.x = positions[j + i];
  56084. v1.y = positions[j + i + 1];
  56085. v1.z = positions[j + i + 2];
  56086. v2.x = positions[j + i + 3];
  56087. v2.y = positions[j + i + 4];
  56088. v2.z = positions[j + i + 5];
  56089. v3.x = positions[k + i];
  56090. v3.y = positions[k + i + 1];
  56091. v3.z = positions[k + i + 2];
  56092. v4.x = positions[k + i + 3];
  56093. v4.y = positions[k + i + 4];
  56094. v4.z = positions[k + i + 5];
  56095. // 2D slope V1V4
  56096. cd = (v4.z - v1.z) / (v4.x - v1.x);
  56097. h = v1.z - cd * v1.x; // v1 belongs to the slope
  56098. // facet equations :
  56099. // we compute each facet normal vector
  56100. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  56101. // we compute the value d by applying the equation to v1 which belongs to the plane
  56102. // then we store the facet equation in a Vector4
  56103. v2.subtractToRef(v1, v1v2);
  56104. v3.subtractToRef(v1, v1v3);
  56105. v4.subtractToRef(v1, v1v4);
  56106. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  56107. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  56108. norm1.normalize();
  56109. norm2.normalize();
  56110. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  56111. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  56112. var quad = this._heightQuads[row * subdivisionsX + col];
  56113. quad.slope.copyFromFloats(cd, h);
  56114. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  56115. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  56116. }
  56117. }
  56118. return this;
  56119. };
  56120. GroundMesh.prototype.serialize = function (serializationObject) {
  56121. _super.prototype.serialize.call(this, serializationObject);
  56122. serializationObject.subdivisionsX = this._subdivisionsX;
  56123. serializationObject.subdivisionsY = this._subdivisionsY;
  56124. serializationObject.minX = this._minX;
  56125. serializationObject.maxX = this._maxX;
  56126. serializationObject.minZ = this._minZ;
  56127. serializationObject.maxZ = this._maxZ;
  56128. serializationObject.width = this._width;
  56129. serializationObject.height = this._height;
  56130. };
  56131. GroundMesh.Parse = function (parsedMesh, scene) {
  56132. var result = new GroundMesh(parsedMesh.name, scene);
  56133. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  56134. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  56135. result._minX = parsedMesh.minX;
  56136. result._maxX = parsedMesh.maxX;
  56137. result._minZ = parsedMesh.minZ;
  56138. result._maxZ = parsedMesh.maxZ;
  56139. result._width = parsedMesh.width;
  56140. result._height = parsedMesh.height;
  56141. return result;
  56142. };
  56143. return GroundMesh;
  56144. }(BABYLON.Mesh));
  56145. BABYLON.GroundMesh = GroundMesh;
  56146. })(BABYLON || (BABYLON = {}));
  56147. //# sourceMappingURL=babylon.groundMesh.js.map
  56148. "use strict";
  56149. var BABYLON;
  56150. (function (BABYLON) {
  56151. /**
  56152. * Creates an instance based on a source mesh.
  56153. */
  56154. var InstancedMesh = /** @class */ (function (_super) {
  56155. __extends(InstancedMesh, _super);
  56156. function InstancedMesh(name, source) {
  56157. var _this = _super.call(this, name, source.getScene()) || this;
  56158. source.instances.push(_this);
  56159. _this._sourceMesh = source;
  56160. _this.position.copyFrom(source.position);
  56161. _this.rotation.copyFrom(source.rotation);
  56162. _this.scaling.copyFrom(source.scaling);
  56163. if (source.rotationQuaternion) {
  56164. _this.rotationQuaternion = source.rotationQuaternion.clone();
  56165. }
  56166. _this.infiniteDistance = source.infiniteDistance;
  56167. _this.setPivotMatrix(source.getPivotMatrix());
  56168. _this.refreshBoundingInfo();
  56169. _this._syncSubMeshes();
  56170. return _this;
  56171. }
  56172. /**
  56173. * Returns the string "InstancedMesh".
  56174. */
  56175. InstancedMesh.prototype.getClassName = function () {
  56176. return "InstancedMesh";
  56177. };
  56178. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  56179. // Methods
  56180. get: function () {
  56181. return this._sourceMesh.receiveShadows;
  56182. },
  56183. enumerable: true,
  56184. configurable: true
  56185. });
  56186. Object.defineProperty(InstancedMesh.prototype, "material", {
  56187. get: function () {
  56188. return this._sourceMesh.material;
  56189. },
  56190. enumerable: true,
  56191. configurable: true
  56192. });
  56193. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  56194. get: function () {
  56195. return this._sourceMesh.visibility;
  56196. },
  56197. enumerable: true,
  56198. configurable: true
  56199. });
  56200. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  56201. get: function () {
  56202. return this._sourceMesh.skeleton;
  56203. },
  56204. enumerable: true,
  56205. configurable: true
  56206. });
  56207. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  56208. get: function () {
  56209. return this._sourceMesh.renderingGroupId;
  56210. },
  56211. set: function (value) {
  56212. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  56213. return;
  56214. }
  56215. //no-op with warning
  56216. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  56217. },
  56218. enumerable: true,
  56219. configurable: true
  56220. });
  56221. /**
  56222. * Returns the total number of vertices (integer).
  56223. */
  56224. InstancedMesh.prototype.getTotalVertices = function () {
  56225. return this._sourceMesh.getTotalVertices();
  56226. };
  56227. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  56228. get: function () {
  56229. return this._sourceMesh;
  56230. },
  56231. enumerable: true,
  56232. configurable: true
  56233. });
  56234. /**
  56235. * Is this node ready to be used/rendered
  56236. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  56237. * @return {boolean} is it ready
  56238. */
  56239. InstancedMesh.prototype.isReady = function (completeCheck) {
  56240. if (completeCheck === void 0) { completeCheck = false; }
  56241. return this._sourceMesh.isReady(completeCheck, true);
  56242. };
  56243. /**
  56244. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  56245. */
  56246. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  56247. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  56248. };
  56249. /**
  56250. * Sets the vertex data of the mesh geometry for the requested `kind`.
  56251. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  56252. * The `data` are either a numeric array either a Float32Array.
  56253. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  56254. * 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).
  56255. * Note that a new underlying VertexBuffer object is created each call.
  56256. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  56257. *
  56258. * Possible `kind` values :
  56259. * - BABYLON.VertexBuffer.PositionKind
  56260. * - BABYLON.VertexBuffer.UVKind
  56261. * - BABYLON.VertexBuffer.UV2Kind
  56262. * - BABYLON.VertexBuffer.UV3Kind
  56263. * - BABYLON.VertexBuffer.UV4Kind
  56264. * - BABYLON.VertexBuffer.UV5Kind
  56265. * - BABYLON.VertexBuffer.UV6Kind
  56266. * - BABYLON.VertexBuffer.ColorKind
  56267. * - BABYLON.VertexBuffer.MatricesIndicesKind
  56268. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  56269. * - BABYLON.VertexBuffer.MatricesWeightsKind
  56270. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  56271. *
  56272. * Returns the Mesh.
  56273. */
  56274. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  56275. if (this.sourceMesh) {
  56276. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  56277. }
  56278. return this.sourceMesh;
  56279. };
  56280. /**
  56281. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  56282. * If the mesh has no geometry, it is simply returned as it is.
  56283. * The `data` are either a numeric array either a Float32Array.
  56284. * No new underlying VertexBuffer object is created.
  56285. * 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.
  56286. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  56287. *
  56288. * Possible `kind` values :
  56289. * - BABYLON.VertexBuffer.PositionKind
  56290. * - BABYLON.VertexBuffer.UVKind
  56291. * - BABYLON.VertexBuffer.UV2Kind
  56292. * - BABYLON.VertexBuffer.UV3Kind
  56293. * - BABYLON.VertexBuffer.UV4Kind
  56294. * - BABYLON.VertexBuffer.UV5Kind
  56295. * - BABYLON.VertexBuffer.UV6Kind
  56296. * - BABYLON.VertexBuffer.ColorKind
  56297. * - BABYLON.VertexBuffer.MatricesIndicesKind
  56298. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  56299. * - BABYLON.VertexBuffer.MatricesWeightsKind
  56300. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  56301. *
  56302. * Returns the Mesh.
  56303. */
  56304. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  56305. if (this.sourceMesh) {
  56306. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  56307. }
  56308. return this.sourceMesh;
  56309. };
  56310. /**
  56311. * Sets the mesh indices.
  56312. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  56313. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  56314. * This method creates a new index buffer each call.
  56315. * Returns the Mesh.
  56316. */
  56317. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  56318. if (totalVertices === void 0) { totalVertices = null; }
  56319. if (this.sourceMesh) {
  56320. this.sourceMesh.setIndices(indices, totalVertices);
  56321. }
  56322. return this.sourceMesh;
  56323. };
  56324. /**
  56325. * Boolean : True if the mesh owns the requested kind of data.
  56326. */
  56327. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  56328. return this._sourceMesh.isVerticesDataPresent(kind);
  56329. };
  56330. /**
  56331. * Returns an array of indices (IndicesArray).
  56332. */
  56333. InstancedMesh.prototype.getIndices = function () {
  56334. return this._sourceMesh.getIndices();
  56335. };
  56336. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  56337. get: function () {
  56338. return this._sourceMesh._positions;
  56339. },
  56340. enumerable: true,
  56341. configurable: true
  56342. });
  56343. /**
  56344. * Sets a new updated BoundingInfo to the mesh.
  56345. * Returns the mesh.
  56346. */
  56347. InstancedMesh.prototype.refreshBoundingInfo = function () {
  56348. var meshBB = this._sourceMesh.getBoundingInfo();
  56349. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  56350. this._updateBoundingInfo();
  56351. return this;
  56352. };
  56353. InstancedMesh.prototype._preActivate = function () {
  56354. if (this._currentLOD) {
  56355. this._currentLOD._preActivate();
  56356. }
  56357. return this;
  56358. };
  56359. InstancedMesh.prototype._activate = function (renderId) {
  56360. if (this._currentLOD) {
  56361. this._currentLOD._registerInstanceForRenderId(this, renderId);
  56362. }
  56363. return this;
  56364. };
  56365. /**
  56366. * Returns the current associated LOD AbstractMesh.
  56367. */
  56368. InstancedMesh.prototype.getLOD = function (camera) {
  56369. if (!camera) {
  56370. return this;
  56371. }
  56372. var boundingInfo = this.getBoundingInfo();
  56373. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  56374. if (this._currentLOD === this.sourceMesh) {
  56375. return this;
  56376. }
  56377. return this._currentLOD;
  56378. };
  56379. InstancedMesh.prototype._syncSubMeshes = function () {
  56380. this.releaseSubMeshes();
  56381. if (this._sourceMesh.subMeshes) {
  56382. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  56383. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  56384. }
  56385. }
  56386. return this;
  56387. };
  56388. InstancedMesh.prototype._generatePointsArray = function () {
  56389. return this._sourceMesh._generatePointsArray();
  56390. };
  56391. /**
  56392. * Creates a new InstancedMesh from the current mesh.
  56393. * - name (string) : the cloned mesh name
  56394. * - newParent (optional Node) : the optional Node to parent the clone to.
  56395. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  56396. *
  56397. * Returns the clone.
  56398. */
  56399. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  56400. var result = this._sourceMesh.createInstance(name);
  56401. // Deep copy
  56402. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  56403. // Bounding info
  56404. this.refreshBoundingInfo();
  56405. // Parent
  56406. if (newParent) {
  56407. result.parent = newParent;
  56408. }
  56409. if (!doNotCloneChildren) {
  56410. // Children
  56411. for (var index = 0; index < this.getScene().meshes.length; index++) {
  56412. var mesh = this.getScene().meshes[index];
  56413. if (mesh.parent === this) {
  56414. mesh.clone(mesh.name, result);
  56415. }
  56416. }
  56417. }
  56418. result.computeWorldMatrix(true);
  56419. return result;
  56420. };
  56421. /**
  56422. * Disposes the InstancedMesh.
  56423. * Returns nothing.
  56424. */
  56425. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  56426. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  56427. // Remove from mesh
  56428. var index = this._sourceMesh.instances.indexOf(this);
  56429. this._sourceMesh.instances.splice(index, 1);
  56430. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  56431. };
  56432. return InstancedMesh;
  56433. }(BABYLON.AbstractMesh));
  56434. BABYLON.InstancedMesh = InstancedMesh;
  56435. })(BABYLON || (BABYLON = {}));
  56436. //# sourceMappingURL=babylon.instancedMesh.js.map
  56437. "use strict";
  56438. var BABYLON;
  56439. (function (BABYLON) {
  56440. var LinesMesh = /** @class */ (function (_super) {
  56441. __extends(LinesMesh, _super);
  56442. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  56443. if (scene === void 0) { scene = null; }
  56444. if (parent === void 0) { parent = null; }
  56445. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  56446. _this.useVertexColor = useVertexColor;
  56447. _this.useVertexAlpha = useVertexAlpha;
  56448. _this.color = new BABYLON.Color3(1, 1, 1);
  56449. _this.alpha = 1;
  56450. if (source) {
  56451. _this.color = source.color.clone();
  56452. _this.alpha = source.alpha;
  56453. _this.useVertexColor = source.useVertexColor;
  56454. _this.useVertexAlpha = source.useVertexAlpha;
  56455. }
  56456. _this._intersectionThreshold = 0.1;
  56457. var defines = [];
  56458. var options = {
  56459. attributes: [BABYLON.VertexBuffer.PositionKind],
  56460. uniforms: ["world", "viewProjection"],
  56461. needAlphaBlending: true,
  56462. defines: defines
  56463. };
  56464. if (useVertexAlpha === false) {
  56465. options.needAlphaBlending = false;
  56466. }
  56467. if (!useVertexColor) {
  56468. options.uniforms.push("color");
  56469. }
  56470. else {
  56471. options.defines.push("#define VERTEXCOLOR");
  56472. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  56473. }
  56474. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  56475. return _this;
  56476. }
  56477. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  56478. /**
  56479. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  56480. * This margin is expressed in world space coordinates, so its value may vary.
  56481. * Default value is 0.1
  56482. * @returns the intersection Threshold value.
  56483. */
  56484. get: function () {
  56485. return this._intersectionThreshold;
  56486. },
  56487. /**
  56488. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  56489. * This margin is expressed in world space coordinates, so its value may vary.
  56490. * @param value the new threshold to apply
  56491. */
  56492. set: function (value) {
  56493. if (this._intersectionThreshold === value) {
  56494. return;
  56495. }
  56496. this._intersectionThreshold = value;
  56497. if (this.geometry) {
  56498. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  56499. }
  56500. },
  56501. enumerable: true,
  56502. configurable: true
  56503. });
  56504. /**
  56505. * Returns the string "LineMesh"
  56506. */
  56507. LinesMesh.prototype.getClassName = function () {
  56508. return "LinesMesh";
  56509. };
  56510. Object.defineProperty(LinesMesh.prototype, "material", {
  56511. get: function () {
  56512. return this._colorShader;
  56513. },
  56514. set: function (value) {
  56515. // Do nothing
  56516. },
  56517. enumerable: true,
  56518. configurable: true
  56519. });
  56520. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  56521. get: function () {
  56522. return false;
  56523. },
  56524. enumerable: true,
  56525. configurable: true
  56526. });
  56527. LinesMesh.prototype.createInstance = function (name) {
  56528. throw new Error("LinesMeshes do not support createInstance.");
  56529. };
  56530. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  56531. if (!this._geometry) {
  56532. return this;
  56533. }
  56534. // VBOs
  56535. this._geometry._bind(this._colorShader.getEffect());
  56536. // Color
  56537. if (!this.useVertexColor) {
  56538. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  56539. }
  56540. return this;
  56541. };
  56542. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  56543. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  56544. return this;
  56545. }
  56546. var engine = this.getScene().getEngine();
  56547. // Draw order
  56548. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  56549. return this;
  56550. };
  56551. LinesMesh.prototype.dispose = function (doNotRecurse) {
  56552. this._colorShader.dispose();
  56553. _super.prototype.dispose.call(this, doNotRecurse);
  56554. };
  56555. /**
  56556. * Returns a new LineMesh object cloned from the current one.
  56557. */
  56558. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  56559. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  56560. };
  56561. return LinesMesh;
  56562. }(BABYLON.Mesh));
  56563. BABYLON.LinesMesh = LinesMesh;
  56564. })(BABYLON || (BABYLON = {}));
  56565. //# sourceMappingURL=babylon.linesMesh.js.map
  56566. "use strict";
  56567. var BABYLON;
  56568. (function (BABYLON) {
  56569. var MeshBuilder = /** @class */ (function () {
  56570. function MeshBuilder() {
  56571. }
  56572. MeshBuilder.updateSideOrientation = function (orientation) {
  56573. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  56574. return BABYLON.Mesh.DOUBLESIDE;
  56575. }
  56576. if (orientation === undefined || orientation === null) {
  56577. return BABYLON.Mesh.FRONTSIDE;
  56578. }
  56579. return orientation;
  56580. };
  56581. /**
  56582. * Creates a box mesh.
  56583. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  56584. * The parameter `size` sets the size (float) of each box side (default 1).
  56585. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  56586. * 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).
  56587. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  56588. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56589. * 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).
  56590. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56591. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56592. */
  56593. MeshBuilder.CreateBox = function (name, options, scene) {
  56594. if (scene === void 0) { scene = null; }
  56595. var box = new BABYLON.Mesh(name, scene);
  56596. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56597. box._originalBuilderSideOrientation = options.sideOrientation;
  56598. var vertexData = BABYLON.VertexData.CreateBox(options);
  56599. vertexData.applyToMesh(box, options.updatable);
  56600. return box;
  56601. };
  56602. /**
  56603. * Creates a sphere mesh.
  56604. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  56605. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  56606. * 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`).
  56607. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  56608. * 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
  56609. * 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).
  56610. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56611. * 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).
  56612. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56613. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56614. */
  56615. MeshBuilder.CreateSphere = function (name, options, scene) {
  56616. var sphere = new BABYLON.Mesh(name, scene);
  56617. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56618. sphere._originalBuilderSideOrientation = options.sideOrientation;
  56619. var vertexData = BABYLON.VertexData.CreateSphere(options);
  56620. vertexData.applyToMesh(sphere, options.updatable);
  56621. return sphere;
  56622. };
  56623. /**
  56624. * Creates a plane polygonal mesh. By default, this is a disc.
  56625. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  56626. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  56627. * 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.
  56628. * 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
  56629. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56630. * 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).
  56631. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56632. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56633. */
  56634. MeshBuilder.CreateDisc = function (name, options, scene) {
  56635. if (scene === void 0) { scene = null; }
  56636. var disc = new BABYLON.Mesh(name, scene);
  56637. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56638. disc._originalBuilderSideOrientation = options.sideOrientation;
  56639. var vertexData = BABYLON.VertexData.CreateDisc(options);
  56640. vertexData.applyToMesh(disc, options.updatable);
  56641. return disc;
  56642. };
  56643. /**
  56644. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  56645. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  56646. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  56647. * 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`).
  56648. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  56649. * 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.
  56650. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56651. * 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).
  56652. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56653. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56654. */
  56655. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  56656. var sphere = new BABYLON.Mesh(name, scene);
  56657. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56658. sphere._originalBuilderSideOrientation = options.sideOrientation;
  56659. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  56660. vertexData.applyToMesh(sphere, options.updatable);
  56661. return sphere;
  56662. };
  56663. ;
  56664. /**
  56665. * Creates a ribbon mesh.
  56666. * 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.
  56667. *
  56668. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  56669. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  56670. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  56671. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  56672. * 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.
  56673. * 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.
  56674. * 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
  56675. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56676. * 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).
  56677. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56678. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56679. * 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.
  56680. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  56681. * 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
  56682. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  56683. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  56684. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56685. */
  56686. MeshBuilder.CreateRibbon = function (name, options, scene) {
  56687. if (scene === void 0) { scene = null; }
  56688. var pathArray = options.pathArray;
  56689. var closeArray = options.closeArray;
  56690. var closePath = options.closePath;
  56691. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56692. var instance = options.instance;
  56693. var updatable = options.updatable;
  56694. if (instance) {
  56695. // positionFunction : ribbon case
  56696. // only pathArray and sideOrientation parameters are taken into account for positions update
  56697. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  56698. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  56699. var positionFunction = function (positions) {
  56700. var minlg = pathArray[0].length;
  56701. var i = 0;
  56702. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  56703. for (var si = 1; si <= ns; si++) {
  56704. for (var p = 0; p < pathArray.length; p++) {
  56705. var path = pathArray[p];
  56706. var l = path.length;
  56707. minlg = (minlg < l) ? minlg : l;
  56708. var j = 0;
  56709. while (j < minlg) {
  56710. positions[i] = path[j].x;
  56711. positions[i + 1] = path[j].y;
  56712. positions[i + 2] = path[j].z;
  56713. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  56714. BABYLON.Tmp.Vector3[0].x = path[j].x;
  56715. }
  56716. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  56717. BABYLON.Tmp.Vector3[1].x = path[j].x;
  56718. }
  56719. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  56720. BABYLON.Tmp.Vector3[0].y = path[j].y;
  56721. }
  56722. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  56723. BABYLON.Tmp.Vector3[1].y = path[j].y;
  56724. }
  56725. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  56726. BABYLON.Tmp.Vector3[0].z = path[j].z;
  56727. }
  56728. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  56729. BABYLON.Tmp.Vector3[1].z = path[j].z;
  56730. }
  56731. j++;
  56732. i += 3;
  56733. }
  56734. if (instance._closePath) {
  56735. positions[i] = path[0].x;
  56736. positions[i + 1] = path[0].y;
  56737. positions[i + 2] = path[0].z;
  56738. i += 3;
  56739. }
  56740. }
  56741. }
  56742. };
  56743. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56744. positionFunction(positions);
  56745. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  56746. instance._boundingInfo.update(instance._worldMatrix);
  56747. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  56748. if (options.colors) {
  56749. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56750. for (var c = 0; c < options.colors.length; c++) {
  56751. colors[c * 4] = options.colors[c].r;
  56752. colors[c * 4 + 1] = options.colors[c].g;
  56753. colors[c * 4 + 2] = options.colors[c].b;
  56754. colors[c * 4 + 3] = options.colors[c].a;
  56755. }
  56756. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  56757. }
  56758. if (options.uvs) {
  56759. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  56760. for (var i = 0; i < options.uvs.length; i++) {
  56761. uvs[i * 2] = options.uvs[i].x;
  56762. uvs[i * 2 + 1] = options.uvs[i].y;
  56763. }
  56764. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  56765. }
  56766. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  56767. var indices = instance.getIndices();
  56768. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56769. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  56770. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  56771. if (instance._closePath) {
  56772. var indexFirst = 0;
  56773. var indexLast = 0;
  56774. for (var p = 0; p < pathArray.length; p++) {
  56775. indexFirst = instance._idx[p] * 3;
  56776. if (p + 1 < pathArray.length) {
  56777. indexLast = (instance._idx[p + 1] - 1) * 3;
  56778. }
  56779. else {
  56780. indexLast = normals.length - 3;
  56781. }
  56782. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  56783. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  56784. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  56785. normals[indexLast] = normals[indexFirst];
  56786. normals[indexLast + 1] = normals[indexFirst + 1];
  56787. normals[indexLast + 2] = normals[indexFirst + 2];
  56788. }
  56789. }
  56790. if (!(instance.areNormalsFrozen)) {
  56791. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  56792. }
  56793. }
  56794. return instance;
  56795. }
  56796. else {
  56797. var ribbon = new BABYLON.Mesh(name, scene);
  56798. ribbon._originalBuilderSideOrientation = sideOrientation;
  56799. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  56800. if (closePath) {
  56801. ribbon._idx = vertexData._idx;
  56802. }
  56803. ribbon._closePath = closePath;
  56804. ribbon._closeArray = closeArray;
  56805. vertexData.applyToMesh(ribbon, updatable);
  56806. return ribbon;
  56807. }
  56808. };
  56809. /**
  56810. * Creates a cylinder or a cone mesh.
  56811. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  56812. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  56813. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  56814. * 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.
  56815. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  56816. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  56817. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  56818. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  56819. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  56820. * 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).
  56821. * 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
  56822. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  56823. * 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
  56824. * 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.
  56825. * If `enclose` is false, a ring surface is one element.
  56826. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  56827. * 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
  56828. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56829. * 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).
  56830. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56831. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56832. */
  56833. MeshBuilder.CreateCylinder = function (name, options, scene) {
  56834. var cylinder = new BABYLON.Mesh(name, scene);
  56835. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56836. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  56837. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  56838. vertexData.applyToMesh(cylinder, options.updatable);
  56839. return cylinder;
  56840. };
  56841. /**
  56842. * Creates a torus mesh.
  56843. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  56844. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  56845. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  56846. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  56847. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56848. * 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).
  56849. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56850. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56851. */
  56852. MeshBuilder.CreateTorus = function (name, options, scene) {
  56853. var torus = new BABYLON.Mesh(name, scene);
  56854. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56855. torus._originalBuilderSideOrientation = options.sideOrientation;
  56856. var vertexData = BABYLON.VertexData.CreateTorus(options);
  56857. vertexData.applyToMesh(torus, options.updatable);
  56858. return torus;
  56859. };
  56860. /**
  56861. * Creates a torus knot mesh.
  56862. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  56863. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  56864. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  56865. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  56866. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  56867. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56868. * 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).
  56869. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56870. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56871. */
  56872. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  56873. var torusKnot = new BABYLON.Mesh(name, scene);
  56874. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56875. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  56876. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  56877. vertexData.applyToMesh(torusKnot, options.updatable);
  56878. return torusKnot;
  56879. };
  56880. /**
  56881. * Creates a line system mesh.
  56882. * A line system is a pool of many lines gathered in a single mesh.
  56883. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  56884. * 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.
  56885. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  56886. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  56887. * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter. The way to update it is the same than for
  56888. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  56889. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  56890. * 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
  56891. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  56892. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56893. */
  56894. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  56895. var instance = options.instance;
  56896. var lines = options.lines;
  56897. var colors = options.colors;
  56898. if (instance) {
  56899. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56900. var vertexColor;
  56901. var lineColors;
  56902. if (colors) {
  56903. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56904. }
  56905. var i = 0;
  56906. var c = 0;
  56907. for (var l = 0; l < lines.length; l++) {
  56908. var points = lines[l];
  56909. for (var p = 0; p < points.length; p++) {
  56910. positions[i] = points[p].x;
  56911. positions[i + 1] = points[p].y;
  56912. positions[i + 2] = points[p].z;
  56913. if (colors && vertexColor) {
  56914. lineColors = colors[l];
  56915. vertexColor[c] = lineColors[p].r;
  56916. vertexColor[c + 1] = lineColors[p].g;
  56917. vertexColor[c + 2] = lineColors[p].b;
  56918. vertexColor[c + 3] = lineColors[p].a;
  56919. c += 4;
  56920. }
  56921. i += 3;
  56922. }
  56923. }
  56924. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  56925. if (colors && vertexColor) {
  56926. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  56927. }
  56928. return instance;
  56929. }
  56930. // line system creation
  56931. var useVertexColor = (colors) ? true : false;
  56932. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  56933. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  56934. vertexData.applyToMesh(lineSystem, options.updatable);
  56935. return lineSystem;
  56936. };
  56937. /**
  56938. * Creates a line mesh.
  56939. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  56940. * 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.
  56941. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  56942. * The parameter `points` is an array successive Vector3.
  56943. * 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
  56944. * The optional parameter `colors` is an array of successive Color4, one per line point.
  56945. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  56946. * When updating an instance, remember that only point positions can change, not the number of points.
  56947. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56948. */
  56949. MeshBuilder.CreateLines = function (name, options, scene) {
  56950. if (scene === void 0) { scene = null; }
  56951. var colors = (options.colors) ? [options.colors] : null;
  56952. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  56953. return lines;
  56954. };
  56955. /**
  56956. * Creates a dashed line mesh.
  56957. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  56958. * 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.
  56959. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  56960. * The parameter `points` is an array successive Vector3.
  56961. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  56962. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  56963. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  56964. * 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
  56965. * When updating an instance, remember that only point positions can change, not the number of points.
  56966. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56967. */
  56968. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  56969. if (scene === void 0) { scene = null; }
  56970. var points = options.points;
  56971. var instance = options.instance;
  56972. var gapSize = options.gapSize || 1;
  56973. var dashSize = options.dashSize || 3;
  56974. if (instance) {
  56975. var positionFunction = function (positions) {
  56976. var curvect = BABYLON.Vector3.Zero();
  56977. var nbSeg = positions.length / 6;
  56978. var lg = 0;
  56979. var nb = 0;
  56980. var shft = 0;
  56981. var dashshft = 0;
  56982. var curshft = 0;
  56983. var p = 0;
  56984. var i = 0;
  56985. var j = 0;
  56986. for (i = 0; i < points.length - 1; i++) {
  56987. points[i + 1].subtractToRef(points[i], curvect);
  56988. lg += curvect.length();
  56989. }
  56990. shft = lg / nbSeg;
  56991. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  56992. for (i = 0; i < points.length - 1; i++) {
  56993. points[i + 1].subtractToRef(points[i], curvect);
  56994. nb = Math.floor(curvect.length() / shft);
  56995. curvect.normalize();
  56996. j = 0;
  56997. while (j < nb && p < positions.length) {
  56998. curshft = shft * j;
  56999. positions[p] = points[i].x + curshft * curvect.x;
  57000. positions[p + 1] = points[i].y + curshft * curvect.y;
  57001. positions[p + 2] = points[i].z + curshft * curvect.z;
  57002. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  57003. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  57004. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  57005. p += 6;
  57006. j++;
  57007. }
  57008. }
  57009. while (p < positions.length) {
  57010. positions[p] = points[i].x;
  57011. positions[p + 1] = points[i].y;
  57012. positions[p + 2] = points[i].z;
  57013. p += 3;
  57014. }
  57015. };
  57016. instance.updateMeshPositions(positionFunction, false);
  57017. return instance;
  57018. }
  57019. // dashed lines creation
  57020. var dashedLines = new BABYLON.LinesMesh(name, scene);
  57021. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  57022. vertexData.applyToMesh(dashedLines, options.updatable);
  57023. dashedLines.dashSize = dashSize;
  57024. dashedLines.gapSize = gapSize;
  57025. return dashedLines;
  57026. };
  57027. /**
  57028. * Creates an extruded shape mesh.
  57029. * 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.
  57030. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  57031. *
  57032. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  57033. * 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
  57034. * extruded along the Z axis.
  57035. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  57036. * 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.
  57037. * The parameter `scale` (float, default 1) is the value to scale the shape.
  57038. * 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
  57039. * 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
  57040. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  57041. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57042. * 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).
  57043. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57044. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  57045. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57046. */
  57047. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  57048. if (scene === void 0) { scene = null; }
  57049. var path = options.path;
  57050. var shape = options.shape;
  57051. var scale = options.scale || 1;
  57052. var rotation = options.rotation || 0;
  57053. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  57054. var updatable = options.updatable;
  57055. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57056. var instance = options.instance || null;
  57057. var invertUV = options.invertUV || false;
  57058. 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);
  57059. };
  57060. /**
  57061. * Creates an custom extruded shape mesh.
  57062. * 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.
  57063. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  57064. *
  57065. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  57066. * 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
  57067. * extruded along the Z axis.
  57068. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  57069. * 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
  57070. * and the distance of this point from the begining of the path :
  57071. * ```javascript
  57072. * var rotationFunction = function(i, distance) {
  57073. * // do things
  57074. * return rotationValue; }
  57075. * ```
  57076. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  57077. * 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
  57078. * and the distance of this point from the begining of the path :
  57079. * ```javascript
  57080. * var scaleFunction = function(i, distance) {
  57081. * // do things
  57082. * return scaleValue;}
  57083. * ```
  57084. * It must returns a float value that will be the scale value applied to the shape on each path point.
  57085. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  57086. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  57087. * 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
  57088. * 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
  57089. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  57090. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57091. * 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).
  57092. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57093. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  57094. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57095. */
  57096. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  57097. var path = options.path;
  57098. var shape = options.shape;
  57099. var scaleFunction = options.scaleFunction || (function () { return 1; });
  57100. var rotationFunction = options.rotationFunction || (function () { return 0; });
  57101. var ribbonCloseArray = options.ribbonCloseArray || false;
  57102. var ribbonClosePath = options.ribbonClosePath || false;
  57103. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  57104. var updatable = options.updatable;
  57105. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57106. var instance = options.instance;
  57107. var invertUV = options.invertUV || false;
  57108. 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);
  57109. };
  57110. /**
  57111. * Creates lathe mesh.
  57112. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  57113. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  57114. *
  57115. * 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
  57116. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  57117. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  57118. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  57119. * 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.
  57120. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  57121. * 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
  57122. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57123. * 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).
  57124. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57125. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  57126. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57127. */
  57128. MeshBuilder.CreateLathe = function (name, options, scene) {
  57129. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  57130. var closed = (options.closed === undefined) ? true : options.closed;
  57131. var shape = options.shape;
  57132. var radius = options.radius || 1;
  57133. var tessellation = options.tessellation || 64;
  57134. var updatable = options.updatable;
  57135. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57136. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  57137. var pi2 = Math.PI * 2;
  57138. var paths = new Array();
  57139. var invertUV = options.invertUV || false;
  57140. var i = 0;
  57141. var p = 0;
  57142. var step = pi2 / tessellation * arc;
  57143. var rotated;
  57144. var path = new Array();
  57145. ;
  57146. for (i = 0; i <= tessellation; i++) {
  57147. var path = [];
  57148. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  57149. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  57150. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  57151. }
  57152. for (p = 0; p < shape.length; p++) {
  57153. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  57154. path.push(rotated);
  57155. }
  57156. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  57157. 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));
  57158. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  57159. }
  57160. paths.push(path);
  57161. }
  57162. // lathe ribbon
  57163. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  57164. return lathe;
  57165. };
  57166. /**
  57167. * Creates a plane mesh.
  57168. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  57169. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  57170. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  57171. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  57172. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57173. * 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).
  57174. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57175. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57176. */
  57177. MeshBuilder.CreatePlane = function (name, options, scene) {
  57178. var plane = new BABYLON.Mesh(name, scene);
  57179. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57180. plane._originalBuilderSideOrientation = options.sideOrientation;
  57181. var vertexData = BABYLON.VertexData.CreatePlane(options);
  57182. vertexData.applyToMesh(plane, options.updatable);
  57183. if (options.sourcePlane) {
  57184. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  57185. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  57186. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  57187. plane.rotate(vectorProduct, product);
  57188. }
  57189. return plane;
  57190. };
  57191. /**
  57192. * Creates a ground mesh.
  57193. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  57194. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  57195. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  57196. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57197. */
  57198. MeshBuilder.CreateGround = function (name, options, scene) {
  57199. var ground = new BABYLON.GroundMesh(name, scene);
  57200. ground._setReady(false);
  57201. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  57202. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  57203. ground._width = options.width || 1;
  57204. ground._height = options.height || 1;
  57205. ground._maxX = ground._width / 2;
  57206. ground._maxZ = ground._height / 2;
  57207. ground._minX = -ground._maxX;
  57208. ground._minZ = -ground._maxZ;
  57209. var vertexData = BABYLON.VertexData.CreateGround(options);
  57210. vertexData.applyToMesh(ground, options.updatable);
  57211. ground._setReady(true);
  57212. return ground;
  57213. };
  57214. /**
  57215. * Creates a tiled ground mesh.
  57216. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  57217. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  57218. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  57219. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  57220. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  57221. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  57222. * numbers of subdivisions on the ground width and height of each tile.
  57223. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57224. */
  57225. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  57226. var tiledGround = new BABYLON.Mesh(name, scene);
  57227. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  57228. vertexData.applyToMesh(tiledGround, options.updatable);
  57229. return tiledGround;
  57230. };
  57231. /**
  57232. * Creates a ground mesh from a height map.
  57233. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  57234. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  57235. * The parameter `url` sets the URL of the height map image resource.
  57236. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  57237. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  57238. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  57239. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  57240. * 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.
  57241. * 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).
  57242. * This function is passed the newly built mesh :
  57243. * ```javascript
  57244. * function(mesh) { // do things
  57245. * return; }
  57246. * ```
  57247. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57248. */
  57249. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  57250. var width = options.width || 10.0;
  57251. var height = options.height || 10.0;
  57252. var subdivisions = options.subdivisions || 1 | 0;
  57253. var minHeight = options.minHeight || 0.0;
  57254. var maxHeight = options.maxHeight || 1.0;
  57255. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  57256. var updatable = options.updatable;
  57257. var onReady = options.onReady;
  57258. var ground = new BABYLON.GroundMesh(name, scene);
  57259. ground._subdivisionsX = subdivisions;
  57260. ground._subdivisionsY = subdivisions;
  57261. ground._width = width;
  57262. ground._height = height;
  57263. ground._maxX = ground._width / 2.0;
  57264. ground._maxZ = ground._height / 2.0;
  57265. ground._minX = -ground._maxX;
  57266. ground._minZ = -ground._maxZ;
  57267. ground._setReady(false);
  57268. var onload = function (img) {
  57269. // Getting height map data
  57270. var canvas = document.createElement("canvas");
  57271. var context = canvas.getContext("2d");
  57272. if (!context) {
  57273. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  57274. }
  57275. if (scene.isDisposed) {
  57276. return;
  57277. }
  57278. var bufferWidth = img.width;
  57279. var bufferHeight = img.height;
  57280. canvas.width = bufferWidth;
  57281. canvas.height = bufferHeight;
  57282. context.drawImage(img, 0, 0);
  57283. // Create VertexData from map data
  57284. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  57285. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  57286. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  57287. width: width, height: height,
  57288. subdivisions: subdivisions,
  57289. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  57290. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  57291. });
  57292. vertexData.applyToMesh(ground, updatable);
  57293. //execute ready callback, if set
  57294. if (onReady) {
  57295. onReady(ground);
  57296. }
  57297. ground._setReady(true);
  57298. };
  57299. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  57300. return ground;
  57301. };
  57302. /**
  57303. * Creates a polygon mesh.
  57304. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  57305. * 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.
  57306. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57307. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57308. * 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).
  57309. * Remember you can only change the shape positions, not their number when updating a polygon.
  57310. */
  57311. MeshBuilder.CreatePolygon = function (name, options, scene) {
  57312. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57313. var shape = options.shape;
  57314. var holes = options.holes || [];
  57315. var depth = options.depth || 0;
  57316. var contours = [];
  57317. var hole = [];
  57318. for (var i = 0; i < shape.length; i++) {
  57319. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  57320. }
  57321. var epsilon = 0.00000001;
  57322. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  57323. contours.pop();
  57324. }
  57325. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  57326. for (var hNb = 0; hNb < holes.length; hNb++) {
  57327. hole = [];
  57328. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  57329. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  57330. }
  57331. polygonTriangulation.addHole(hole);
  57332. }
  57333. var polygon = polygonTriangulation.build(options.updatable, depth);
  57334. polygon._originalBuilderSideOrientation = options.sideOrientation;
  57335. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  57336. vertexData.applyToMesh(polygon, options.updatable);
  57337. return polygon;
  57338. };
  57339. ;
  57340. /**
  57341. * Creates an extruded polygon mesh, with depth in the Y direction.
  57342. * 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).
  57343. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  57344. */
  57345. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  57346. return MeshBuilder.CreatePolygon(name, options, scene);
  57347. };
  57348. ;
  57349. /**
  57350. * Creates a tube mesh.
  57351. * 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.
  57352. *
  57353. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  57354. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  57355. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  57356. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  57357. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  57358. * 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.
  57359. * It must return a radius value (positive float) :
  57360. * ```javascript
  57361. * var radiusFunction = function(i, distance) {
  57362. * // do things
  57363. * return radius; }
  57364. * ```
  57365. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  57366. * 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
  57367. * 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
  57368. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57369. * 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).
  57370. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57371. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  57372. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57373. */
  57374. MeshBuilder.CreateTube = function (name, options, scene) {
  57375. var path = options.path;
  57376. var instance = options.instance;
  57377. var radius = 1.0;
  57378. if (instance) {
  57379. radius = instance.radius;
  57380. }
  57381. if (options.radius !== undefined) {
  57382. radius = options.radius;
  57383. }
  57384. ;
  57385. var tessellation = options.tessellation || 64 | 0;
  57386. var radiusFunction = options.radiusFunction || null;
  57387. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  57388. var invertUV = options.invertUV || false;
  57389. var updatable = options.updatable;
  57390. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57391. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  57392. // tube geometry
  57393. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  57394. var tangents = path3D.getTangents();
  57395. var normals = path3D.getNormals();
  57396. var distances = path3D.getDistances();
  57397. var pi2 = Math.PI * 2;
  57398. var step = pi2 / tessellation * arc;
  57399. var returnRadius = function () { return radius; };
  57400. var radiusFunctionFinal = radiusFunction || returnRadius;
  57401. var circlePath;
  57402. var rad;
  57403. var normal;
  57404. var rotated;
  57405. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  57406. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  57407. for (var i = 0; i < path.length; i++) {
  57408. rad = radiusFunctionFinal(i, distances[i]); // current radius
  57409. circlePath = Array(); // current circle array
  57410. normal = normals[i]; // current normal
  57411. for (var t = 0; t < tessellation; t++) {
  57412. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  57413. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  57414. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  57415. rotated.scaleInPlace(rad).addInPlace(path[i]);
  57416. circlePath[t] = rotated;
  57417. }
  57418. circlePaths[index] = circlePath;
  57419. index++;
  57420. }
  57421. // cap
  57422. var capPath = function (nbPoints, pathIndex) {
  57423. var pointCap = Array();
  57424. for (var i = 0; i < nbPoints; i++) {
  57425. pointCap.push(path[pathIndex]);
  57426. }
  57427. return pointCap;
  57428. };
  57429. switch (cap) {
  57430. case BABYLON.Mesh.NO_CAP:
  57431. break;
  57432. case BABYLON.Mesh.CAP_START:
  57433. circlePaths[0] = capPath(tessellation, 0);
  57434. circlePaths[1] = circlePaths[2].slice(0);
  57435. break;
  57436. case BABYLON.Mesh.CAP_END:
  57437. circlePaths[index] = circlePaths[index - 1].slice(0);
  57438. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  57439. break;
  57440. case BABYLON.Mesh.CAP_ALL:
  57441. circlePaths[0] = capPath(tessellation, 0);
  57442. circlePaths[1] = circlePaths[2].slice(0);
  57443. circlePaths[index] = circlePaths[index - 1].slice(0);
  57444. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  57445. break;
  57446. default:
  57447. break;
  57448. }
  57449. return circlePaths;
  57450. };
  57451. var path3D;
  57452. var pathArray;
  57453. if (instance) {
  57454. var arc = options.arc || instance.arc;
  57455. path3D = (instance.path3D).update(path);
  57456. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  57457. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  57458. instance.path3D = path3D;
  57459. instance.pathArray = pathArray;
  57460. instance.arc = arc;
  57461. instance.radius = radius;
  57462. return instance;
  57463. }
  57464. // tube creation
  57465. path3D = new BABYLON.Path3D(path);
  57466. var newPathArray = new Array();
  57467. cap = (cap < 0 || cap > 3) ? 0 : cap;
  57468. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  57469. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  57470. tube.pathArray = pathArray;
  57471. tube.path3D = path3D;
  57472. tube.tessellation = tessellation;
  57473. tube.cap = cap;
  57474. tube.arc = options.arc;
  57475. tube.radius = radius;
  57476. return tube;
  57477. };
  57478. /**
  57479. * Creates a polyhedron mesh.
  57480. *
  57481. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  57482. * 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
  57483. * to choose the wanted type.
  57484. * The parameter `size` (positive float, default 1) sets the polygon size.
  57485. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  57486. * 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`.
  57487. * 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
  57488. * 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)`).
  57489. * 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
  57490. * 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.
  57491. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57492. * 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).
  57493. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57494. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57495. */
  57496. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  57497. var polyhedron = new BABYLON.Mesh(name, scene);
  57498. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57499. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  57500. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  57501. vertexData.applyToMesh(polyhedron, options.updatable);
  57502. return polyhedron;
  57503. };
  57504. /**
  57505. * Creates a decal mesh.
  57506. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  57507. * 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.
  57508. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  57509. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  57510. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  57511. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  57512. */
  57513. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  57514. var indices = sourceMesh.getIndices();
  57515. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57516. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57517. var position = options.position || BABYLON.Vector3.Zero();
  57518. var normal = options.normal || BABYLON.Vector3.Up();
  57519. var size = options.size || BABYLON.Vector3.One();
  57520. var angle = options.angle || 0;
  57521. // Getting correct rotation
  57522. if (!normal) {
  57523. var target = new BABYLON.Vector3(0, 0, 1);
  57524. var camera = sourceMesh.getScene().activeCamera;
  57525. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  57526. normal = camera.globalPosition.subtract(cameraWorldTarget);
  57527. }
  57528. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  57529. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  57530. var pitch = Math.atan2(normal.y, len);
  57531. // Matrix
  57532. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  57533. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  57534. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  57535. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  57536. var vertexData = new BABYLON.VertexData();
  57537. vertexData.indices = [];
  57538. vertexData.positions = [];
  57539. vertexData.normals = [];
  57540. vertexData.uvs = [];
  57541. var currentVertexDataIndex = 0;
  57542. var extractDecalVector3 = function (indexId) {
  57543. var result = new BABYLON.PositionNormalVertex();
  57544. if (!indices || !positions || !normals) {
  57545. return result;
  57546. }
  57547. var vertexId = indices[indexId];
  57548. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  57549. // Send vector to decal local world
  57550. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  57551. // Get normal
  57552. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  57553. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  57554. return result;
  57555. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  57556. var clip = function (vertices, axis) {
  57557. if (vertices.length === 0) {
  57558. return vertices;
  57559. }
  57560. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  57561. var clipVertices = function (v0, v1) {
  57562. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  57563. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  57564. };
  57565. var result = new Array();
  57566. for (var index = 0; index < vertices.length; index += 3) {
  57567. var v1Out;
  57568. var v2Out;
  57569. var v3Out;
  57570. var total = 0;
  57571. var nV1 = null;
  57572. var nV2 = null;
  57573. var nV3 = null;
  57574. var nV4 = null;
  57575. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  57576. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  57577. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  57578. v1Out = d1 > 0;
  57579. v2Out = d2 > 0;
  57580. v3Out = d3 > 0;
  57581. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  57582. switch (total) {
  57583. case 0:
  57584. result.push(vertices[index]);
  57585. result.push(vertices[index + 1]);
  57586. result.push(vertices[index + 2]);
  57587. break;
  57588. case 1:
  57589. if (v1Out) {
  57590. nV1 = vertices[index + 1];
  57591. nV2 = vertices[index + 2];
  57592. nV3 = clipVertices(vertices[index], nV1);
  57593. nV4 = clipVertices(vertices[index], nV2);
  57594. }
  57595. if (v2Out) {
  57596. nV1 = vertices[index];
  57597. nV2 = vertices[index + 2];
  57598. nV3 = clipVertices(vertices[index + 1], nV1);
  57599. nV4 = clipVertices(vertices[index + 1], nV2);
  57600. result.push(nV3);
  57601. result.push(nV2.clone());
  57602. result.push(nV1.clone());
  57603. result.push(nV2.clone());
  57604. result.push(nV3.clone());
  57605. result.push(nV4);
  57606. break;
  57607. }
  57608. if (v3Out) {
  57609. nV1 = vertices[index];
  57610. nV2 = vertices[index + 1];
  57611. nV3 = clipVertices(vertices[index + 2], nV1);
  57612. nV4 = clipVertices(vertices[index + 2], nV2);
  57613. }
  57614. if (nV1 && nV2 && nV3 && nV4) {
  57615. result.push(nV1.clone());
  57616. result.push(nV2.clone());
  57617. result.push(nV3);
  57618. result.push(nV4);
  57619. result.push(nV3.clone());
  57620. result.push(nV2.clone());
  57621. }
  57622. break;
  57623. case 2:
  57624. if (!v1Out) {
  57625. nV1 = vertices[index].clone();
  57626. nV2 = clipVertices(nV1, vertices[index + 1]);
  57627. nV3 = clipVertices(nV1, vertices[index + 2]);
  57628. result.push(nV1);
  57629. result.push(nV2);
  57630. result.push(nV3);
  57631. }
  57632. if (!v2Out) {
  57633. nV1 = vertices[index + 1].clone();
  57634. nV2 = clipVertices(nV1, vertices[index + 2]);
  57635. nV3 = clipVertices(nV1, vertices[index]);
  57636. result.push(nV1);
  57637. result.push(nV2);
  57638. result.push(nV3);
  57639. }
  57640. if (!v3Out) {
  57641. nV1 = vertices[index + 2].clone();
  57642. nV2 = clipVertices(nV1, vertices[index]);
  57643. nV3 = clipVertices(nV1, vertices[index + 1]);
  57644. result.push(nV1);
  57645. result.push(nV2);
  57646. result.push(nV3);
  57647. }
  57648. break;
  57649. case 3:
  57650. break;
  57651. }
  57652. }
  57653. return result;
  57654. };
  57655. for (var index = 0; index < indices.length; index += 3) {
  57656. var faceVertices = new Array();
  57657. faceVertices.push(extractDecalVector3(index));
  57658. faceVertices.push(extractDecalVector3(index + 1));
  57659. faceVertices.push(extractDecalVector3(index + 2));
  57660. // Clip
  57661. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  57662. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  57663. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  57664. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  57665. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  57666. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  57667. if (faceVertices.length === 0) {
  57668. continue;
  57669. }
  57670. // Add UVs and get back to world
  57671. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  57672. var vertex = faceVertices[vIndex];
  57673. //TODO check for Int32Array | Uint32Array | Uint16Array
  57674. vertexData.indices.push(currentVertexDataIndex);
  57675. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  57676. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  57677. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  57678. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  57679. currentVertexDataIndex++;
  57680. }
  57681. }
  57682. // Return mesh
  57683. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  57684. vertexData.applyToMesh(decal);
  57685. decal.position = position.clone();
  57686. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  57687. return decal;
  57688. };
  57689. // Privates
  57690. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  57691. // extrusion geometry
  57692. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  57693. var tangents = path3D.getTangents();
  57694. var normals = path3D.getNormals();
  57695. var binormals = path3D.getBinormals();
  57696. var distances = path3D.getDistances();
  57697. var angle = 0;
  57698. var returnScale = function () { return scale !== null ? scale : 1; };
  57699. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  57700. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  57701. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  57702. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  57703. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  57704. for (var i = 0; i < curve.length; i++) {
  57705. var shapePath = new Array();
  57706. var angleStep = rotate(i, distances[i]);
  57707. var scaleRatio = scl(i, distances[i]);
  57708. for (var p = 0; p < shape.length; p++) {
  57709. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  57710. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  57711. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  57712. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  57713. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  57714. shapePath[p] = rotated;
  57715. }
  57716. shapePaths[index] = shapePath;
  57717. angle += angleStep;
  57718. index++;
  57719. }
  57720. // cap
  57721. var capPath = function (shapePath) {
  57722. var pointCap = Array();
  57723. var barycenter = BABYLON.Vector3.Zero();
  57724. var i;
  57725. for (i = 0; i < shapePath.length; i++) {
  57726. barycenter.addInPlace(shapePath[i]);
  57727. }
  57728. barycenter.scaleInPlace(1.0 / shapePath.length);
  57729. for (i = 0; i < shapePath.length; i++) {
  57730. pointCap.push(barycenter);
  57731. }
  57732. return pointCap;
  57733. };
  57734. switch (cap) {
  57735. case BABYLON.Mesh.NO_CAP:
  57736. break;
  57737. case BABYLON.Mesh.CAP_START:
  57738. shapePaths[0] = capPath(shapePaths[2]);
  57739. shapePaths[1] = shapePaths[2];
  57740. break;
  57741. case BABYLON.Mesh.CAP_END:
  57742. shapePaths[index] = shapePaths[index - 1];
  57743. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  57744. break;
  57745. case BABYLON.Mesh.CAP_ALL:
  57746. shapePaths[0] = capPath(shapePaths[2]);
  57747. shapePaths[1] = shapePaths[2];
  57748. shapePaths[index] = shapePaths[index - 1];
  57749. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  57750. break;
  57751. default:
  57752. break;
  57753. }
  57754. return shapePaths;
  57755. };
  57756. var path3D;
  57757. var pathArray;
  57758. if (instance) {
  57759. path3D = (instance.path3D).update(curve);
  57760. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  57761. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  57762. return instance;
  57763. }
  57764. // extruded shape creation
  57765. path3D = new BABYLON.Path3D(curve);
  57766. var newShapePaths = new Array();
  57767. cap = (cap < 0 || cap > 3) ? 0 : cap;
  57768. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  57769. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  57770. extrudedGeneric.pathArray = pathArray;
  57771. extrudedGeneric.path3D = path3D;
  57772. extrudedGeneric.cap = cap;
  57773. return extrudedGeneric;
  57774. };
  57775. return MeshBuilder;
  57776. }());
  57777. BABYLON.MeshBuilder = MeshBuilder;
  57778. })(BABYLON || (BABYLON = {}));
  57779. //# sourceMappingURL=babylon.meshBuilder.js.map
  57780. "use strict";
  57781. var BABYLON;
  57782. (function (BABYLON) {
  57783. /**
  57784. * Draco compression (https://google.github.io/draco/)
  57785. */
  57786. var DracoCompression = /** @class */ (function () {
  57787. /**
  57788. * Constructor
  57789. * @param numWorkers The number of workers for async operations
  57790. */
  57791. function DracoCompression(numWorkers) {
  57792. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  57793. var workerBlobUrl = URL && URL.createObjectURL && URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  57794. if (!workerBlobUrl || !Worker) {
  57795. BABYLON.Tools.Error("Draco Compression disabled. The current context doesn't support worker creation or URL.createObjectURL");
  57796. return;
  57797. }
  57798. var workers = new Array(numWorkers);
  57799. for (var i = 0; i < workers.length; i++) {
  57800. var worker = new Worker(workerBlobUrl);
  57801. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  57802. workers[i] = worker;
  57803. }
  57804. this._workerPool = new BABYLON.WorkerPool(workers);
  57805. }
  57806. /**
  57807. * Stop all async operations and release resources.
  57808. */
  57809. DracoCompression.prototype.dispose = function () {
  57810. this._workerPool.dispose();
  57811. delete this._workerPool;
  57812. };
  57813. /**
  57814. * Decode Draco compressed mesh data to vertex data.
  57815. * @param data The array buffer view for the Draco compression data
  57816. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  57817. * @returns A promise that resolves with the decoded vertex data
  57818. */
  57819. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  57820. var _this = this;
  57821. return new Promise(function (resolve, reject) {
  57822. _this._workerPool.push(function (worker, onComplete) {
  57823. var vertexData = new BABYLON.VertexData();
  57824. var onError = function (error) {
  57825. worker.removeEventListener("error", onError);
  57826. worker.removeEventListener("message", onMessage);
  57827. reject(error);
  57828. onComplete();
  57829. };
  57830. var onMessage = function (message) {
  57831. if (message.data === "done") {
  57832. worker.removeEventListener("error", onError);
  57833. worker.removeEventListener("message", onMessage);
  57834. resolve(vertexData);
  57835. onComplete();
  57836. }
  57837. else if (message.data.id === "indices") {
  57838. vertexData.indices = message.data.value;
  57839. }
  57840. else {
  57841. vertexData.set(message.data.value, message.data.id);
  57842. }
  57843. };
  57844. worker.addEventListener("error", onError);
  57845. worker.addEventListener("message", onMessage);
  57846. var dataCopy = new Uint8Array(data.byteLength);
  57847. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  57848. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  57849. });
  57850. });
  57851. };
  57852. /**
  57853. * The worker function that gets converted to a blob url to pass into a worker.
  57854. */
  57855. DracoCompression._Worker = function () {
  57856. // self is actually a DedicatedWorkerGlobalScope
  57857. var _self = self;
  57858. var decodeMesh = function (data, attributes) {
  57859. var dracoModule = new DracoDecoderModule();
  57860. var buffer = new dracoModule.DecoderBuffer();
  57861. buffer.Init(data, data.byteLength);
  57862. var decoder = new dracoModule.Decoder();
  57863. var geometry;
  57864. var status;
  57865. try {
  57866. var type = decoder.GetEncodedGeometryType(buffer);
  57867. switch (type) {
  57868. case dracoModule.TRIANGULAR_MESH:
  57869. geometry = new dracoModule.Mesh();
  57870. status = decoder.DecodeBufferToMesh(buffer, geometry);
  57871. break;
  57872. case dracoModule.POINT_CLOUD:
  57873. geometry = new dracoModule.PointCloud();
  57874. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  57875. break;
  57876. default:
  57877. throw new Error("Invalid geometry type " + type);
  57878. }
  57879. if (!status.ok() || !geometry.ptr) {
  57880. throw new Error(status.error_msg());
  57881. }
  57882. var numPoints = geometry.num_points();
  57883. if (type === dracoModule.TRIANGULAR_MESH) {
  57884. var numFaces = geometry.num_faces();
  57885. var faceIndices = new dracoModule.DracoInt32Array();
  57886. try {
  57887. var indices = new Uint32Array(numFaces * 3);
  57888. for (var i = 0; i < numFaces; i++) {
  57889. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  57890. var offset = i * 3;
  57891. indices[offset + 0] = faceIndices.GetValue(0);
  57892. indices[offset + 1] = faceIndices.GetValue(1);
  57893. indices[offset + 2] = faceIndices.GetValue(2);
  57894. }
  57895. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  57896. }
  57897. finally {
  57898. dracoModule.destroy(faceIndices);
  57899. }
  57900. }
  57901. for (var kind in attributes) {
  57902. var uniqueId = attributes[kind];
  57903. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  57904. var dracoData = new dracoModule.DracoFloat32Array();
  57905. try {
  57906. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  57907. var babylonData = new Float32Array(numPoints * attribute.num_components());
  57908. for (var i = 0; i < babylonData.length; i++) {
  57909. babylonData[i] = dracoData.GetValue(i);
  57910. }
  57911. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  57912. }
  57913. finally {
  57914. dracoModule.destroy(dracoData);
  57915. }
  57916. }
  57917. }
  57918. finally {
  57919. if (geometry) {
  57920. dracoModule.destroy(geometry);
  57921. }
  57922. dracoModule.destroy(decoder);
  57923. dracoModule.destroy(buffer);
  57924. }
  57925. _self.postMessage("done");
  57926. };
  57927. _self.onmessage = function (event) {
  57928. switch (event.data.id) {
  57929. case "initDecoder": {
  57930. importScripts(event.data.url);
  57931. break;
  57932. }
  57933. case "decodeMesh": {
  57934. decodeMesh(event.data.data, event.data.attributes);
  57935. break;
  57936. }
  57937. }
  57938. };
  57939. };
  57940. DracoCompression._GetDefaultDecoderUrl = function () {
  57941. if (!BABYLON.Tools.IsWindowObjectExist()) {
  57942. return null;
  57943. }
  57944. for (var i = 0; i < document.scripts.length; i++) {
  57945. if (document.scripts[i].type === "text/x-draco-decoder") {
  57946. return document.scripts[i].src;
  57947. }
  57948. }
  57949. return null;
  57950. };
  57951. /**
  57952. * Gets the url to the draco decoder if available.
  57953. */
  57954. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  57955. return DracoCompression;
  57956. }());
  57957. BABYLON.DracoCompression = DracoCompression;
  57958. })(BABYLON || (BABYLON = {}));
  57959. //# sourceMappingURL=babylon.dracoCompression.js.map
  57960. "use strict";
  57961. var BABYLON;
  57962. (function (BABYLON) {
  57963. var AudioEngine = /** @class */ (function () {
  57964. function AudioEngine() {
  57965. this._audioContext = null;
  57966. this._audioContextInitialized = false;
  57967. this.canUseWebAudio = false;
  57968. this.WarnedWebAudioUnsupported = false;
  57969. this.unlocked = false;
  57970. this.isMP3supported = false;
  57971. this.isOGGsupported = false;
  57972. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  57973. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  57974. this.canUseWebAudio = true;
  57975. }
  57976. var audioElem = document.createElement('audio');
  57977. try {
  57978. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  57979. this.isMP3supported = true;
  57980. }
  57981. }
  57982. catch (e) {
  57983. // protect error during capability check.
  57984. }
  57985. try {
  57986. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  57987. this.isOGGsupported = true;
  57988. }
  57989. }
  57990. catch (e) {
  57991. // protect error during capability check.
  57992. }
  57993. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  57994. this._unlockiOSaudio();
  57995. }
  57996. else {
  57997. this.unlocked = true;
  57998. }
  57999. }
  58000. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  58001. get: function () {
  58002. if (!this._audioContextInitialized) {
  58003. this._initializeAudioContext();
  58004. }
  58005. return this._audioContext;
  58006. },
  58007. enumerable: true,
  58008. configurable: true
  58009. });
  58010. AudioEngine.prototype._unlockiOSaudio = function () {
  58011. var _this = this;
  58012. var unlockaudio = function () {
  58013. if (!_this.audioContext) {
  58014. return;
  58015. }
  58016. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  58017. var source = _this.audioContext.createBufferSource();
  58018. source.buffer = buffer;
  58019. source.connect(_this.audioContext.destination);
  58020. source.start(0);
  58021. setTimeout(function () {
  58022. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  58023. _this.unlocked = true;
  58024. window.removeEventListener('touchend', unlockaudio, false);
  58025. if (_this.onAudioUnlocked) {
  58026. _this.onAudioUnlocked();
  58027. }
  58028. }
  58029. }, 0);
  58030. };
  58031. window.addEventListener('touchend', unlockaudio, false);
  58032. };
  58033. AudioEngine.prototype._initializeAudioContext = function () {
  58034. try {
  58035. if (this.canUseWebAudio) {
  58036. this._audioContext = new AudioContext();
  58037. // create a global volume gain node
  58038. this.masterGain = this._audioContext.createGain();
  58039. this.masterGain.gain.value = 1;
  58040. this.masterGain.connect(this._audioContext.destination);
  58041. this._audioContextInitialized = true;
  58042. }
  58043. }
  58044. catch (e) {
  58045. this.canUseWebAudio = false;
  58046. BABYLON.Tools.Error("Web Audio: " + e.message);
  58047. }
  58048. };
  58049. AudioEngine.prototype.dispose = function () {
  58050. if (this.canUseWebAudio && this._audioContextInitialized) {
  58051. if (this._connectedAnalyser && this._audioContext) {
  58052. this._connectedAnalyser.stopDebugCanvas();
  58053. this._connectedAnalyser.dispose();
  58054. this.masterGain.disconnect();
  58055. this.masterGain.connect(this._audioContext.destination);
  58056. this._connectedAnalyser = null;
  58057. }
  58058. this.masterGain.gain.value = 1;
  58059. }
  58060. this.WarnedWebAudioUnsupported = false;
  58061. };
  58062. AudioEngine.prototype.getGlobalVolume = function () {
  58063. if (this.canUseWebAudio && this._audioContextInitialized) {
  58064. return this.masterGain.gain.value;
  58065. }
  58066. else {
  58067. return -1;
  58068. }
  58069. };
  58070. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  58071. if (this.canUseWebAudio && this._audioContextInitialized) {
  58072. this.masterGain.gain.value = newVolume;
  58073. }
  58074. };
  58075. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  58076. if (this._connectedAnalyser) {
  58077. this._connectedAnalyser.stopDebugCanvas();
  58078. }
  58079. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  58080. this._connectedAnalyser = analyser;
  58081. this.masterGain.disconnect();
  58082. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  58083. }
  58084. };
  58085. return AudioEngine;
  58086. }());
  58087. BABYLON.AudioEngine = AudioEngine;
  58088. })(BABYLON || (BABYLON = {}));
  58089. //# sourceMappingURL=babylon.audioEngine.js.map
  58090. "use strict";
  58091. var BABYLON;
  58092. (function (BABYLON) {
  58093. var Sound = /** @class */ (function () {
  58094. /**
  58095. * Create a sound and attach it to a scene
  58096. * @param name Name of your sound
  58097. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  58098. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  58099. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  58100. */
  58101. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  58102. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  58103. var _this = this;
  58104. this.autoplay = false;
  58105. this.loop = false;
  58106. this.useCustomAttenuation = false;
  58107. this.spatialSound = false;
  58108. this.refDistance = 1;
  58109. this.rolloffFactor = 1;
  58110. this.maxDistance = 100;
  58111. this.distanceModel = "linear";
  58112. this._panningModel = "equalpower";
  58113. this._playbackRate = 1;
  58114. this._streaming = false;
  58115. this._startTime = 0;
  58116. this._startOffset = 0;
  58117. this._position = BABYLON.Vector3.Zero();
  58118. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  58119. this._volume = 1;
  58120. this._isReadyToPlay = false;
  58121. this.isPlaying = false;
  58122. this.isPaused = false;
  58123. this._isDirectional = false;
  58124. // Used if you'd like to create a directional sound.
  58125. // If not set, the sound will be omnidirectional
  58126. this._coneInnerAngle = 360;
  58127. this._coneOuterAngle = 360;
  58128. this._coneOuterGain = 0;
  58129. this._isOutputConnected = false;
  58130. this._urlType = "Unknown";
  58131. this.name = name;
  58132. this._scene = scene;
  58133. this._readyToPlayCallback = readyToPlayCallback;
  58134. // Default custom attenuation function is a linear attenuation
  58135. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  58136. if (currentDistance < maxDistance) {
  58137. return currentVolume * (1 - currentDistance / maxDistance);
  58138. }
  58139. else {
  58140. return 0;
  58141. }
  58142. };
  58143. if (options) {
  58144. this.autoplay = options.autoplay || false;
  58145. this.loop = options.loop || false;
  58146. // if volume === 0, we need another way to check this option
  58147. if (options.volume !== undefined) {
  58148. this._volume = options.volume;
  58149. }
  58150. this.spatialSound = options.spatialSound || false;
  58151. this.maxDistance = options.maxDistance || 100;
  58152. this.useCustomAttenuation = options.useCustomAttenuation || false;
  58153. this.rolloffFactor = options.rolloffFactor || 1;
  58154. this.refDistance = options.refDistance || 1;
  58155. this.distanceModel = options.distanceModel || "linear";
  58156. this._playbackRate = options.playbackRate || 1;
  58157. this._streaming = options.streaming || false;
  58158. }
  58159. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  58160. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  58161. this._soundGain.gain.value = this._volume;
  58162. this._inputAudioNode = this._soundGain;
  58163. this._ouputAudioNode = this._soundGain;
  58164. if (this.spatialSound) {
  58165. this._createSpatialParameters();
  58166. }
  58167. this._scene.mainSoundTrack.AddSound(this);
  58168. var validParameter = true;
  58169. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  58170. if (urlOrArrayBuffer) {
  58171. try {
  58172. if (typeof (urlOrArrayBuffer) === "string")
  58173. this._urlType = "String";
  58174. if (Array.isArray(urlOrArrayBuffer))
  58175. this._urlType = "Array";
  58176. if (urlOrArrayBuffer instanceof ArrayBuffer)
  58177. this._urlType = "ArrayBuffer";
  58178. var urls = [];
  58179. var codecSupportedFound = false;
  58180. switch (this._urlType) {
  58181. case "ArrayBuffer":
  58182. if (urlOrArrayBuffer.byteLength > 0) {
  58183. codecSupportedFound = true;
  58184. this._soundLoaded(urlOrArrayBuffer);
  58185. }
  58186. break;
  58187. case "String":
  58188. urls.push(urlOrArrayBuffer);
  58189. case "Array":
  58190. if (urls.length === 0)
  58191. urls = urlOrArrayBuffer;
  58192. // If we found a supported format, we load it immediately and stop the loop
  58193. for (var i = 0; i < urls.length; i++) {
  58194. var url = urls[i];
  58195. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  58196. codecSupportedFound = true;
  58197. }
  58198. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  58199. codecSupportedFound = true;
  58200. }
  58201. if (url.indexOf(".wav", url.length - 4) !== -1) {
  58202. codecSupportedFound = true;
  58203. }
  58204. if (url.indexOf("blob:") !== -1) {
  58205. codecSupportedFound = true;
  58206. }
  58207. if (codecSupportedFound) {
  58208. // Loading sound using XHR2
  58209. if (!this._streaming) {
  58210. this._scene._loadFile(url, function (data) {
  58211. _this._soundLoaded(data);
  58212. }, undefined, true, true, function (exception) {
  58213. if (exception) {
  58214. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  58215. }
  58216. BABYLON.Tools.Error("Sound creation aborted.");
  58217. _this._scene.mainSoundTrack.RemoveSound(_this);
  58218. });
  58219. }
  58220. else {
  58221. this._htmlAudioElement = new Audio(url);
  58222. this._htmlAudioElement.controls = false;
  58223. this._htmlAudioElement.loop = this.loop;
  58224. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  58225. this._htmlAudioElement.preload = "auto";
  58226. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  58227. _this._isReadyToPlay = true;
  58228. if (_this.autoplay) {
  58229. _this.play();
  58230. }
  58231. if (_this._readyToPlayCallback) {
  58232. _this._readyToPlayCallback();
  58233. }
  58234. });
  58235. document.body.appendChild(this._htmlAudioElement);
  58236. }
  58237. break;
  58238. }
  58239. }
  58240. break;
  58241. default:
  58242. validParameter = false;
  58243. break;
  58244. }
  58245. if (!validParameter) {
  58246. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  58247. }
  58248. else {
  58249. if (!codecSupportedFound) {
  58250. this._isReadyToPlay = true;
  58251. // Simulating a ready to play event to avoid breaking code path
  58252. if (this._readyToPlayCallback) {
  58253. window.setTimeout(function () {
  58254. if (_this._readyToPlayCallback) {
  58255. _this._readyToPlayCallback();
  58256. }
  58257. }, 1000);
  58258. }
  58259. }
  58260. }
  58261. }
  58262. catch (ex) {
  58263. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  58264. this._scene.mainSoundTrack.RemoveSound(this);
  58265. }
  58266. }
  58267. }
  58268. else {
  58269. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  58270. this._scene.mainSoundTrack.AddSound(this);
  58271. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  58272. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  58273. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  58274. }
  58275. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  58276. if (this._readyToPlayCallback) {
  58277. window.setTimeout(function () {
  58278. if (_this._readyToPlayCallback) {
  58279. _this._readyToPlayCallback();
  58280. }
  58281. }, 1000);
  58282. }
  58283. }
  58284. }
  58285. Sound.prototype.dispose = function () {
  58286. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58287. if (this.isPlaying) {
  58288. this.stop();
  58289. }
  58290. this._isReadyToPlay = false;
  58291. if (this.soundTrackId === -1) {
  58292. this._scene.mainSoundTrack.RemoveSound(this);
  58293. }
  58294. else {
  58295. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  58296. }
  58297. if (this._soundGain) {
  58298. this._soundGain.disconnect();
  58299. this._soundGain = null;
  58300. }
  58301. if (this._soundPanner) {
  58302. this._soundPanner.disconnect();
  58303. this._soundPanner = null;
  58304. }
  58305. if (this._soundSource) {
  58306. this._soundSource.disconnect();
  58307. this._soundSource = null;
  58308. }
  58309. this._audioBuffer = null;
  58310. if (this._htmlAudioElement) {
  58311. this._htmlAudioElement.pause();
  58312. this._htmlAudioElement.src = "";
  58313. document.body.removeChild(this._htmlAudioElement);
  58314. }
  58315. if (this._connectedMesh && this._registerFunc) {
  58316. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  58317. this._connectedMesh = null;
  58318. }
  58319. }
  58320. };
  58321. Sound.prototype.isReady = function () {
  58322. return this._isReadyToPlay;
  58323. };
  58324. Sound.prototype._soundLoaded = function (audioData) {
  58325. var _this = this;
  58326. if (!BABYLON.Engine.audioEngine.audioContext) {
  58327. return;
  58328. }
  58329. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  58330. _this._audioBuffer = buffer;
  58331. _this._isReadyToPlay = true;
  58332. if (_this.autoplay) {
  58333. _this.play();
  58334. }
  58335. if (_this._readyToPlayCallback) {
  58336. _this._readyToPlayCallback();
  58337. }
  58338. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  58339. };
  58340. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  58341. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58342. this._audioBuffer = audioBuffer;
  58343. this._isReadyToPlay = true;
  58344. }
  58345. };
  58346. Sound.prototype.updateOptions = function (options) {
  58347. if (options) {
  58348. this.loop = options.loop || this.loop;
  58349. this.maxDistance = options.maxDistance || this.maxDistance;
  58350. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  58351. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  58352. this.refDistance = options.refDistance || this.refDistance;
  58353. this.distanceModel = options.distanceModel || this.distanceModel;
  58354. this._playbackRate = options.playbackRate || this._playbackRate;
  58355. this._updateSpatialParameters();
  58356. if (this.isPlaying) {
  58357. if (this._streaming) {
  58358. this._htmlAudioElement.playbackRate = this._playbackRate;
  58359. }
  58360. else {
  58361. if (this._soundSource) {
  58362. this._soundSource.playbackRate.value = this._playbackRate;
  58363. }
  58364. }
  58365. }
  58366. }
  58367. };
  58368. Sound.prototype._createSpatialParameters = function () {
  58369. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  58370. if (this._scene.headphone) {
  58371. this._panningModel = "HRTF";
  58372. }
  58373. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  58374. this._updateSpatialParameters();
  58375. this._soundPanner.connect(this._ouputAudioNode);
  58376. this._inputAudioNode = this._soundPanner;
  58377. }
  58378. };
  58379. Sound.prototype._updateSpatialParameters = function () {
  58380. if (this.spatialSound && this._soundPanner) {
  58381. if (this.useCustomAttenuation) {
  58382. // Tricks to disable in a way embedded Web Audio attenuation
  58383. this._soundPanner.distanceModel = "linear";
  58384. this._soundPanner.maxDistance = Number.MAX_VALUE;
  58385. this._soundPanner.refDistance = 1;
  58386. this._soundPanner.rolloffFactor = 1;
  58387. this._soundPanner.panningModel = this._panningModel;
  58388. }
  58389. else {
  58390. this._soundPanner.distanceModel = this.distanceModel;
  58391. this._soundPanner.maxDistance = this.maxDistance;
  58392. this._soundPanner.refDistance = this.refDistance;
  58393. this._soundPanner.rolloffFactor = this.rolloffFactor;
  58394. this._soundPanner.panningModel = this._panningModel;
  58395. }
  58396. }
  58397. };
  58398. Sound.prototype.switchPanningModelToHRTF = function () {
  58399. this._panningModel = "HRTF";
  58400. this._switchPanningModel();
  58401. };
  58402. Sound.prototype.switchPanningModelToEqualPower = function () {
  58403. this._panningModel = "equalpower";
  58404. this._switchPanningModel();
  58405. };
  58406. Sound.prototype._switchPanningModel = function () {
  58407. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  58408. this._soundPanner.panningModel = this._panningModel;
  58409. }
  58410. };
  58411. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  58412. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58413. if (this._isOutputConnected) {
  58414. this._ouputAudioNode.disconnect();
  58415. }
  58416. this._ouputAudioNode.connect(soundTrackAudioNode);
  58417. this._isOutputConnected = true;
  58418. }
  58419. };
  58420. /**
  58421. * Transform this sound into a directional source
  58422. * @param coneInnerAngle Size of the inner cone in degree
  58423. * @param coneOuterAngle Size of the outer cone in degree
  58424. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  58425. */
  58426. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  58427. if (coneOuterAngle < coneInnerAngle) {
  58428. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  58429. return;
  58430. }
  58431. this._coneInnerAngle = coneInnerAngle;
  58432. this._coneOuterAngle = coneOuterAngle;
  58433. this._coneOuterGain = coneOuterGain;
  58434. this._isDirectional = true;
  58435. if (this.isPlaying && this.loop) {
  58436. this.stop();
  58437. this.play();
  58438. }
  58439. };
  58440. Sound.prototype.setPosition = function (newPosition) {
  58441. this._position = newPosition;
  58442. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  58443. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  58444. }
  58445. };
  58446. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  58447. this._localDirection = newLocalDirection;
  58448. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  58449. this._updateDirection();
  58450. }
  58451. };
  58452. Sound.prototype._updateDirection = function () {
  58453. if (!this._connectedMesh || !this._soundPanner) {
  58454. return;
  58455. }
  58456. var mat = this._connectedMesh.getWorldMatrix();
  58457. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  58458. direction.normalize();
  58459. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  58460. };
  58461. Sound.prototype.updateDistanceFromListener = function () {
  58462. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  58463. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  58464. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  58465. }
  58466. };
  58467. Sound.prototype.setAttenuationFunction = function (callback) {
  58468. this._customAttenuationFunction = callback;
  58469. };
  58470. /**
  58471. * Play the sound
  58472. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  58473. * @param offset (optional) Start the sound setting it at a specific time
  58474. */
  58475. Sound.prototype.play = function (time, offset) {
  58476. var _this = this;
  58477. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  58478. try {
  58479. if (this._startOffset < 0) {
  58480. time = -this._startOffset;
  58481. this._startOffset = 0;
  58482. }
  58483. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  58484. if (!this._soundSource || !this._streamingSource) {
  58485. if (this.spatialSound && this._soundPanner) {
  58486. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  58487. if (this._isDirectional) {
  58488. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  58489. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  58490. this._soundPanner.coneOuterGain = this._coneOuterGain;
  58491. if (this._connectedMesh) {
  58492. this._updateDirection();
  58493. }
  58494. else {
  58495. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  58496. }
  58497. }
  58498. }
  58499. }
  58500. if (this._streaming) {
  58501. if (!this._streamingSource) {
  58502. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  58503. this._htmlAudioElement.onended = function () { _this._onended(); };
  58504. this._htmlAudioElement.playbackRate = this._playbackRate;
  58505. }
  58506. this._streamingSource.disconnect();
  58507. this._streamingSource.connect(this._inputAudioNode);
  58508. this._htmlAudioElement.play();
  58509. }
  58510. else {
  58511. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  58512. this._soundSource.buffer = this._audioBuffer;
  58513. this._soundSource.connect(this._inputAudioNode);
  58514. this._soundSource.loop = this.loop;
  58515. this._soundSource.playbackRate.value = this._playbackRate;
  58516. this._soundSource.onended = function () { _this._onended(); };
  58517. if (this._soundSource.buffer) {
  58518. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  58519. }
  58520. }
  58521. this._startTime = startTime;
  58522. this.isPlaying = true;
  58523. this.isPaused = false;
  58524. }
  58525. catch (ex) {
  58526. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  58527. }
  58528. }
  58529. };
  58530. Sound.prototype._onended = function () {
  58531. this.isPlaying = false;
  58532. if (this.onended) {
  58533. this.onended();
  58534. }
  58535. };
  58536. /**
  58537. * Stop the sound
  58538. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  58539. */
  58540. Sound.prototype.stop = function (time) {
  58541. if (this.isPlaying) {
  58542. if (this._streaming) {
  58543. this._htmlAudioElement.pause();
  58544. // Test needed for Firefox or it will generate an Invalid State Error
  58545. if (this._htmlAudioElement.currentTime > 0) {
  58546. this._htmlAudioElement.currentTime = 0;
  58547. }
  58548. }
  58549. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  58550. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  58551. this._soundSource.stop(stopTime);
  58552. this._soundSource.onended = function () { };
  58553. if (!this.isPaused) {
  58554. this._startOffset = 0;
  58555. }
  58556. }
  58557. this.isPlaying = false;
  58558. }
  58559. };
  58560. Sound.prototype.pause = function () {
  58561. if (this.isPlaying) {
  58562. this.isPaused = true;
  58563. if (this._streaming) {
  58564. this._htmlAudioElement.pause();
  58565. }
  58566. else if (BABYLON.Engine.audioEngine.audioContext) {
  58567. this.stop(0);
  58568. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  58569. }
  58570. }
  58571. };
  58572. Sound.prototype.setVolume = function (newVolume, time) {
  58573. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  58574. if (time && BABYLON.Engine.audioEngine.audioContext) {
  58575. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  58576. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  58577. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  58578. }
  58579. else {
  58580. this._soundGain.gain.value = newVolume;
  58581. }
  58582. }
  58583. this._volume = newVolume;
  58584. };
  58585. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  58586. this._playbackRate = newPlaybackRate;
  58587. if (this.isPlaying) {
  58588. if (this._streaming) {
  58589. this._htmlAudioElement.playbackRate = this._playbackRate;
  58590. }
  58591. else if (this._soundSource) {
  58592. this._soundSource.playbackRate.value = this._playbackRate;
  58593. }
  58594. }
  58595. };
  58596. Sound.prototype.getVolume = function () {
  58597. return this._volume;
  58598. };
  58599. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  58600. var _this = this;
  58601. if (this._connectedMesh && this._registerFunc) {
  58602. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  58603. this._registerFunc = null;
  58604. }
  58605. this._connectedMesh = meshToConnectTo;
  58606. if (!this.spatialSound) {
  58607. this.spatialSound = true;
  58608. this._createSpatialParameters();
  58609. if (this.isPlaying && this.loop) {
  58610. this.stop();
  58611. this.play();
  58612. }
  58613. }
  58614. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  58615. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  58616. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  58617. };
  58618. Sound.prototype.detachFromMesh = function () {
  58619. if (this._connectedMesh && this._registerFunc) {
  58620. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  58621. this._registerFunc = null;
  58622. this._connectedMesh = null;
  58623. }
  58624. };
  58625. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  58626. if (!node.getBoundingInfo) {
  58627. return;
  58628. }
  58629. var mesh = node;
  58630. var boundingInfo = mesh.getBoundingInfo();
  58631. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  58632. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  58633. this._updateDirection();
  58634. }
  58635. };
  58636. Sound.prototype.clone = function () {
  58637. var _this = this;
  58638. if (!this._streaming) {
  58639. var setBufferAndRun = function () {
  58640. if (_this._isReadyToPlay) {
  58641. clonedSound._audioBuffer = _this.getAudioBuffer();
  58642. clonedSound._isReadyToPlay = true;
  58643. if (clonedSound.autoplay) {
  58644. clonedSound.play();
  58645. }
  58646. }
  58647. else {
  58648. window.setTimeout(setBufferAndRun, 300);
  58649. }
  58650. };
  58651. var currentOptions = {
  58652. autoplay: this.autoplay, loop: this.loop,
  58653. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  58654. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  58655. refDistance: this.refDistance, distanceModel: this.distanceModel
  58656. };
  58657. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  58658. if (this.useCustomAttenuation) {
  58659. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  58660. }
  58661. clonedSound.setPosition(this._position);
  58662. clonedSound.setPlaybackRate(this._playbackRate);
  58663. setBufferAndRun();
  58664. return clonedSound;
  58665. }
  58666. else {
  58667. return null;
  58668. }
  58669. };
  58670. Sound.prototype.getAudioBuffer = function () {
  58671. return this._audioBuffer;
  58672. };
  58673. Sound.prototype.serialize = function () {
  58674. var serializationObject = {
  58675. name: this.name,
  58676. url: this.name,
  58677. autoplay: this.autoplay,
  58678. loop: this.loop,
  58679. volume: this._volume,
  58680. spatialSound: this.spatialSound,
  58681. maxDistance: this.maxDistance,
  58682. rolloffFactor: this.rolloffFactor,
  58683. refDistance: this.refDistance,
  58684. distanceModel: this.distanceModel,
  58685. playbackRate: this._playbackRate,
  58686. panningModel: this._panningModel,
  58687. soundTrackId: this.soundTrackId
  58688. };
  58689. if (this.spatialSound) {
  58690. if (this._connectedMesh)
  58691. serializationObject.connectedMeshId = this._connectedMesh.id;
  58692. serializationObject.position = this._position.asArray();
  58693. serializationObject.refDistance = this.refDistance;
  58694. serializationObject.distanceModel = this.distanceModel;
  58695. serializationObject.isDirectional = this._isDirectional;
  58696. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  58697. serializationObject.coneInnerAngle = this._coneInnerAngle;
  58698. serializationObject.coneOuterAngle = this._coneOuterAngle;
  58699. serializationObject.coneOuterGain = this._coneOuterGain;
  58700. }
  58701. return serializationObject;
  58702. };
  58703. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  58704. var soundName = parsedSound.name;
  58705. var soundUrl;
  58706. if (parsedSound.url) {
  58707. soundUrl = rootUrl + parsedSound.url;
  58708. }
  58709. else {
  58710. soundUrl = rootUrl + soundName;
  58711. }
  58712. var options = {
  58713. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  58714. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  58715. rolloffFactor: parsedSound.rolloffFactor,
  58716. refDistance: parsedSound.refDistance,
  58717. distanceModel: parsedSound.distanceModel,
  58718. playbackRate: parsedSound.playbackRate
  58719. };
  58720. var newSound;
  58721. if (!sourceSound) {
  58722. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  58723. scene._addPendingData(newSound);
  58724. }
  58725. else {
  58726. var setBufferAndRun = function () {
  58727. if (sourceSound._isReadyToPlay) {
  58728. newSound._audioBuffer = sourceSound.getAudioBuffer();
  58729. newSound._isReadyToPlay = true;
  58730. if (newSound.autoplay) {
  58731. newSound.play();
  58732. }
  58733. }
  58734. else {
  58735. window.setTimeout(setBufferAndRun, 300);
  58736. }
  58737. };
  58738. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  58739. setBufferAndRun();
  58740. }
  58741. if (parsedSound.position) {
  58742. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  58743. newSound.setPosition(soundPosition);
  58744. }
  58745. if (parsedSound.isDirectional) {
  58746. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  58747. if (parsedSound.localDirectionToMesh) {
  58748. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  58749. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  58750. }
  58751. }
  58752. if (parsedSound.connectedMeshId) {
  58753. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  58754. if (connectedMesh) {
  58755. newSound.attachToMesh(connectedMesh);
  58756. }
  58757. }
  58758. return newSound;
  58759. };
  58760. return Sound;
  58761. }());
  58762. BABYLON.Sound = Sound;
  58763. })(BABYLON || (BABYLON = {}));
  58764. //# sourceMappingURL=babylon.sound.js.map
  58765. "use strict";
  58766. var BABYLON;
  58767. (function (BABYLON) {
  58768. var SoundTrack = /** @class */ (function () {
  58769. function SoundTrack(scene, options) {
  58770. this.id = -1;
  58771. this._isMainTrack = false;
  58772. this._isInitialized = false;
  58773. this._scene = scene;
  58774. this.soundCollection = new Array();
  58775. this._options = options;
  58776. if (!this._isMainTrack) {
  58777. this._scene.soundTracks.push(this);
  58778. this.id = this._scene.soundTracks.length - 1;
  58779. }
  58780. }
  58781. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  58782. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  58783. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  58784. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  58785. if (this._options) {
  58786. if (this._options.volume) {
  58787. this._outputAudioNode.gain.value = this._options.volume;
  58788. }
  58789. if (this._options.mainTrack) {
  58790. this._isMainTrack = this._options.mainTrack;
  58791. }
  58792. }
  58793. this._isInitialized = true;
  58794. }
  58795. };
  58796. SoundTrack.prototype.dispose = function () {
  58797. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  58798. if (this._connectedAnalyser) {
  58799. this._connectedAnalyser.stopDebugCanvas();
  58800. }
  58801. while (this.soundCollection.length) {
  58802. this.soundCollection[0].dispose();
  58803. }
  58804. if (this._outputAudioNode) {
  58805. this._outputAudioNode.disconnect();
  58806. }
  58807. this._outputAudioNode = null;
  58808. }
  58809. };
  58810. SoundTrack.prototype.AddSound = function (sound) {
  58811. if (!this._isInitialized) {
  58812. this._initializeSoundTrackAudioGraph();
  58813. }
  58814. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58815. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  58816. }
  58817. if (sound.soundTrackId) {
  58818. if (sound.soundTrackId === -1) {
  58819. this._scene.mainSoundTrack.RemoveSound(sound);
  58820. }
  58821. else {
  58822. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  58823. }
  58824. }
  58825. this.soundCollection.push(sound);
  58826. sound.soundTrackId = this.id;
  58827. };
  58828. SoundTrack.prototype.RemoveSound = function (sound) {
  58829. var index = this.soundCollection.indexOf(sound);
  58830. if (index !== -1) {
  58831. this.soundCollection.splice(index, 1);
  58832. }
  58833. };
  58834. SoundTrack.prototype.setVolume = function (newVolume) {
  58835. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58836. this._outputAudioNode.gain.value = newVolume;
  58837. }
  58838. };
  58839. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  58840. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58841. for (var i = 0; i < this.soundCollection.length; i++) {
  58842. this.soundCollection[i].switchPanningModelToHRTF();
  58843. }
  58844. }
  58845. };
  58846. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  58847. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58848. for (var i = 0; i < this.soundCollection.length; i++) {
  58849. this.soundCollection[i].switchPanningModelToEqualPower();
  58850. }
  58851. }
  58852. };
  58853. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  58854. if (this._connectedAnalyser) {
  58855. this._connectedAnalyser.stopDebugCanvas();
  58856. }
  58857. this._connectedAnalyser = analyser;
  58858. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58859. this._outputAudioNode.disconnect();
  58860. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  58861. }
  58862. };
  58863. return SoundTrack;
  58864. }());
  58865. BABYLON.SoundTrack = SoundTrack;
  58866. })(BABYLON || (BABYLON = {}));
  58867. //# sourceMappingURL=babylon.soundtrack.js.map
  58868. "use strict";
  58869. var BABYLON;
  58870. (function (BABYLON) {
  58871. var Analyser = /** @class */ (function () {
  58872. function Analyser(scene) {
  58873. this.SMOOTHING = 0.75;
  58874. this.FFT_SIZE = 512;
  58875. this.BARGRAPHAMPLITUDE = 256;
  58876. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  58877. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  58878. this._scene = scene;
  58879. this._audioEngine = BABYLON.Engine.audioEngine;
  58880. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  58881. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  58882. this._webAudioAnalyser.minDecibels = -140;
  58883. this._webAudioAnalyser.maxDecibels = 0;
  58884. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  58885. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  58886. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  58887. }
  58888. }
  58889. Analyser.prototype.getFrequencyBinCount = function () {
  58890. if (this._audioEngine.canUseWebAudio) {
  58891. return this._webAudioAnalyser.frequencyBinCount;
  58892. }
  58893. else {
  58894. return 0;
  58895. }
  58896. };
  58897. Analyser.prototype.getByteFrequencyData = function () {
  58898. if (this._audioEngine.canUseWebAudio) {
  58899. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58900. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58901. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  58902. }
  58903. return this._byteFreqs;
  58904. };
  58905. Analyser.prototype.getByteTimeDomainData = function () {
  58906. if (this._audioEngine.canUseWebAudio) {
  58907. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58908. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58909. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  58910. }
  58911. return this._byteTime;
  58912. };
  58913. Analyser.prototype.getFloatFrequencyData = function () {
  58914. if (this._audioEngine.canUseWebAudio) {
  58915. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58916. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58917. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  58918. }
  58919. return this._floatFreqs;
  58920. };
  58921. Analyser.prototype.drawDebugCanvas = function () {
  58922. var _this = this;
  58923. if (this._audioEngine.canUseWebAudio) {
  58924. if (!this._debugCanvas) {
  58925. this._debugCanvas = document.createElement("canvas");
  58926. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  58927. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  58928. this._debugCanvas.style.position = "absolute";
  58929. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  58930. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  58931. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  58932. document.body.appendChild(this._debugCanvas);
  58933. this._registerFunc = function () {
  58934. _this.drawDebugCanvas();
  58935. };
  58936. this._scene.registerBeforeRender(this._registerFunc);
  58937. }
  58938. if (this._registerFunc && this._debugCanvasContext) {
  58939. var workingArray = this.getByteFrequencyData();
  58940. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  58941. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  58942. // Draw the frequency domain chart.
  58943. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  58944. var value = workingArray[i];
  58945. var percent = value / this.BARGRAPHAMPLITUDE;
  58946. var height = this.DEBUGCANVASSIZE.height * percent;
  58947. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  58948. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  58949. var hue = i / this.getFrequencyBinCount() * 360;
  58950. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  58951. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  58952. }
  58953. }
  58954. }
  58955. };
  58956. Analyser.prototype.stopDebugCanvas = function () {
  58957. if (this._debugCanvas) {
  58958. if (this._registerFunc) {
  58959. this._scene.unregisterBeforeRender(this._registerFunc);
  58960. this._registerFunc = null;
  58961. }
  58962. document.body.removeChild(this._debugCanvas);
  58963. this._debugCanvas = null;
  58964. this._debugCanvasContext = null;
  58965. }
  58966. };
  58967. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  58968. if (this._audioEngine.canUseWebAudio) {
  58969. inputAudioNode.connect(this._webAudioAnalyser);
  58970. this._webAudioAnalyser.connect(outputAudioNode);
  58971. }
  58972. };
  58973. Analyser.prototype.dispose = function () {
  58974. if (this._audioEngine.canUseWebAudio) {
  58975. this._webAudioAnalyser.disconnect();
  58976. }
  58977. };
  58978. return Analyser;
  58979. }());
  58980. BABYLON.Analyser = Analyser;
  58981. })(BABYLON || (BABYLON = {}));
  58982. //# sourceMappingURL=babylon.analyser.js.map
  58983. "use strict";
  58984. var BABYLON;
  58985. (function (BABYLON) {
  58986. var CubeTexture = /** @class */ (function (_super) {
  58987. __extends(CubeTexture, _super);
  58988. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  58989. if (extensions === void 0) { extensions = null; }
  58990. if (noMipmap === void 0) { noMipmap = false; }
  58991. if (files === void 0) { files = null; }
  58992. if (onLoad === void 0) { onLoad = null; }
  58993. if (onError === void 0) { onError = null; }
  58994. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  58995. if (prefiltered === void 0) { prefiltered = false; }
  58996. if (forcedExtension === void 0) { forcedExtension = null; }
  58997. var _this = _super.call(this, scene) || this;
  58998. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  58999. /**
  59000. * Gets or sets the center of the bounding box associated with the cube texture
  59001. * It must define where the camera used to render the texture was set
  59002. */
  59003. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  59004. _this.name = rootUrl;
  59005. _this.url = rootUrl;
  59006. _this._noMipmap = noMipmap;
  59007. _this.hasAlpha = false;
  59008. _this._format = format;
  59009. _this._prefiltered = prefiltered;
  59010. _this.isCube = true;
  59011. _this._textureMatrix = BABYLON.Matrix.Identity();
  59012. if (prefiltered) {
  59013. _this.gammaSpace = false;
  59014. }
  59015. if (!rootUrl && !files) {
  59016. return _this;
  59017. }
  59018. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  59019. var lastDot = rootUrl.lastIndexOf(".");
  59020. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  59021. var isDDS = (extension === ".dds");
  59022. if (!files) {
  59023. if (!isDDS && !extensions) {
  59024. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  59025. }
  59026. files = [];
  59027. if (extensions) {
  59028. for (var index = 0; index < extensions.length; index++) {
  59029. files.push(rootUrl + extensions[index]);
  59030. }
  59031. }
  59032. }
  59033. _this._files = files;
  59034. if (!_this._texture) {
  59035. if (!scene.useDelayedTextureLoading) {
  59036. if (prefiltered) {
  59037. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  59038. }
  59039. else {
  59040. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  59041. }
  59042. }
  59043. else {
  59044. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  59045. }
  59046. }
  59047. else if (onLoad) {
  59048. if (_this._texture.isReady) {
  59049. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  59050. }
  59051. else {
  59052. _this._texture.onLoadedObservable.add(onLoad);
  59053. }
  59054. }
  59055. return _this;
  59056. }
  59057. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  59058. get: function () {
  59059. return this._boundingBoxSize;
  59060. },
  59061. /**
  59062. * Gets or sets the size of the bounding box associated with the cube texture
  59063. * When defined, the cubemap will switch to local mode
  59064. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  59065. * @example https://www.babylonjs-playground.com/#RNASML
  59066. */
  59067. set: function (value) {
  59068. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  59069. return;
  59070. }
  59071. this._boundingBoxSize = value;
  59072. var scene = this.getScene();
  59073. if (scene) {
  59074. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  59075. }
  59076. },
  59077. enumerable: true,
  59078. configurable: true
  59079. });
  59080. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  59081. var rootUrlKey = "";
  59082. files.forEach(function (url) { return rootUrlKey += url; });
  59083. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  59084. };
  59085. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  59086. if (forcedExtension === void 0) { forcedExtension = null; }
  59087. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  59088. };
  59089. // Methods
  59090. CubeTexture.prototype.delayLoad = function () {
  59091. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  59092. return;
  59093. }
  59094. var scene = this.getScene();
  59095. if (!scene) {
  59096. return;
  59097. }
  59098. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  59099. this._texture = this._getFromCache(this.url, this._noMipmap);
  59100. if (!this._texture) {
  59101. if (this._prefiltered) {
  59102. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  59103. }
  59104. else {
  59105. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  59106. }
  59107. }
  59108. };
  59109. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  59110. return this._textureMatrix;
  59111. };
  59112. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  59113. this._textureMatrix = value;
  59114. };
  59115. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  59116. var texture = BABYLON.SerializationHelper.Parse(function () {
  59117. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  59118. }, parsedTexture, scene);
  59119. // Local Cubemaps
  59120. if (parsedTexture.boundingBoxPosition) {
  59121. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  59122. }
  59123. if (parsedTexture.boundingBoxSize) {
  59124. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  59125. }
  59126. // Animations
  59127. if (parsedTexture.animations) {
  59128. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  59129. var parsedAnimation = parsedTexture.animations[animationIndex];
  59130. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  59131. }
  59132. }
  59133. return texture;
  59134. };
  59135. CubeTexture.prototype.clone = function () {
  59136. var _this = this;
  59137. return BABYLON.SerializationHelper.Clone(function () {
  59138. var scene = _this.getScene();
  59139. if (!scene) {
  59140. return _this;
  59141. }
  59142. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  59143. }, this);
  59144. };
  59145. return CubeTexture;
  59146. }(BABYLON.BaseTexture));
  59147. BABYLON.CubeTexture = CubeTexture;
  59148. })(BABYLON || (BABYLON = {}));
  59149. //# sourceMappingURL=babylon.cubeTexture.js.map
  59150. "use strict";
  59151. var BABYLON;
  59152. (function (BABYLON) {
  59153. var RenderTargetTexture = /** @class */ (function (_super) {
  59154. __extends(RenderTargetTexture, _super);
  59155. /**
  59156. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  59157. * or used a shadow, depth texture...
  59158. * @param name The friendly name of the texture
  59159. * @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)
  59160. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  59161. * @param generateMipMaps True if mip maps need to be generated after render.
  59162. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  59163. * @param type The type of the buffer in the RTT (int, half float, float...)
  59164. * @param isCube True if a cube texture needs to be created
  59165. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  59166. * @param generateDepthBuffer True to generate a depth buffer
  59167. * @param generateStencilBuffer True to generate a stencil buffer
  59168. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  59169. */
  59170. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  59171. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  59172. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59173. if (isCube === void 0) { isCube = false; }
  59174. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59175. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  59176. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  59177. if (isMulti === void 0) { isMulti = false; }
  59178. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  59179. _this.isCube = isCube;
  59180. /**
  59181. * Use this list to define the list of mesh you want to render.
  59182. */
  59183. _this.renderList = new Array();
  59184. _this.renderParticles = true;
  59185. _this.renderSprites = false;
  59186. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  59187. _this.ignoreCameraViewport = false;
  59188. // Events
  59189. /**
  59190. * An event triggered when the texture is unbind.
  59191. */
  59192. _this.onBeforeBindObservable = new BABYLON.Observable();
  59193. /**
  59194. * An event triggered when the texture is unbind.
  59195. */
  59196. _this.onAfterUnbindObservable = new BABYLON.Observable();
  59197. /**
  59198. * An event triggered before rendering the texture
  59199. */
  59200. _this.onBeforeRenderObservable = new BABYLON.Observable();
  59201. /**
  59202. * An event triggered after rendering the texture
  59203. */
  59204. _this.onAfterRenderObservable = new BABYLON.Observable();
  59205. /**
  59206. * An event triggered after the texture clear
  59207. */
  59208. _this.onClearObservable = new BABYLON.Observable();
  59209. _this._currentRefreshId = -1;
  59210. _this._refreshRate = 1;
  59211. _this._samples = 1;
  59212. /**
  59213. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  59214. * It must define where the camera used to render the texture is set
  59215. */
  59216. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  59217. scene = _this.getScene();
  59218. if (!scene) {
  59219. return _this;
  59220. }
  59221. _this._engine = scene.getEngine();
  59222. _this.name = name;
  59223. _this.isRenderTarget = true;
  59224. _this._initialSizeParameter = size;
  59225. _this._processSizeParameter(size);
  59226. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  59227. });
  59228. _this._generateMipMaps = generateMipMaps ? true : false;
  59229. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  59230. // Rendering groups
  59231. _this._renderingManager = new BABYLON.RenderingManager(scene);
  59232. if (isMulti) {
  59233. return _this;
  59234. }
  59235. _this._renderTargetOptions = {
  59236. generateMipMaps: generateMipMaps,
  59237. type: type,
  59238. samplingMode: samplingMode,
  59239. generateDepthBuffer: generateDepthBuffer,
  59240. generateStencilBuffer: generateStencilBuffer
  59241. };
  59242. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  59243. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59244. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59245. }
  59246. if (isCube) {
  59247. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  59248. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  59249. _this._textureMatrix = BABYLON.Matrix.Identity();
  59250. }
  59251. else {
  59252. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  59253. }
  59254. return _this;
  59255. }
  59256. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  59257. get: function () {
  59258. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  59259. },
  59260. enumerable: true,
  59261. configurable: true
  59262. });
  59263. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  59264. get: function () {
  59265. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  59266. },
  59267. enumerable: true,
  59268. configurable: true
  59269. });
  59270. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  59271. get: function () {
  59272. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  59273. },
  59274. enumerable: true,
  59275. configurable: true
  59276. });
  59277. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  59278. set: function (callback) {
  59279. if (this._onAfterUnbindObserver) {
  59280. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  59281. }
  59282. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  59283. },
  59284. enumerable: true,
  59285. configurable: true
  59286. });
  59287. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  59288. set: function (callback) {
  59289. if (this._onBeforeRenderObserver) {
  59290. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  59291. }
  59292. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  59293. },
  59294. enumerable: true,
  59295. configurable: true
  59296. });
  59297. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  59298. set: function (callback) {
  59299. if (this._onAfterRenderObserver) {
  59300. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  59301. }
  59302. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  59303. },
  59304. enumerable: true,
  59305. configurable: true
  59306. });
  59307. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  59308. set: function (callback) {
  59309. if (this._onClearObserver) {
  59310. this.onClearObservable.remove(this._onClearObserver);
  59311. }
  59312. this._onClearObserver = this.onClearObservable.add(callback);
  59313. },
  59314. enumerable: true,
  59315. configurable: true
  59316. });
  59317. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  59318. get: function () {
  59319. return this._renderTargetOptions;
  59320. },
  59321. enumerable: true,
  59322. configurable: true
  59323. });
  59324. RenderTargetTexture.prototype._onRatioRescale = function () {
  59325. if (this._sizeRatio) {
  59326. this.resize(this._initialSizeParameter);
  59327. }
  59328. };
  59329. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  59330. get: function () {
  59331. return this._boundingBoxSize;
  59332. },
  59333. /**
  59334. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  59335. * When defined, the cubemap will switch to local mode
  59336. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  59337. * @example https://www.babylonjs-playground.com/#RNASML
  59338. */
  59339. set: function (value) {
  59340. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  59341. return;
  59342. }
  59343. this._boundingBoxSize = value;
  59344. var scene = this.getScene();
  59345. if (scene) {
  59346. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  59347. }
  59348. },
  59349. enumerable: true,
  59350. configurable: true
  59351. });
  59352. /**
  59353. * Creates a depth stencil texture.
  59354. * This is only available in WebGL 2 or with the depth texture extension available.
  59355. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  59356. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  59357. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  59358. */
  59359. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  59360. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  59361. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  59362. if (generateStencil === void 0) { generateStencil = false; }
  59363. if (!this.getScene()) {
  59364. return;
  59365. }
  59366. var engine = this.getScene().getEngine();
  59367. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  59368. bilinearFiltering: bilinearFiltering,
  59369. comparisonFunction: comparisonFunction,
  59370. generateStencil: generateStencil,
  59371. isCube: this.isCube
  59372. });
  59373. engine.setFrameBufferDepthStencilTexture(this);
  59374. };
  59375. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  59376. if (size.ratio) {
  59377. this._sizeRatio = size.ratio;
  59378. this._size = {
  59379. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  59380. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  59381. };
  59382. }
  59383. else {
  59384. this._size = size;
  59385. }
  59386. };
  59387. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  59388. get: function () {
  59389. return this._samples;
  59390. },
  59391. set: function (value) {
  59392. if (this._samples === value) {
  59393. return;
  59394. }
  59395. var scene = this.getScene();
  59396. if (!scene) {
  59397. return;
  59398. }
  59399. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  59400. },
  59401. enumerable: true,
  59402. configurable: true
  59403. });
  59404. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  59405. this._currentRefreshId = -1;
  59406. };
  59407. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  59408. get: function () {
  59409. return this._refreshRate;
  59410. },
  59411. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  59412. set: function (value) {
  59413. this._refreshRate = value;
  59414. this.resetRefreshCounter();
  59415. },
  59416. enumerable: true,
  59417. configurable: true
  59418. });
  59419. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  59420. if (!this._postProcessManager) {
  59421. var scene = this.getScene();
  59422. if (!scene) {
  59423. return;
  59424. }
  59425. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  59426. this._postProcesses = new Array();
  59427. }
  59428. this._postProcesses.push(postProcess);
  59429. this._postProcesses[0].autoClear = false;
  59430. };
  59431. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  59432. if (!this._postProcesses) {
  59433. return;
  59434. }
  59435. if (dispose) {
  59436. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  59437. var postProcess = _a[_i];
  59438. postProcess.dispose();
  59439. }
  59440. }
  59441. this._postProcesses = [];
  59442. };
  59443. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  59444. if (!this._postProcesses) {
  59445. return;
  59446. }
  59447. var index = this._postProcesses.indexOf(postProcess);
  59448. if (index === -1) {
  59449. return;
  59450. }
  59451. this._postProcesses.splice(index, 1);
  59452. if (this._postProcesses.length > 0) {
  59453. this._postProcesses[0].autoClear = false;
  59454. }
  59455. };
  59456. RenderTargetTexture.prototype._shouldRender = function () {
  59457. if (this._currentRefreshId === -1) {
  59458. this._currentRefreshId = 1;
  59459. return true;
  59460. }
  59461. if (this.refreshRate === this._currentRefreshId) {
  59462. this._currentRefreshId = 1;
  59463. return true;
  59464. }
  59465. this._currentRefreshId++;
  59466. return false;
  59467. };
  59468. RenderTargetTexture.prototype.getRenderSize = function () {
  59469. if (this._size.width) {
  59470. return this._size.width;
  59471. }
  59472. return this._size;
  59473. };
  59474. RenderTargetTexture.prototype.getRenderWidth = function () {
  59475. if (this._size.width) {
  59476. return this._size.width;
  59477. }
  59478. return this._size;
  59479. };
  59480. RenderTargetTexture.prototype.getRenderHeight = function () {
  59481. if (this._size.width) {
  59482. return this._size.height;
  59483. }
  59484. return this._size;
  59485. };
  59486. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  59487. get: function () {
  59488. return true;
  59489. },
  59490. enumerable: true,
  59491. configurable: true
  59492. });
  59493. RenderTargetTexture.prototype.scale = function (ratio) {
  59494. var newSize = this.getRenderSize() * ratio;
  59495. this.resize(newSize);
  59496. };
  59497. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  59498. if (this.isCube) {
  59499. return this._textureMatrix;
  59500. }
  59501. return _super.prototype.getReflectionTextureMatrix.call(this);
  59502. };
  59503. RenderTargetTexture.prototype.resize = function (size) {
  59504. this.releaseInternalTexture();
  59505. var scene = this.getScene();
  59506. if (!scene) {
  59507. return;
  59508. }
  59509. this._processSizeParameter(size);
  59510. if (this.isCube) {
  59511. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  59512. }
  59513. else {
  59514. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  59515. }
  59516. };
  59517. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  59518. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  59519. if (dumpForDebug === void 0) { dumpForDebug = false; }
  59520. var scene = this.getScene();
  59521. if (!scene) {
  59522. return;
  59523. }
  59524. var engine = scene.getEngine();
  59525. if (this.useCameraPostProcesses !== undefined) {
  59526. useCameraPostProcess = this.useCameraPostProcesses;
  59527. }
  59528. if (this._waitingRenderList) {
  59529. this.renderList = [];
  59530. for (var index = 0; index < this._waitingRenderList.length; index++) {
  59531. var id = this._waitingRenderList[index];
  59532. var mesh_1 = scene.getMeshByID(id);
  59533. if (mesh_1) {
  59534. this.renderList.push(mesh_1);
  59535. }
  59536. }
  59537. delete this._waitingRenderList;
  59538. }
  59539. // Is predicate defined?
  59540. if (this.renderListPredicate) {
  59541. if (this.renderList) {
  59542. this.renderList.splice(0); // Clear previous renderList
  59543. }
  59544. else {
  59545. this.renderList = [];
  59546. }
  59547. var scene = this.getScene();
  59548. if (!scene) {
  59549. return;
  59550. }
  59551. var sceneMeshes = scene.meshes;
  59552. for (var index = 0; index < sceneMeshes.length; index++) {
  59553. var mesh = sceneMeshes[index];
  59554. if (this.renderListPredicate(mesh)) {
  59555. this.renderList.push(mesh);
  59556. }
  59557. }
  59558. }
  59559. this.onBeforeBindObservable.notifyObservers(this);
  59560. // Set custom projection.
  59561. // Needs to be before binding to prevent changing the aspect ratio.
  59562. var camera;
  59563. if (this.activeCamera) {
  59564. camera = this.activeCamera;
  59565. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  59566. if (this.activeCamera !== scene.activeCamera) {
  59567. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  59568. }
  59569. }
  59570. else {
  59571. camera = scene.activeCamera;
  59572. if (camera) {
  59573. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  59574. }
  59575. }
  59576. // Prepare renderingManager
  59577. this._renderingManager.reset();
  59578. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  59579. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  59580. var sceneRenderId = scene.getRenderId();
  59581. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  59582. var mesh = currentRenderList[meshIndex];
  59583. if (mesh) {
  59584. if (!mesh.isReady(this.refreshRate === 0)) {
  59585. this.resetRefreshCounter();
  59586. continue;
  59587. }
  59588. mesh._preActivateForIntermediateRendering(sceneRenderId);
  59589. var isMasked = void 0;
  59590. if (!this.renderList && camera) {
  59591. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  59592. }
  59593. else {
  59594. isMasked = false;
  59595. }
  59596. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  59597. mesh._activate(sceneRenderId);
  59598. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  59599. var subMesh = mesh.subMeshes[subIndex];
  59600. scene._activeIndices.addCount(subMesh.indexCount, false);
  59601. this._renderingManager.dispatch(subMesh, mesh);
  59602. }
  59603. }
  59604. }
  59605. }
  59606. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  59607. var particleSystem = scene.particleSystems[particleIndex];
  59608. var emitter = particleSystem.emitter;
  59609. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  59610. continue;
  59611. }
  59612. if (currentRenderList.indexOf(emitter) >= 0) {
  59613. this._renderingManager.dispatchParticles(particleSystem);
  59614. }
  59615. }
  59616. if (this.isCube) {
  59617. for (var face = 0; face < 6; face++) {
  59618. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  59619. scene.incrementRenderId();
  59620. scene.resetCachedMaterial();
  59621. }
  59622. }
  59623. else {
  59624. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  59625. }
  59626. this.onAfterUnbindObservable.notifyObservers(this);
  59627. if (scene.activeCamera) {
  59628. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  59629. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  59630. }
  59631. engine.setViewport(scene.activeCamera.viewport);
  59632. }
  59633. scene.resetCachedMaterial();
  59634. };
  59635. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  59636. var minimum = 128;
  59637. var x = renderDimension * scale;
  59638. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  59639. // Ensure we don't exceed the render dimension (while staying POT)
  59640. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  59641. };
  59642. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  59643. var _this = this;
  59644. if (!this._texture) {
  59645. return;
  59646. }
  59647. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  59648. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  59649. });
  59650. };
  59651. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  59652. var scene = this.getScene();
  59653. if (!scene) {
  59654. return;
  59655. }
  59656. var engine = scene.getEngine();
  59657. if (!this._texture) {
  59658. return;
  59659. }
  59660. // Bind
  59661. if (this._postProcessManager) {
  59662. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  59663. }
  59664. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  59665. if (this._texture) {
  59666. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  59667. }
  59668. }
  59669. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  59670. // Clear
  59671. if (this.onClearObservable.hasObservers()) {
  59672. this.onClearObservable.notifyObservers(engine);
  59673. }
  59674. else {
  59675. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  59676. }
  59677. if (!this._doNotChangeAspectRatio) {
  59678. scene.updateTransformMatrix(true);
  59679. }
  59680. // Render
  59681. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  59682. if (this._postProcessManager) {
  59683. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  59684. }
  59685. else if (useCameraPostProcess) {
  59686. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  59687. }
  59688. if (!this._doNotChangeAspectRatio) {
  59689. scene.updateTransformMatrix(true);
  59690. }
  59691. // Dump ?
  59692. if (dumpForDebug) {
  59693. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  59694. }
  59695. // Unbind
  59696. if (!this.isCube || faceIndex === 5) {
  59697. if (this.isCube) {
  59698. if (faceIndex === 5) {
  59699. engine.generateMipMapsForCubemap(this._texture);
  59700. }
  59701. }
  59702. this.unbindFrameBuffer(engine, faceIndex);
  59703. }
  59704. else {
  59705. this.onAfterRenderObservable.notifyObservers(faceIndex);
  59706. }
  59707. };
  59708. /**
  59709. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  59710. * This allowed control for front to back rendering or reversly depending of the special needs.
  59711. *
  59712. * @param renderingGroupId The rendering group id corresponding to its index
  59713. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  59714. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  59715. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  59716. */
  59717. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  59718. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  59719. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  59720. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  59721. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  59722. };
  59723. /**
  59724. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  59725. *
  59726. * @param renderingGroupId The rendering group id corresponding to its index
  59727. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  59728. */
  59729. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  59730. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  59731. };
  59732. RenderTargetTexture.prototype.clone = function () {
  59733. var textureSize = this.getSize();
  59734. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  59735. // Base texture
  59736. newTexture.hasAlpha = this.hasAlpha;
  59737. newTexture.level = this.level;
  59738. // RenderTarget Texture
  59739. newTexture.coordinatesMode = this.coordinatesMode;
  59740. if (this.renderList) {
  59741. newTexture.renderList = this.renderList.slice(0);
  59742. }
  59743. return newTexture;
  59744. };
  59745. RenderTargetTexture.prototype.serialize = function () {
  59746. if (!this.name) {
  59747. return null;
  59748. }
  59749. var serializationObject = _super.prototype.serialize.call(this);
  59750. serializationObject.renderTargetSize = this.getRenderSize();
  59751. serializationObject.renderList = [];
  59752. if (this.renderList) {
  59753. for (var index = 0; index < this.renderList.length; index++) {
  59754. serializationObject.renderList.push(this.renderList[index].id);
  59755. }
  59756. }
  59757. return serializationObject;
  59758. };
  59759. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  59760. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  59761. var objBuffer = this.getInternalTexture();
  59762. var scene = this.getScene();
  59763. if (objBuffer && scene) {
  59764. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  59765. }
  59766. };
  59767. RenderTargetTexture.prototype.dispose = function () {
  59768. if (this._postProcessManager) {
  59769. this._postProcessManager.dispose();
  59770. this._postProcessManager = null;
  59771. }
  59772. this.clearPostProcesses(true);
  59773. if (this._resizeObserver) {
  59774. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  59775. this._resizeObserver = null;
  59776. }
  59777. this.renderList = null;
  59778. // Remove from custom render targets
  59779. var scene = this.getScene();
  59780. if (!scene) {
  59781. return;
  59782. }
  59783. var index = scene.customRenderTargets.indexOf(this);
  59784. if (index >= 0) {
  59785. scene.customRenderTargets.splice(index, 1);
  59786. }
  59787. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  59788. var camera = _a[_i];
  59789. index = camera.customRenderTargets.indexOf(this);
  59790. if (index >= 0) {
  59791. camera.customRenderTargets.splice(index, 1);
  59792. }
  59793. }
  59794. _super.prototype.dispose.call(this);
  59795. };
  59796. RenderTargetTexture.prototype._rebuild = function () {
  59797. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  59798. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  59799. }
  59800. if (this._postProcessManager) {
  59801. this._postProcessManager._rebuild();
  59802. }
  59803. };
  59804. /**
  59805. * Clear the info related to rendering groups preventing retention point in material dispose.
  59806. */
  59807. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  59808. if (this._renderingManager) {
  59809. this._renderingManager.freeRenderingGroups();
  59810. }
  59811. };
  59812. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  59813. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  59814. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  59815. return RenderTargetTexture;
  59816. }(BABYLON.Texture));
  59817. BABYLON.RenderTargetTexture = RenderTargetTexture;
  59818. })(BABYLON || (BABYLON = {}));
  59819. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  59820. "use strict";
  59821. var BABYLON;
  59822. (function (BABYLON) {
  59823. ;
  59824. var MultiRenderTarget = /** @class */ (function (_super) {
  59825. __extends(MultiRenderTarget, _super);
  59826. function MultiRenderTarget(name, size, count, scene, options) {
  59827. var _this = this;
  59828. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  59829. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  59830. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  59831. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  59832. _this._engine = scene.getEngine();
  59833. if (!_this.isSupported) {
  59834. _this.dispose();
  59835. return;
  59836. }
  59837. var types = [];
  59838. var samplingModes = [];
  59839. for (var i = 0; i < count; i++) {
  59840. if (options && options.types && options.types[i] !== undefined) {
  59841. types.push(options.types[i]);
  59842. }
  59843. else {
  59844. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59845. }
  59846. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  59847. samplingModes.push(options.samplingModes[i]);
  59848. }
  59849. else {
  59850. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59851. }
  59852. }
  59853. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  59854. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  59855. _this._size = size;
  59856. _this._multiRenderTargetOptions = {
  59857. samplingModes: samplingModes,
  59858. generateMipMaps: generateMipMaps,
  59859. generateDepthBuffer: generateDepthBuffer,
  59860. generateStencilBuffer: generateStencilBuffer,
  59861. generateDepthTexture: generateDepthTexture,
  59862. types: types,
  59863. textureCount: count
  59864. };
  59865. _this._createInternalTextures();
  59866. _this._createTextures();
  59867. return _this;
  59868. }
  59869. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  59870. get: function () {
  59871. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  59872. },
  59873. enumerable: true,
  59874. configurable: true
  59875. });
  59876. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  59877. get: function () {
  59878. return this._textures;
  59879. },
  59880. enumerable: true,
  59881. configurable: true
  59882. });
  59883. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  59884. get: function () {
  59885. return this._textures[this._textures.length - 1];
  59886. },
  59887. enumerable: true,
  59888. configurable: true
  59889. });
  59890. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  59891. set: function (wrap) {
  59892. if (this._textures) {
  59893. for (var i = 0; i < this._textures.length; i++) {
  59894. this._textures[i].wrapU = wrap;
  59895. }
  59896. }
  59897. },
  59898. enumerable: true,
  59899. configurable: true
  59900. });
  59901. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  59902. set: function (wrap) {
  59903. if (this._textures) {
  59904. for (var i = 0; i < this._textures.length; i++) {
  59905. this._textures[i].wrapV = wrap;
  59906. }
  59907. }
  59908. },
  59909. enumerable: true,
  59910. configurable: true
  59911. });
  59912. MultiRenderTarget.prototype._rebuild = function () {
  59913. this.releaseInternalTextures();
  59914. this._createInternalTextures();
  59915. for (var i = 0; i < this._internalTextures.length; i++) {
  59916. var texture = this._textures[i];
  59917. texture._texture = this._internalTextures[i];
  59918. }
  59919. // Keeps references to frame buffer and stencil/depth buffer
  59920. this._texture = this._internalTextures[0];
  59921. };
  59922. MultiRenderTarget.prototype._createInternalTextures = function () {
  59923. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  59924. };
  59925. MultiRenderTarget.prototype._createTextures = function () {
  59926. this._textures = [];
  59927. for (var i = 0; i < this._internalTextures.length; i++) {
  59928. var texture = new BABYLON.Texture(null, this.getScene());
  59929. texture._texture = this._internalTextures[i];
  59930. this._textures.push(texture);
  59931. }
  59932. // Keeps references to frame buffer and stencil/depth buffer
  59933. this._texture = this._internalTextures[0];
  59934. };
  59935. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  59936. get: function () {
  59937. return this._samples;
  59938. },
  59939. set: function (value) {
  59940. if (this._samples === value) {
  59941. return;
  59942. }
  59943. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  59944. },
  59945. enumerable: true,
  59946. configurable: true
  59947. });
  59948. MultiRenderTarget.prototype.resize = function (size) {
  59949. this.releaseInternalTextures();
  59950. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  59951. this._createInternalTextures();
  59952. };
  59953. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  59954. var _this = this;
  59955. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  59956. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  59957. });
  59958. };
  59959. MultiRenderTarget.prototype.dispose = function () {
  59960. this.releaseInternalTextures();
  59961. _super.prototype.dispose.call(this);
  59962. };
  59963. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  59964. if (!this._internalTextures) {
  59965. return;
  59966. }
  59967. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  59968. if (this._internalTextures[i] !== undefined) {
  59969. this._internalTextures[i].dispose();
  59970. this._internalTextures.splice(i, 1);
  59971. }
  59972. }
  59973. };
  59974. return MultiRenderTarget;
  59975. }(BABYLON.RenderTargetTexture));
  59976. BABYLON.MultiRenderTarget = MultiRenderTarget;
  59977. })(BABYLON || (BABYLON = {}));
  59978. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  59979. "use strict";
  59980. var BABYLON;
  59981. (function (BABYLON) {
  59982. var MirrorTexture = /** @class */ (function (_super) {
  59983. __extends(MirrorTexture, _super);
  59984. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  59985. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59986. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59987. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  59988. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  59989. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  59990. _this._transformMatrix = BABYLON.Matrix.Zero();
  59991. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  59992. _this._adaptiveBlurKernel = 0;
  59993. _this._blurKernelX = 0;
  59994. _this._blurKernelY = 0;
  59995. _this._blurRatio = 1.0;
  59996. _this.ignoreCameraViewport = true;
  59997. _this.onBeforeRenderObservable.add(function () {
  59998. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  59999. _this._savedViewMatrix = scene.getViewMatrix();
  60000. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  60001. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  60002. scene.clipPlane = _this.mirrorPlane;
  60003. scene.getEngine().cullBackFaces = false;
  60004. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  60005. });
  60006. _this.onAfterRenderObservable.add(function () {
  60007. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  60008. scene.getEngine().cullBackFaces = true;
  60009. scene._mirroredCameraPosition = null;
  60010. delete scene.clipPlane;
  60011. });
  60012. return _this;
  60013. }
  60014. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  60015. get: function () {
  60016. return this._blurRatio;
  60017. },
  60018. set: function (value) {
  60019. if (this._blurRatio === value) {
  60020. return;
  60021. }
  60022. this._blurRatio = value;
  60023. this._preparePostProcesses();
  60024. },
  60025. enumerable: true,
  60026. configurable: true
  60027. });
  60028. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  60029. set: function (value) {
  60030. this._adaptiveBlurKernel = value;
  60031. this._autoComputeBlurKernel();
  60032. },
  60033. enumerable: true,
  60034. configurable: true
  60035. });
  60036. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  60037. set: function (value) {
  60038. this.blurKernelX = value;
  60039. this.blurKernelY = value;
  60040. },
  60041. enumerable: true,
  60042. configurable: true
  60043. });
  60044. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  60045. get: function () {
  60046. return this._blurKernelX;
  60047. },
  60048. set: function (value) {
  60049. if (this._blurKernelX === value) {
  60050. return;
  60051. }
  60052. this._blurKernelX = value;
  60053. this._preparePostProcesses();
  60054. },
  60055. enumerable: true,
  60056. configurable: true
  60057. });
  60058. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  60059. get: function () {
  60060. return this._blurKernelY;
  60061. },
  60062. set: function (value) {
  60063. if (this._blurKernelY === value) {
  60064. return;
  60065. }
  60066. this._blurKernelY = value;
  60067. this._preparePostProcesses();
  60068. },
  60069. enumerable: true,
  60070. configurable: true
  60071. });
  60072. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  60073. var engine = this.getScene().getEngine();
  60074. var dw = this.getRenderWidth() / engine.getRenderWidth();
  60075. var dh = this.getRenderHeight() / engine.getRenderHeight();
  60076. this.blurKernelX = this._adaptiveBlurKernel * dw;
  60077. this.blurKernelY = this._adaptiveBlurKernel * dh;
  60078. };
  60079. MirrorTexture.prototype._onRatioRescale = function () {
  60080. if (this._sizeRatio) {
  60081. this.resize(this._initialSizeParameter);
  60082. if (!this._adaptiveBlurKernel) {
  60083. this._preparePostProcesses();
  60084. }
  60085. }
  60086. if (this._adaptiveBlurKernel) {
  60087. this._autoComputeBlurKernel();
  60088. }
  60089. };
  60090. MirrorTexture.prototype._preparePostProcesses = function () {
  60091. this.clearPostProcesses(true);
  60092. if (this._blurKernelX && this._blurKernelY) {
  60093. var engine = this.getScene().getEngine();
  60094. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60095. 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);
  60096. this._blurX.autoClear = false;
  60097. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  60098. this._blurX.inputTexture = this._texture;
  60099. }
  60100. else {
  60101. this._blurX.alwaysForcePOT = true;
  60102. }
  60103. 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);
  60104. this._blurY.autoClear = false;
  60105. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  60106. this.addPostProcess(this._blurX);
  60107. this.addPostProcess(this._blurY);
  60108. }
  60109. else {
  60110. if (this._blurY) {
  60111. this.removePostProcess(this._blurY);
  60112. this._blurY.dispose();
  60113. this._blurY = null;
  60114. }
  60115. if (this._blurX) {
  60116. this.removePostProcess(this._blurX);
  60117. this._blurX.dispose();
  60118. this._blurX = null;
  60119. }
  60120. }
  60121. };
  60122. MirrorTexture.prototype.clone = function () {
  60123. var scene = this.getScene();
  60124. if (!scene) {
  60125. return this;
  60126. }
  60127. var textureSize = this.getSize();
  60128. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  60129. // Base texture
  60130. newTexture.hasAlpha = this.hasAlpha;
  60131. newTexture.level = this.level;
  60132. // Mirror Texture
  60133. newTexture.mirrorPlane = this.mirrorPlane.clone();
  60134. if (this.renderList) {
  60135. newTexture.renderList = this.renderList.slice(0);
  60136. }
  60137. return newTexture;
  60138. };
  60139. MirrorTexture.prototype.serialize = function () {
  60140. if (!this.name) {
  60141. return null;
  60142. }
  60143. var serializationObject = _super.prototype.serialize.call(this);
  60144. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  60145. return serializationObject;
  60146. };
  60147. return MirrorTexture;
  60148. }(BABYLON.RenderTargetTexture));
  60149. BABYLON.MirrorTexture = MirrorTexture;
  60150. })(BABYLON || (BABYLON = {}));
  60151. //# sourceMappingURL=babylon.mirrorTexture.js.map
  60152. "use strict";
  60153. var BABYLON;
  60154. (function (BABYLON) {
  60155. /**
  60156. * Creates a refraction texture used by refraction channel of the standard material.
  60157. * @param name the texture name
  60158. * @param size size of the underlying texture
  60159. * @param scene root scene
  60160. */
  60161. var RefractionTexture = /** @class */ (function (_super) {
  60162. __extends(RefractionTexture, _super);
  60163. function RefractionTexture(name, size, scene, generateMipMaps) {
  60164. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  60165. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  60166. _this.depth = 2.0;
  60167. _this.onBeforeRenderObservable.add(function () {
  60168. scene.clipPlane = _this.refractionPlane;
  60169. });
  60170. _this.onAfterRenderObservable.add(function () {
  60171. delete scene.clipPlane;
  60172. });
  60173. return _this;
  60174. }
  60175. RefractionTexture.prototype.clone = function () {
  60176. var scene = this.getScene();
  60177. if (!scene) {
  60178. return this;
  60179. }
  60180. var textureSize = this.getSize();
  60181. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  60182. // Base texture
  60183. newTexture.hasAlpha = this.hasAlpha;
  60184. newTexture.level = this.level;
  60185. // Refraction Texture
  60186. newTexture.refractionPlane = this.refractionPlane.clone();
  60187. if (this.renderList) {
  60188. newTexture.renderList = this.renderList.slice(0);
  60189. }
  60190. newTexture.depth = this.depth;
  60191. return newTexture;
  60192. };
  60193. RefractionTexture.prototype.serialize = function () {
  60194. if (!this.name) {
  60195. return null;
  60196. }
  60197. var serializationObject = _super.prototype.serialize.call(this);
  60198. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  60199. serializationObject.depth = this.depth;
  60200. return serializationObject;
  60201. };
  60202. return RefractionTexture;
  60203. }(BABYLON.RenderTargetTexture));
  60204. BABYLON.RefractionTexture = RefractionTexture;
  60205. })(BABYLON || (BABYLON = {}));
  60206. //# sourceMappingURL=babylon.refractionTexture.js.map
  60207. "use strict";
  60208. var BABYLON;
  60209. (function (BABYLON) {
  60210. /**
  60211. * A class extending {BABYLON.Texture} allowing drawing on a texture
  60212. * @see http://doc.babylonjs.com/how_to/dynamictexture
  60213. */
  60214. var DynamicTexture = /** @class */ (function (_super) {
  60215. __extends(DynamicTexture, _super);
  60216. /**
  60217. * Creates a {BABYLON.DynamicTexture}
  60218. * @param name defines the name of the texture
  60219. * @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
  60220. * @param scene defines the scene where you want the texture
  60221. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  60222. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  60223. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  60224. */
  60225. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  60226. if (scene === void 0) { scene = null; }
  60227. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60228. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  60229. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  60230. _this.name = name;
  60231. _this._engine = _this.getScene().getEngine();
  60232. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60233. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60234. _this._generateMipMaps = generateMipMaps;
  60235. if (options.getContext) {
  60236. _this._canvas = options;
  60237. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  60238. }
  60239. else {
  60240. _this._canvas = document.createElement("canvas");
  60241. if (options.width) {
  60242. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  60243. }
  60244. else {
  60245. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  60246. }
  60247. }
  60248. var textureSize = _this.getSize();
  60249. _this._canvas.width = textureSize.width;
  60250. _this._canvas.height = textureSize.height;
  60251. _this._context = _this._canvas.getContext("2d");
  60252. return _this;
  60253. }
  60254. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  60255. /**
  60256. * Gets the current state of canRescale
  60257. */
  60258. get: function () {
  60259. return true;
  60260. },
  60261. enumerable: true,
  60262. configurable: true
  60263. });
  60264. DynamicTexture.prototype._recreate = function (textureSize) {
  60265. this._canvas.width = textureSize.width;
  60266. this._canvas.height = textureSize.height;
  60267. this.releaseInternalTexture();
  60268. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  60269. };
  60270. /**
  60271. * Scales the texture
  60272. * @param ratio the scale factor to apply to both width and height
  60273. */
  60274. DynamicTexture.prototype.scale = function (ratio) {
  60275. var textureSize = this.getSize();
  60276. textureSize.width *= ratio;
  60277. textureSize.height *= ratio;
  60278. this._recreate(textureSize);
  60279. };
  60280. /**
  60281. * Resizes the texture
  60282. * @param width the new width
  60283. * @param height the new height
  60284. */
  60285. DynamicTexture.prototype.scaleTo = function (width, height) {
  60286. var textureSize = this.getSize();
  60287. textureSize.width = width;
  60288. textureSize.height = height;
  60289. this._recreate(textureSize);
  60290. };
  60291. /**
  60292. * Gets the context of the canvas used by the texture
  60293. * @returns the canvas context of the dynamic texture
  60294. */
  60295. DynamicTexture.prototype.getContext = function () {
  60296. return this._context;
  60297. };
  60298. /**
  60299. * Clears the texture
  60300. */
  60301. DynamicTexture.prototype.clear = function () {
  60302. var size = this.getSize();
  60303. this._context.fillRect(0, 0, size.width, size.height);
  60304. };
  60305. /**
  60306. * Updates the texture
  60307. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  60308. */
  60309. DynamicTexture.prototype.update = function (invertY) {
  60310. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  60311. };
  60312. /**
  60313. * Draws text onto the texture
  60314. * @param text defines the text to be drawn
  60315. * @param x defines the placement of the text from the left
  60316. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  60317. * @param font defines the font to be used with font-style, font-size, font-name
  60318. * @param color defines the color used for the text
  60319. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  60320. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  60321. * @param update defines whether texture is immediately update (default is true)
  60322. */
  60323. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  60324. if (update === void 0) { update = true; }
  60325. var size = this.getSize();
  60326. if (clearColor) {
  60327. this._context.fillStyle = clearColor;
  60328. this._context.fillRect(0, 0, size.width, size.height);
  60329. }
  60330. this._context.font = font;
  60331. if (x === null || x === undefined) {
  60332. var textSize = this._context.measureText(text);
  60333. x = (size.width - textSize.width) / 2;
  60334. }
  60335. if (y === null || y === undefined) {
  60336. var fontSize = parseInt((font.replace(/\D/g, '')));
  60337. ;
  60338. y = (size.height / 2) + (fontSize / 3.65);
  60339. }
  60340. this._context.fillStyle = color;
  60341. this._context.fillText(text, x, y);
  60342. if (update) {
  60343. this.update(invertY);
  60344. }
  60345. };
  60346. /**
  60347. * Clones the texture
  60348. * @returns the clone of the texture.
  60349. */
  60350. DynamicTexture.prototype.clone = function () {
  60351. var scene = this.getScene();
  60352. if (!scene) {
  60353. return this;
  60354. }
  60355. var textureSize = this.getSize();
  60356. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  60357. // Base texture
  60358. newTexture.hasAlpha = this.hasAlpha;
  60359. newTexture.level = this.level;
  60360. // Dynamic Texture
  60361. newTexture.wrapU = this.wrapU;
  60362. newTexture.wrapV = this.wrapV;
  60363. return newTexture;
  60364. };
  60365. /** @ignore */
  60366. DynamicTexture.prototype._rebuild = function () {
  60367. this.update();
  60368. };
  60369. return DynamicTexture;
  60370. }(BABYLON.Texture));
  60371. BABYLON.DynamicTexture = DynamicTexture;
  60372. })(BABYLON || (BABYLON = {}));
  60373. //# sourceMappingURL=babylon.dynamicTexture.js.map
  60374. "use strict";
  60375. var BABYLON;
  60376. (function (BABYLON) {
  60377. var VideoTexture = /** @class */ (function (_super) {
  60378. __extends(VideoTexture, _super);
  60379. /**
  60380. * Creates a video texture.
  60381. * Sample : https://doc.babylonjs.com/how_to/video_texture
  60382. * @param {string | null} name optional name, will detect from video source, if not defined
  60383. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  60384. * @param {BABYLON.Scene} scene is obviously the current scene.
  60385. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  60386. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  60387. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  60388. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  60389. */
  60390. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  60391. if (generateMipMaps === void 0) { generateMipMaps = false; }
  60392. if (invertY === void 0) { invertY = false; }
  60393. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60394. if (settings === void 0) { settings = {
  60395. autoPlay: true,
  60396. loop: true,
  60397. autoUpdateTexture: true,
  60398. }; }
  60399. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  60400. _this._createInternalTexture = function () {
  60401. if (_this._texture != null) {
  60402. return;
  60403. }
  60404. if (!_this._engine.needPOTTextures ||
  60405. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  60406. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60407. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60408. }
  60409. else {
  60410. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60411. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60412. _this._generateMipMaps = false;
  60413. }
  60414. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  60415. _this._texture.isReady = true;
  60416. _this._updateInternalTexture();
  60417. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  60418. _this.onLoadObservable.notifyObservers(_this);
  60419. }
  60420. };
  60421. _this.reset = function () {
  60422. if (_this._texture == null) {
  60423. return;
  60424. }
  60425. _this._texture.dispose();
  60426. _this._texture = null;
  60427. };
  60428. _this._updateInternalTexture = function (e) {
  60429. if (_this._texture == null || !_this._texture.isReady) {
  60430. return;
  60431. }
  60432. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  60433. return;
  60434. }
  60435. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  60436. };
  60437. _this._engine = _this.getScene().getEngine();
  60438. _this._generateMipMaps = generateMipMaps;
  60439. _this._samplingMode = samplingMode;
  60440. _this.autoUpdateTexture = settings.autoUpdateTexture;
  60441. _this.name = name || _this._getName(src);
  60442. _this.video = _this._getVideo(src);
  60443. if (settings.autoPlay !== undefined) {
  60444. _this.video.autoplay = settings.autoPlay;
  60445. }
  60446. if (settings.loop !== undefined) {
  60447. _this.video.loop = settings.loop;
  60448. }
  60449. _this.video.addEventListener("canplay", _this._createInternalTexture);
  60450. _this.video.addEventListener("paused", _this._updateInternalTexture);
  60451. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  60452. _this.video.addEventListener("emptied", _this.reset);
  60453. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  60454. _this._createInternalTexture();
  60455. }
  60456. return _this;
  60457. }
  60458. VideoTexture.prototype._getName = function (src) {
  60459. if (src instanceof HTMLVideoElement) {
  60460. return src.currentSrc;
  60461. }
  60462. if (typeof src === "object") {
  60463. return src.toString();
  60464. }
  60465. return src;
  60466. };
  60467. ;
  60468. VideoTexture.prototype._getVideo = function (src) {
  60469. if (src instanceof HTMLVideoElement) {
  60470. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  60471. return src;
  60472. }
  60473. var video = document.createElement("video");
  60474. if (typeof src === "string") {
  60475. BABYLON.Tools.SetCorsBehavior(src, video);
  60476. video.src = src;
  60477. }
  60478. else {
  60479. BABYLON.Tools.SetCorsBehavior(src[0], video);
  60480. src.forEach(function (url) {
  60481. var source = document.createElement("source");
  60482. source.src = url;
  60483. video.appendChild(source);
  60484. });
  60485. }
  60486. return video;
  60487. };
  60488. ;
  60489. /**
  60490. * Internal method to initiate `update`.
  60491. */
  60492. VideoTexture.prototype._rebuild = function () {
  60493. this.update();
  60494. };
  60495. /**
  60496. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  60497. */
  60498. VideoTexture.prototype.update = function () {
  60499. if (!this.autoUpdateTexture) {
  60500. // Expecting user to call `updateTexture` manually
  60501. return;
  60502. }
  60503. this.updateTexture(true);
  60504. };
  60505. /**
  60506. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  60507. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  60508. */
  60509. VideoTexture.prototype.updateTexture = function (isVisible) {
  60510. if (!isVisible) {
  60511. return;
  60512. }
  60513. if (this.video.paused) {
  60514. return;
  60515. }
  60516. this._updateInternalTexture();
  60517. };
  60518. /**
  60519. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  60520. * @param url New url.
  60521. */
  60522. VideoTexture.prototype.updateURL = function (url) {
  60523. this.video.src = url;
  60524. };
  60525. VideoTexture.prototype.dispose = function () {
  60526. _super.prototype.dispose.call(this);
  60527. this.video.removeEventListener("canplay", this._createInternalTexture);
  60528. this.video.removeEventListener("paused", this._updateInternalTexture);
  60529. this.video.removeEventListener("seeked", this._updateInternalTexture);
  60530. this.video.removeEventListener("emptied", this.reset);
  60531. this.video.pause();
  60532. };
  60533. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  60534. var video = document.createElement("video");
  60535. var constraintsDeviceId;
  60536. if (constraints && constraints.deviceId) {
  60537. constraintsDeviceId = {
  60538. exact: constraints.deviceId,
  60539. };
  60540. }
  60541. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  60542. if (navigator.mediaDevices) {
  60543. navigator.mediaDevices.getUserMedia({ video: constraints })
  60544. .then(function (stream) {
  60545. if (video.mozSrcObject !== undefined) {
  60546. // hack for Firefox < 19
  60547. video.mozSrcObject = stream;
  60548. }
  60549. else {
  60550. video.srcObject = stream;
  60551. }
  60552. var onPlaying = function () {
  60553. if (onReady) {
  60554. onReady(new VideoTexture("video", video, scene, true, true));
  60555. }
  60556. video.removeEventListener("playing", onPlaying);
  60557. };
  60558. video.addEventListener("playing", onPlaying);
  60559. video.play();
  60560. })
  60561. .catch(function (err) {
  60562. BABYLON.Tools.Error(err.name);
  60563. });
  60564. }
  60565. else {
  60566. navigator.getUserMedia =
  60567. navigator.getUserMedia ||
  60568. navigator.webkitGetUserMedia ||
  60569. navigator.mozGetUserMedia ||
  60570. navigator.msGetUserMedia;
  60571. if (navigator.getUserMedia) {
  60572. navigator.getUserMedia({
  60573. video: {
  60574. deviceId: constraintsDeviceId,
  60575. width: {
  60576. min: (constraints && constraints.minWidth) || 256,
  60577. max: (constraints && constraints.maxWidth) || 640,
  60578. },
  60579. height: {
  60580. min: (constraints && constraints.minHeight) || 256,
  60581. max: (constraints && constraints.maxHeight) || 480,
  60582. },
  60583. },
  60584. }, function (stream) {
  60585. if (video.mozSrcObject !== undefined) {
  60586. // hack for Firefox < 19
  60587. video.mozSrcObject = stream;
  60588. }
  60589. else {
  60590. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  60591. }
  60592. video.play();
  60593. if (onReady) {
  60594. onReady(new VideoTexture("video", video, scene, true, true));
  60595. }
  60596. }, function (e) {
  60597. BABYLON.Tools.Error(e.name);
  60598. });
  60599. }
  60600. }
  60601. };
  60602. return VideoTexture;
  60603. }(BABYLON.Texture));
  60604. BABYLON.VideoTexture = VideoTexture;
  60605. })(BABYLON || (BABYLON = {}));
  60606. //# sourceMappingURL=babylon.videoTexture.js.map
  60607. "use strict";
  60608. var BABYLON;
  60609. (function (BABYLON) {
  60610. var RawTexture = /** @class */ (function (_super) {
  60611. __extends(RawTexture, _super);
  60612. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  60613. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60614. if (invertY === void 0) { invertY = false; }
  60615. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60616. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60617. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  60618. _this.format = format;
  60619. _this._engine = scene.getEngine();
  60620. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  60621. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60622. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60623. return _this;
  60624. }
  60625. RawTexture.prototype.update = function (data) {
  60626. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  60627. };
  60628. // Statics
  60629. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60630. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60631. if (invertY === void 0) { invertY = false; }
  60632. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60633. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  60634. };
  60635. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60636. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60637. if (invertY === void 0) { invertY = false; }
  60638. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60639. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  60640. };
  60641. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60642. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60643. if (invertY === void 0) { invertY = false; }
  60644. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60645. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  60646. };
  60647. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  60648. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60649. if (invertY === void 0) { invertY = false; }
  60650. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60651. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60652. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  60653. };
  60654. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  60655. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60656. if (invertY === void 0) { invertY = false; }
  60657. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60658. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60659. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  60660. };
  60661. return RawTexture;
  60662. }(BABYLON.Texture));
  60663. BABYLON.RawTexture = RawTexture;
  60664. })(BABYLON || (BABYLON = {}));
  60665. //# sourceMappingURL=babylon.rawTexture.js.map
  60666. "use strict";
  60667. var BABYLON;
  60668. (function (BABYLON) {
  60669. /**
  60670. * PostProcess can be used to apply a shader to a texture after it has been rendered
  60671. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  60672. */
  60673. var PostProcess = /** @class */ (function () {
  60674. /**
  60675. * Creates a new instance PostProcess
  60676. * @param name The name of the PostProcess.
  60677. * @param fragmentUrl The url of the fragment shader to be used.
  60678. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  60679. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  60680. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  60681. * @param camera The camera to apply the render pass to.
  60682. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  60683. * @param engine The engine which the post process will be applied. (default: current engine)
  60684. * @param reusable If the post process can be reused on the same frame. (default: false)
  60685. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  60686. * @param textureType Type of textures used when performing the post process. (default: 0)
  60687. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  60688. * @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
  60689. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  60690. */
  60691. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  60692. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  60693. if (defines === void 0) { defines = null; }
  60694. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60695. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  60696. if (blockCompilation === void 0) { blockCompilation = false; }
  60697. this.name = name;
  60698. /**
  60699. * Width of the texture to apply the post process on
  60700. */
  60701. this.width = -1;
  60702. /**
  60703. * Height of the texture to apply the post process on
  60704. */
  60705. this.height = -1;
  60706. /**
  60707. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  60708. */
  60709. this._outputTexture = null;
  60710. /**
  60711. * If the buffer needs to be cleared before applying the post process. (default: true)
  60712. * Should be set to false if shader will overwrite all previous pixels.
  60713. */
  60714. this.autoClear = true;
  60715. /**
  60716. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  60717. */
  60718. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  60719. /**
  60720. * Animations to be used for the post processing
  60721. */
  60722. this.animations = new Array();
  60723. /**
  60724. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  60725. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  60726. */
  60727. this.enablePixelPerfectMode = false;
  60728. /**
  60729. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  60730. */
  60731. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  60732. /**
  60733. * Force textures to be a power of two (default: false)
  60734. */
  60735. this.alwaysForcePOT = false;
  60736. /**
  60737. * Number of sample textures (default: 1)
  60738. */
  60739. this.samples = 1;
  60740. /**
  60741. * Modify the scale of the post process to be the same as the viewport (default: false)
  60742. */
  60743. this.adaptScaleToCurrentViewport = false;
  60744. this._reusable = false;
  60745. /**
  60746. * Smart array of input and output textures for the post process.
  60747. */
  60748. this._textures = new BABYLON.SmartArray(2);
  60749. /**
  60750. * The index in _textures that corresponds to the output texture.
  60751. */
  60752. this._currentRenderTextureInd = 0;
  60753. this._scaleRatio = new BABYLON.Vector2(1, 1);
  60754. this._texelSize = BABYLON.Vector2.Zero();
  60755. // Events
  60756. /**
  60757. * An event triggered when the postprocess is activated.
  60758. */
  60759. this.onActivateObservable = new BABYLON.Observable();
  60760. /**
  60761. * An event triggered when the postprocess changes its size.
  60762. */
  60763. this.onSizeChangedObservable = new BABYLON.Observable();
  60764. /**
  60765. * An event triggered when the postprocess applies its effect.
  60766. */
  60767. this.onApplyObservable = new BABYLON.Observable();
  60768. /**
  60769. * An event triggered before rendering the postprocess
  60770. */
  60771. this.onBeforeRenderObservable = new BABYLON.Observable();
  60772. /**
  60773. * An event triggered after rendering the postprocess
  60774. */
  60775. this.onAfterRenderObservable = new BABYLON.Observable();
  60776. if (camera != null) {
  60777. this._camera = camera;
  60778. this._scene = camera.getScene();
  60779. camera.attachPostProcess(this);
  60780. this._engine = this._scene.getEngine();
  60781. this._scene.postProcesses.push(this);
  60782. }
  60783. else if (engine) {
  60784. this._engine = engine;
  60785. this._engine.postProcesses.push(this);
  60786. }
  60787. this._options = options;
  60788. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  60789. this._reusable = reusable || false;
  60790. this._textureType = textureType;
  60791. this._samplers = samplers || [];
  60792. this._samplers.push("textureSampler");
  60793. this._fragmentUrl = fragmentUrl;
  60794. this._vertexUrl = vertexUrl;
  60795. this._parameters = parameters || [];
  60796. this._parameters.push("scale");
  60797. this._indexParameters = indexParameters;
  60798. if (!blockCompilation) {
  60799. this.updateEffect(defines);
  60800. }
  60801. }
  60802. Object.defineProperty(PostProcess.prototype, "onActivate", {
  60803. /**
  60804. * A function that is added to the onActivateObservable
  60805. */
  60806. set: function (callback) {
  60807. if (this._onActivateObserver) {
  60808. this.onActivateObservable.remove(this._onActivateObserver);
  60809. }
  60810. if (callback) {
  60811. this._onActivateObserver = this.onActivateObservable.add(callback);
  60812. }
  60813. },
  60814. enumerable: true,
  60815. configurable: true
  60816. });
  60817. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  60818. /**
  60819. * A function that is added to the onSizeChangedObservable
  60820. */
  60821. set: function (callback) {
  60822. if (this._onSizeChangedObserver) {
  60823. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  60824. }
  60825. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  60826. },
  60827. enumerable: true,
  60828. configurable: true
  60829. });
  60830. Object.defineProperty(PostProcess.prototype, "onApply", {
  60831. /**
  60832. * A function that is added to the onApplyObservable
  60833. */
  60834. set: function (callback) {
  60835. if (this._onApplyObserver) {
  60836. this.onApplyObservable.remove(this._onApplyObserver);
  60837. }
  60838. this._onApplyObserver = this.onApplyObservable.add(callback);
  60839. },
  60840. enumerable: true,
  60841. configurable: true
  60842. });
  60843. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  60844. /**
  60845. * A function that is added to the onBeforeRenderObservable
  60846. */
  60847. set: function (callback) {
  60848. if (this._onBeforeRenderObserver) {
  60849. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  60850. }
  60851. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  60852. },
  60853. enumerable: true,
  60854. configurable: true
  60855. });
  60856. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  60857. /**
  60858. * A function that is added to the onAfterRenderObservable
  60859. */
  60860. set: function (callback) {
  60861. if (this._onAfterRenderObserver) {
  60862. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  60863. }
  60864. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  60865. },
  60866. enumerable: true,
  60867. configurable: true
  60868. });
  60869. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  60870. /**
  60871. * 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
  60872. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  60873. */
  60874. get: function () {
  60875. return this._textures.data[this._currentRenderTextureInd];
  60876. },
  60877. set: function (value) {
  60878. this._forcedOutputTexture = value;
  60879. },
  60880. enumerable: true,
  60881. configurable: true
  60882. });
  60883. /**
  60884. * Gets the camera which post process is applied to.
  60885. * @returns The camera the post process is applied to.
  60886. */
  60887. PostProcess.prototype.getCamera = function () {
  60888. return this._camera;
  60889. };
  60890. Object.defineProperty(PostProcess.prototype, "texelSize", {
  60891. /**
  60892. * Gets the texel size of the postprocess.
  60893. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  60894. */
  60895. get: function () {
  60896. if (this._shareOutputWithPostProcess) {
  60897. return this._shareOutputWithPostProcess.texelSize;
  60898. }
  60899. if (this._forcedOutputTexture) {
  60900. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  60901. }
  60902. return this._texelSize;
  60903. },
  60904. enumerable: true,
  60905. configurable: true
  60906. });
  60907. /**
  60908. * Gets the engine which this post process belongs to.
  60909. * @returns The engine the post process was enabled with.
  60910. */
  60911. PostProcess.prototype.getEngine = function () {
  60912. return this._engine;
  60913. };
  60914. /**
  60915. * The effect that is created when initializing the post process.
  60916. * @returns The created effect corrisponding the the postprocess.
  60917. */
  60918. PostProcess.prototype.getEffect = function () {
  60919. return this._effect;
  60920. };
  60921. /**
  60922. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  60923. * @param postProcess The post process to share the output with.
  60924. * @returns This post process.
  60925. */
  60926. PostProcess.prototype.shareOutputWith = function (postProcess) {
  60927. this._disposeTextures();
  60928. this._shareOutputWithPostProcess = postProcess;
  60929. return this;
  60930. };
  60931. /**
  60932. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  60933. * This should be called if the post process that shares output with this post process is disabled/disposed.
  60934. */
  60935. PostProcess.prototype.useOwnOutput = function () {
  60936. if (this._textures.length == 0) {
  60937. this._textures = new BABYLON.SmartArray(2);
  60938. }
  60939. this._shareOutputWithPostProcess = null;
  60940. };
  60941. /**
  60942. * Updates the effect with the current post process compile time values and recompiles the shader.
  60943. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  60944. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  60945. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  60946. * @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
  60947. * @param onCompiled Called when the shader has been compiled.
  60948. * @param onError Called if there is an error when compiling a shader.
  60949. */
  60950. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  60951. if (defines === void 0) { defines = null; }
  60952. if (uniforms === void 0) { uniforms = null; }
  60953. if (samplers === void 0) { samplers = null; }
  60954. 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);
  60955. };
  60956. /**
  60957. * The post process is reusable if it can be used multiple times within one frame.
  60958. * @returns If the post process is reusable
  60959. */
  60960. PostProcess.prototype.isReusable = function () {
  60961. return this._reusable;
  60962. };
  60963. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  60964. PostProcess.prototype.markTextureDirty = function () {
  60965. this.width = -1;
  60966. };
  60967. /**
  60968. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  60969. * 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.
  60970. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  60971. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  60972. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  60973. * @returns The target texture that was bound to be written to.
  60974. */
  60975. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  60976. var _this = this;
  60977. if (sourceTexture === void 0) { sourceTexture = null; }
  60978. camera = camera || this._camera;
  60979. var scene = camera.getScene();
  60980. var engine = scene.getEngine();
  60981. var maxSize = engine.getCaps().maxTextureSize;
  60982. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  60983. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  60984. // 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
  60985. var webVRCamera = camera.parent;
  60986. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  60987. requiredWidth /= 2;
  60988. }
  60989. var desiredWidth = (this._options.width || requiredWidth);
  60990. var desiredHeight = this._options.height || requiredHeight;
  60991. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  60992. if (this.adaptScaleToCurrentViewport) {
  60993. var currentViewport = engine.currentViewport;
  60994. if (currentViewport) {
  60995. desiredWidth *= currentViewport.width;
  60996. desiredHeight *= currentViewport.height;
  60997. }
  60998. }
  60999. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  61000. if (!this._options.width) {
  61001. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  61002. }
  61003. if (!this._options.height) {
  61004. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  61005. }
  61006. }
  61007. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  61008. if (this._textures.length > 0) {
  61009. for (var i = 0; i < this._textures.length; i++) {
  61010. this._engine._releaseTexture(this._textures.data[i]);
  61011. }
  61012. this._textures.reset();
  61013. }
  61014. this.width = desiredWidth;
  61015. this.height = desiredHeight;
  61016. var textureSize = { width: this.width, height: this.height };
  61017. var textureOptions = {
  61018. generateMipMaps: false,
  61019. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  61020. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  61021. samplingMode: this.renderTargetSamplingMode,
  61022. type: this._textureType
  61023. };
  61024. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  61025. if (this._reusable) {
  61026. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  61027. }
  61028. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  61029. this.onSizeChangedObservable.notifyObservers(this);
  61030. }
  61031. this._textures.forEach(function (texture) {
  61032. if (texture.samples !== _this.samples) {
  61033. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  61034. }
  61035. });
  61036. }
  61037. var target;
  61038. if (this._shareOutputWithPostProcess) {
  61039. target = this._shareOutputWithPostProcess.inputTexture;
  61040. }
  61041. else if (this._forcedOutputTexture) {
  61042. target = this._forcedOutputTexture;
  61043. this.width = this._forcedOutputTexture.width;
  61044. this.height = this._forcedOutputTexture.height;
  61045. }
  61046. else {
  61047. target = this.inputTexture;
  61048. }
  61049. // Bind the input of this post process to be used as the output of the previous post process.
  61050. if (this.enablePixelPerfectMode) {
  61051. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  61052. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  61053. }
  61054. else {
  61055. this._scaleRatio.copyFromFloats(1, 1);
  61056. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  61057. }
  61058. this.onActivateObservable.notifyObservers(camera);
  61059. // Clear
  61060. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  61061. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  61062. }
  61063. if (this._reusable) {
  61064. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  61065. }
  61066. return target;
  61067. };
  61068. Object.defineProperty(PostProcess.prototype, "isSupported", {
  61069. /**
  61070. * If the post process is supported.
  61071. */
  61072. get: function () {
  61073. return this._effect.isSupported;
  61074. },
  61075. enumerable: true,
  61076. configurable: true
  61077. });
  61078. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  61079. /**
  61080. * The aspect ratio of the output texture.
  61081. */
  61082. get: function () {
  61083. if (this._shareOutputWithPostProcess) {
  61084. return this._shareOutputWithPostProcess.aspectRatio;
  61085. }
  61086. if (this._forcedOutputTexture) {
  61087. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  61088. }
  61089. return this.width / this.height;
  61090. },
  61091. enumerable: true,
  61092. configurable: true
  61093. });
  61094. /**
  61095. * Get a value indicating if the post-process is ready to be used
  61096. * @returns true if the post-process is ready (shader is compiled)
  61097. */
  61098. PostProcess.prototype.isReady = function () {
  61099. return this._effect && this._effect.isReady();
  61100. };
  61101. /**
  61102. * Binds all textures and uniforms to the shader, this will be run on every pass.
  61103. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  61104. */
  61105. PostProcess.prototype.apply = function () {
  61106. // Check
  61107. if (!this._effect || !this._effect.isReady())
  61108. return null;
  61109. // States
  61110. this._engine.enableEffect(this._effect);
  61111. this._engine.setState(false);
  61112. this._engine.setDepthBuffer(false);
  61113. this._engine.setDepthWrite(false);
  61114. // Alpha
  61115. this._engine.setAlphaMode(this.alphaMode);
  61116. if (this.alphaConstants) {
  61117. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  61118. }
  61119. // Bind the output texture of the preivous post process as the input to this post process.
  61120. var source;
  61121. if (this._shareOutputWithPostProcess) {
  61122. source = this._shareOutputWithPostProcess.inputTexture;
  61123. }
  61124. else if (this._forcedOutputTexture) {
  61125. source = this._forcedOutputTexture;
  61126. }
  61127. else {
  61128. source = this.inputTexture;
  61129. }
  61130. this._effect._bindTexture("textureSampler", source);
  61131. // Parameters
  61132. this._effect.setVector2("scale", this._scaleRatio);
  61133. this.onApplyObservable.notifyObservers(this._effect);
  61134. return this._effect;
  61135. };
  61136. PostProcess.prototype._disposeTextures = function () {
  61137. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  61138. return;
  61139. }
  61140. if (this._textures.length > 0) {
  61141. for (var i = 0; i < this._textures.length; i++) {
  61142. this._engine._releaseTexture(this._textures.data[i]);
  61143. }
  61144. }
  61145. this._textures.dispose();
  61146. };
  61147. /**
  61148. * Disposes the post process.
  61149. * @param camera The camera to dispose the post process on.
  61150. */
  61151. PostProcess.prototype.dispose = function (camera) {
  61152. camera = camera || this._camera;
  61153. this._disposeTextures();
  61154. if (this._scene) {
  61155. var index_1 = this._scene.postProcesses.indexOf(this);
  61156. if (index_1 !== -1) {
  61157. this._scene.postProcesses.splice(index_1, 1);
  61158. }
  61159. }
  61160. else {
  61161. var index_2 = this._engine.postProcesses.indexOf(this);
  61162. if (index_2 !== -1) {
  61163. this._engine.postProcesses.splice(index_2, 1);
  61164. }
  61165. }
  61166. if (!camera) {
  61167. return;
  61168. }
  61169. camera.detachPostProcess(this);
  61170. var index = camera._postProcesses.indexOf(this);
  61171. if (index === 0 && camera._postProcesses.length > 0) {
  61172. var firstPostProcess = this._camera._getFirstPostProcess();
  61173. if (firstPostProcess) {
  61174. firstPostProcess.markTextureDirty();
  61175. }
  61176. }
  61177. this.onActivateObservable.clear();
  61178. this.onAfterRenderObservable.clear();
  61179. this.onApplyObservable.clear();
  61180. this.onBeforeRenderObservable.clear();
  61181. this.onSizeChangedObservable.clear();
  61182. };
  61183. return PostProcess;
  61184. }());
  61185. BABYLON.PostProcess = PostProcess;
  61186. })(BABYLON || (BABYLON = {}));
  61187. //# sourceMappingURL=babylon.postProcess.js.map
  61188. "use strict";
  61189. var BABYLON;
  61190. (function (BABYLON) {
  61191. var PassPostProcess = /** @class */ (function (_super) {
  61192. __extends(PassPostProcess, _super);
  61193. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  61194. if (camera === void 0) { camera = null; }
  61195. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61196. if (blockCompilation === void 0) { blockCompilation = false; }
  61197. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  61198. }
  61199. return PassPostProcess;
  61200. }(BABYLON.PostProcess));
  61201. BABYLON.PassPostProcess = PassPostProcess;
  61202. })(BABYLON || (BABYLON = {}));
  61203. //# sourceMappingURL=babylon.passPostProcess.js.map
  61204. "use strict";
  61205. var __assign = (this && this.__assign) || Object.assign || function(t) {
  61206. for (var s, i = 1, n = arguments.length; i < n; i++) {
  61207. s = arguments[i];
  61208. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  61209. t[p] = s[p];
  61210. }
  61211. return t;
  61212. };
  61213. var BABYLON;
  61214. (function (BABYLON) {
  61215. /**
  61216. * Default implementation IShadowGenerator.
  61217. * This is the main object responsible of generating shadows in the framework.
  61218. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  61219. */
  61220. var ShadowGenerator = /** @class */ (function () {
  61221. /**
  61222. * Creates a ShadowGenerator object.
  61223. * A ShadowGenerator is the required tool to use the shadows.
  61224. * Each light casting shadows needs to use its own ShadowGenerator.
  61225. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  61226. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  61227. * @param light The light object generating the shadows.
  61228. * @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.
  61229. */
  61230. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  61231. this._bias = 0.00005;
  61232. this._normalBias = 0;
  61233. this._blurBoxOffset = 1;
  61234. this._blurScale = 2;
  61235. this._blurKernel = 1;
  61236. this._useKernelBlur = false;
  61237. this._filter = ShadowGenerator.FILTER_NONE;
  61238. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  61239. this._contactHardeningLightSizeUVRatio = 0.1;
  61240. this._darkness = 0;
  61241. this._transparencyShadow = false;
  61242. /**
  61243. * Controls the extent to which the shadows fade out at the edge of the frustum
  61244. * Used only by directionals and spots
  61245. */
  61246. this.frustumEdgeFalloff = 0;
  61247. /**
  61248. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  61249. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  61250. * It might on the other hand introduce peter panning.
  61251. */
  61252. this.forceBackFacesOnly = false;
  61253. this._lightDirection = BABYLON.Vector3.Zero();
  61254. this._viewMatrix = BABYLON.Matrix.Zero();
  61255. this._projectionMatrix = BABYLON.Matrix.Zero();
  61256. this._transformMatrix = BABYLON.Matrix.Zero();
  61257. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  61258. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  61259. this._currentFaceIndex = 0;
  61260. this._currentFaceIndexCache = 0;
  61261. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  61262. this._mapSize = mapSize;
  61263. this._light = light;
  61264. this._scene = light.getScene();
  61265. light._shadowGenerator = this;
  61266. // Texture type fallback from float to int if not supported.
  61267. var caps = this._scene.getEngine().getCaps();
  61268. if (!useFullFloatFirst) {
  61269. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  61270. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  61271. }
  61272. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  61273. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  61274. }
  61275. else {
  61276. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  61277. }
  61278. }
  61279. else {
  61280. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  61281. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  61282. }
  61283. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  61284. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  61285. }
  61286. else {
  61287. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  61288. }
  61289. }
  61290. this._initializeGenerator();
  61291. this._applyFilterValues();
  61292. }
  61293. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  61294. /**
  61295. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  61296. */
  61297. get: function () {
  61298. return this._bias;
  61299. },
  61300. /**
  61301. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  61302. */
  61303. set: function (bias) {
  61304. this._bias = bias;
  61305. },
  61306. enumerable: true,
  61307. configurable: true
  61308. });
  61309. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  61310. /**
  61311. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  61312. */
  61313. get: function () {
  61314. return this._normalBias;
  61315. },
  61316. /**
  61317. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  61318. */
  61319. set: function (normalBias) {
  61320. this._normalBias = normalBias;
  61321. },
  61322. enumerable: true,
  61323. configurable: true
  61324. });
  61325. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  61326. /**
  61327. * Gets the blur box offset: offset applied during the blur pass.
  61328. * Only usefull if useKernelBlur = false
  61329. */
  61330. get: function () {
  61331. return this._blurBoxOffset;
  61332. },
  61333. /**
  61334. * Sets the blur box offset: offset applied during the blur pass.
  61335. * Only usefull if useKernelBlur = false
  61336. */
  61337. set: function (value) {
  61338. if (this._blurBoxOffset === value) {
  61339. return;
  61340. }
  61341. this._blurBoxOffset = value;
  61342. this._disposeBlurPostProcesses();
  61343. },
  61344. enumerable: true,
  61345. configurable: true
  61346. });
  61347. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  61348. /**
  61349. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  61350. * 2 means half of the size.
  61351. */
  61352. get: function () {
  61353. return this._blurScale;
  61354. },
  61355. /**
  61356. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  61357. * 2 means half of the size.
  61358. */
  61359. set: function (value) {
  61360. if (this._blurScale === value) {
  61361. return;
  61362. }
  61363. this._blurScale = value;
  61364. this._disposeBlurPostProcesses();
  61365. },
  61366. enumerable: true,
  61367. configurable: true
  61368. });
  61369. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  61370. /**
  61371. * Gets the blur kernel: kernel size of the blur pass.
  61372. * Only usefull if useKernelBlur = true
  61373. */
  61374. get: function () {
  61375. return this._blurKernel;
  61376. },
  61377. /**
  61378. * Sets the blur kernel: kernel size of the blur pass.
  61379. * Only usefull if useKernelBlur = true
  61380. */
  61381. set: function (value) {
  61382. if (this._blurKernel === value) {
  61383. return;
  61384. }
  61385. this._blurKernel = value;
  61386. this._disposeBlurPostProcesses();
  61387. },
  61388. enumerable: true,
  61389. configurable: true
  61390. });
  61391. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  61392. /**
  61393. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  61394. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  61395. */
  61396. get: function () {
  61397. return this._useKernelBlur;
  61398. },
  61399. /**
  61400. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  61401. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  61402. */
  61403. set: function (value) {
  61404. if (this._useKernelBlur === value) {
  61405. return;
  61406. }
  61407. this._useKernelBlur = value;
  61408. this._disposeBlurPostProcesses();
  61409. },
  61410. enumerable: true,
  61411. configurable: true
  61412. });
  61413. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  61414. /**
  61415. * Gets the depth scale used in ESM mode.
  61416. */
  61417. get: function () {
  61418. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  61419. },
  61420. /**
  61421. * Sets the depth scale used in ESM mode.
  61422. * This can override the scale stored on the light.
  61423. */
  61424. set: function (value) {
  61425. this._depthScale = value;
  61426. },
  61427. enumerable: true,
  61428. configurable: true
  61429. });
  61430. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  61431. /**
  61432. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  61433. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  61434. */
  61435. get: function () {
  61436. return this._filter;
  61437. },
  61438. /**
  61439. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  61440. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  61441. */
  61442. set: function (value) {
  61443. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  61444. if (this._light.needCube()) {
  61445. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  61446. this.useExponentialShadowMap = true;
  61447. return;
  61448. }
  61449. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  61450. this.useCloseExponentialShadowMap = true;
  61451. return;
  61452. }
  61453. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  61454. this.usePoissonSampling = true;
  61455. return;
  61456. }
  61457. }
  61458. // Weblg1 fallback for PCF.
  61459. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  61460. if (this._scene.getEngine().webGLVersion === 1) {
  61461. this.usePoissonSampling = true;
  61462. return;
  61463. }
  61464. }
  61465. if (this._filter === value) {
  61466. return;
  61467. }
  61468. this._filter = value;
  61469. this._disposeBlurPostProcesses();
  61470. this._applyFilterValues();
  61471. this._light._markMeshesAsLightDirty();
  61472. },
  61473. enumerable: true,
  61474. configurable: true
  61475. });
  61476. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  61477. /**
  61478. * Gets if the current filter is set to Poisson Sampling.
  61479. */
  61480. get: function () {
  61481. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  61482. },
  61483. /**
  61484. * Sets the current filter to Poisson Sampling.
  61485. */
  61486. set: function (value) {
  61487. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  61488. return;
  61489. }
  61490. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  61491. },
  61492. enumerable: true,
  61493. configurable: true
  61494. });
  61495. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  61496. /**
  61497. * Gets if the current filter is set to VSM.
  61498. * DEPRECATED. Should use useExponentialShadowMap instead.
  61499. */
  61500. get: function () {
  61501. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  61502. return this.useExponentialShadowMap;
  61503. },
  61504. /**
  61505. * Sets the current filter is to VSM.
  61506. * DEPRECATED. Should use useExponentialShadowMap instead.
  61507. */
  61508. set: function (value) {
  61509. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  61510. this.useExponentialShadowMap = value;
  61511. },
  61512. enumerable: true,
  61513. configurable: true
  61514. });
  61515. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  61516. /**
  61517. * Gets if the current filter is set to blurred VSM.
  61518. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  61519. */
  61520. get: function () {
  61521. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  61522. return this.useBlurExponentialShadowMap;
  61523. },
  61524. /**
  61525. * Sets the current filter is to blurred VSM.
  61526. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  61527. */
  61528. set: function (value) {
  61529. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  61530. this.useBlurExponentialShadowMap = value;
  61531. },
  61532. enumerable: true,
  61533. configurable: true
  61534. });
  61535. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  61536. /**
  61537. * Gets if the current filter is set to ESM.
  61538. */
  61539. get: function () {
  61540. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  61541. },
  61542. /**
  61543. * Sets the current filter is to ESM.
  61544. */
  61545. set: function (value) {
  61546. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  61547. return;
  61548. }
  61549. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61550. },
  61551. enumerable: true,
  61552. configurable: true
  61553. });
  61554. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  61555. /**
  61556. * Gets if the current filter is set to filtered ESM.
  61557. */
  61558. get: function () {
  61559. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  61560. },
  61561. /**
  61562. * Gets if the current filter is set to filtered ESM.
  61563. */
  61564. set: function (value) {
  61565. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  61566. return;
  61567. }
  61568. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61569. },
  61570. enumerable: true,
  61571. configurable: true
  61572. });
  61573. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  61574. /**
  61575. * Gets if the current filter is set to "close ESM" (using the inverse of the
  61576. * exponential to prevent steep falloff artifacts).
  61577. */
  61578. get: function () {
  61579. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  61580. },
  61581. /**
  61582. * Sets the current filter to "close ESM" (using the inverse of the
  61583. * exponential to prevent steep falloff artifacts).
  61584. */
  61585. set: function (value) {
  61586. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  61587. return;
  61588. }
  61589. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61590. },
  61591. enumerable: true,
  61592. configurable: true
  61593. });
  61594. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  61595. /**
  61596. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  61597. * exponential to prevent steep falloff artifacts).
  61598. */
  61599. get: function () {
  61600. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  61601. },
  61602. /**
  61603. * Sets the current filter to filtered "close ESM" (using the inverse of the
  61604. * exponential to prevent steep falloff artifacts).
  61605. */
  61606. set: function (value) {
  61607. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  61608. return;
  61609. }
  61610. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61611. },
  61612. enumerable: true,
  61613. configurable: true
  61614. });
  61615. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  61616. /**
  61617. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  61618. */
  61619. get: function () {
  61620. return this.filter === ShadowGenerator.FILTER_PCF;
  61621. },
  61622. /**
  61623. * Sets the current filter to "PCF" (percentage closer filtering).
  61624. */
  61625. set: function (value) {
  61626. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  61627. return;
  61628. }
  61629. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  61630. },
  61631. enumerable: true,
  61632. configurable: true
  61633. });
  61634. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  61635. /**
  61636. * Gets the PCF or PCSS Quality.
  61637. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  61638. */
  61639. get: function () {
  61640. return this._filteringQuality;
  61641. },
  61642. /**
  61643. * Sets the PCF or PCSS Quality.
  61644. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  61645. */
  61646. set: function (filteringQuality) {
  61647. this._filteringQuality = filteringQuality;
  61648. },
  61649. enumerable: true,
  61650. configurable: true
  61651. });
  61652. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  61653. /**
  61654. * Gets if the current filter is set to "PCSS" (contact hardening).
  61655. */
  61656. get: function () {
  61657. return this.filter === ShadowGenerator.FILTER_PCSS;
  61658. },
  61659. /**
  61660. * Sets the current filter to "PCSS" (contact hardening).
  61661. */
  61662. set: function (value) {
  61663. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  61664. return;
  61665. }
  61666. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  61667. },
  61668. enumerable: true,
  61669. configurable: true
  61670. });
  61671. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  61672. /**
  61673. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  61674. * Using a ratio helps keeping shape stability independently of the map size.
  61675. *
  61676. * It does not account for the light projection as it was having too much
  61677. * instability during the light setup or during light position changes.
  61678. *
  61679. * Only valid if useContactHardeningShadow is true.
  61680. */
  61681. get: function () {
  61682. return this._contactHardeningLightSizeUVRatio;
  61683. },
  61684. /**
  61685. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  61686. * Using a ratio helps keeping shape stability independently of the map size.
  61687. *
  61688. * It does not account for the light projection as it was having too much
  61689. * instability during the light setup or during light position changes.
  61690. *
  61691. * Only valid if useContactHardeningShadow is true.
  61692. */
  61693. set: function (contactHardeningLightSizeUVRatio) {
  61694. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  61695. },
  61696. enumerable: true,
  61697. configurable: true
  61698. });
  61699. /**
  61700. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  61701. * 0 means strongest and 1 would means no shadow.
  61702. * @returns the darkness.
  61703. */
  61704. ShadowGenerator.prototype.getDarkness = function () {
  61705. return this._darkness;
  61706. };
  61707. /**
  61708. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  61709. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  61710. * @returns the shadow generator allowing fluent coding.
  61711. */
  61712. ShadowGenerator.prototype.setDarkness = function (darkness) {
  61713. if (darkness >= 1.0)
  61714. this._darkness = 1.0;
  61715. else if (darkness <= 0.0)
  61716. this._darkness = 0.0;
  61717. else
  61718. this._darkness = darkness;
  61719. return this;
  61720. };
  61721. /**
  61722. * Sets the ability to have transparent shadow (boolean).
  61723. * @param transparent True if transparent else False
  61724. * @returns the shadow generator allowing fluent coding
  61725. */
  61726. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  61727. this._transparencyShadow = transparent;
  61728. return this;
  61729. };
  61730. /**
  61731. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  61732. * @returns The render target texture if present otherwise, null
  61733. */
  61734. ShadowGenerator.prototype.getShadowMap = function () {
  61735. return this._shadowMap;
  61736. };
  61737. /**
  61738. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  61739. * @returns The render target texture if the shadow map is present otherwise, null
  61740. */
  61741. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  61742. if (this._shadowMap2) {
  61743. return this._shadowMap2;
  61744. }
  61745. return this._shadowMap;
  61746. };
  61747. /**
  61748. * Helper function to add a mesh and its descendants to the list of shadow casters.
  61749. * @param mesh Mesh to add
  61750. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  61751. * @returns the Shadow Generator itself
  61752. */
  61753. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  61754. if (includeDescendants === void 0) { includeDescendants = true; }
  61755. if (!this._shadowMap) {
  61756. return this;
  61757. }
  61758. if (!this._shadowMap.renderList) {
  61759. this._shadowMap.renderList = [];
  61760. }
  61761. this._shadowMap.renderList.push(mesh);
  61762. if (includeDescendants) {
  61763. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  61764. }
  61765. return this;
  61766. var _a;
  61767. };
  61768. /**
  61769. * Helper function to remove a mesh and its descendants from the list of shadow casters
  61770. * @param mesh Mesh to remove
  61771. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  61772. * @returns the Shadow Generator itself
  61773. */
  61774. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  61775. if (includeDescendants === void 0) { includeDescendants = true; }
  61776. if (!this._shadowMap || !this._shadowMap.renderList) {
  61777. return this;
  61778. }
  61779. var index = this._shadowMap.renderList.indexOf(mesh);
  61780. if (index !== -1) {
  61781. this._shadowMap.renderList.splice(index, 1);
  61782. }
  61783. if (includeDescendants) {
  61784. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  61785. var child = _a[_i];
  61786. this.removeShadowCaster(child);
  61787. }
  61788. }
  61789. return this;
  61790. };
  61791. /**
  61792. * Returns the associated light object.
  61793. * @returns the light generating the shadow
  61794. */
  61795. ShadowGenerator.prototype.getLight = function () {
  61796. return this._light;
  61797. };
  61798. ShadowGenerator.prototype._initializeGenerator = function () {
  61799. this._light._markMeshesAsLightDirty();
  61800. this._initializeShadowMap();
  61801. };
  61802. ShadowGenerator.prototype._initializeShadowMap = function () {
  61803. var _this = this;
  61804. // Render target
  61805. var engine = this._scene.getEngine();
  61806. if (engine.webGLVersion > 1) {
  61807. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  61808. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  61809. }
  61810. else {
  61811. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  61812. }
  61813. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61814. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61815. this._shadowMap.anisotropicFilteringLevel = 1;
  61816. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61817. this._shadowMap.renderParticles = false;
  61818. this._shadowMap.ignoreCameraViewport = true;
  61819. // Record Face Index before render.
  61820. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  61821. _this._currentFaceIndex = faceIndex;
  61822. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61823. engine.setColorWrite(false);
  61824. }
  61825. });
  61826. // Custom render function.
  61827. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  61828. // Blur if required afer render.
  61829. this._shadowMap.onAfterUnbindObservable.add(function () {
  61830. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61831. engine.setColorWrite(true);
  61832. }
  61833. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  61834. return;
  61835. }
  61836. var shadowMap = _this.getShadowMapForRendering();
  61837. if (shadowMap) {
  61838. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  61839. }
  61840. });
  61841. // Clear according to the chosen filter.
  61842. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  61843. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  61844. this._shadowMap.onClearObservable.add(function (engine) {
  61845. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61846. engine.clear(clearOne, false, true, false);
  61847. }
  61848. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  61849. engine.clear(clearZero, true, true, false);
  61850. }
  61851. else {
  61852. engine.clear(clearOne, true, true, false);
  61853. }
  61854. });
  61855. };
  61856. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  61857. var _this = this;
  61858. var engine = this._scene.getEngine();
  61859. var targetSize = this._mapSize / this.blurScale;
  61860. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  61861. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  61862. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61863. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61864. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61865. }
  61866. if (this.useKernelBlur) {
  61867. 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);
  61868. this._kernelBlurXPostprocess.width = targetSize;
  61869. this._kernelBlurXPostprocess.height = targetSize;
  61870. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  61871. effect.setTexture("textureSampler", _this._shadowMap);
  61872. });
  61873. 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);
  61874. this._kernelBlurXPostprocess.autoClear = false;
  61875. this._kernelBlurYPostprocess.autoClear = false;
  61876. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  61877. this._kernelBlurXPostprocess.packedFloat = true;
  61878. this._kernelBlurYPostprocess.packedFloat = true;
  61879. }
  61880. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  61881. }
  61882. else {
  61883. 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);
  61884. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  61885. effect.setFloat2("screenSize", targetSize, targetSize);
  61886. effect.setTexture("textureSampler", _this._shadowMap);
  61887. });
  61888. this._boxBlurPostprocess.autoClear = false;
  61889. this._blurPostProcesses = [this._boxBlurPostprocess];
  61890. }
  61891. };
  61892. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  61893. var index;
  61894. var engine = this._scene.getEngine();
  61895. if (depthOnlySubMeshes.length) {
  61896. engine.setColorWrite(false);
  61897. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  61898. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  61899. }
  61900. engine.setColorWrite(true);
  61901. }
  61902. for (index = 0; index < opaqueSubMeshes.length; index++) {
  61903. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  61904. }
  61905. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  61906. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  61907. }
  61908. if (this._transparencyShadow) {
  61909. for (index = 0; index < transparentSubMeshes.length; index++) {
  61910. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  61911. }
  61912. }
  61913. };
  61914. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  61915. var _this = this;
  61916. var mesh = subMesh.getRenderingMesh();
  61917. var scene = this._scene;
  61918. var engine = scene.getEngine();
  61919. var material = subMesh.getMaterial();
  61920. if (!material) {
  61921. return;
  61922. }
  61923. // Culling
  61924. engine.setState(material.backFaceCulling);
  61925. // Managing instances
  61926. var batch = mesh._getInstancesRenderList(subMesh._id);
  61927. if (batch.mustReturn) {
  61928. return;
  61929. }
  61930. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  61931. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  61932. engine.enableEffect(this._effect);
  61933. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  61934. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  61935. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  61936. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  61937. this._effect.setVector3("lightData", this._cachedDirection);
  61938. }
  61939. else {
  61940. this._effect.setVector3("lightData", this._cachedPosition);
  61941. }
  61942. if (scene.activeCamera) {
  61943. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  61944. }
  61945. // Alpha test
  61946. if (material && material.needAlphaTesting()) {
  61947. var alphaTexture = material.getAlphaTestTexture();
  61948. if (alphaTexture) {
  61949. this._effect.setTexture("diffuseSampler", alphaTexture);
  61950. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  61951. }
  61952. }
  61953. // Bones
  61954. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61955. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  61956. }
  61957. // Morph targets
  61958. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  61959. if (this.forceBackFacesOnly) {
  61960. engine.setState(true, 0, false, true);
  61961. }
  61962. // Draw
  61963. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  61964. if (this.forceBackFacesOnly) {
  61965. engine.setState(true, 0, false, false);
  61966. }
  61967. }
  61968. else {
  61969. // Need to reset refresh rate of the shadowMap
  61970. if (this._shadowMap) {
  61971. this._shadowMap.resetRefreshCounter();
  61972. }
  61973. }
  61974. };
  61975. ShadowGenerator.prototype._applyFilterValues = function () {
  61976. if (!this._shadowMap) {
  61977. return;
  61978. }
  61979. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  61980. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  61981. }
  61982. else {
  61983. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61984. }
  61985. };
  61986. /**
  61987. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  61988. * @param onCompiled Callback triggered at the and of the effects compilation
  61989. * @param options Sets of optional options forcing the compilation with different modes
  61990. */
  61991. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  61992. var _this = this;
  61993. var localOptions = __assign({ useInstances: false }, options);
  61994. var shadowMap = this.getShadowMap();
  61995. if (!shadowMap) {
  61996. if (onCompiled) {
  61997. onCompiled(this);
  61998. }
  61999. return;
  62000. }
  62001. var renderList = shadowMap.renderList;
  62002. if (!renderList) {
  62003. if (onCompiled) {
  62004. onCompiled(this);
  62005. }
  62006. return;
  62007. }
  62008. var subMeshes = new Array();
  62009. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  62010. var mesh = renderList_1[_i];
  62011. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  62012. }
  62013. if (subMeshes.length === 0) {
  62014. if (onCompiled) {
  62015. onCompiled(this);
  62016. }
  62017. return;
  62018. }
  62019. var currentIndex = 0;
  62020. var checkReady = function () {
  62021. if (!_this._scene || !_this._scene.getEngine()) {
  62022. return;
  62023. }
  62024. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  62025. currentIndex++;
  62026. if (currentIndex >= subMeshes.length) {
  62027. if (onCompiled) {
  62028. onCompiled(_this);
  62029. }
  62030. return;
  62031. }
  62032. }
  62033. setTimeout(checkReady, 16);
  62034. };
  62035. checkReady();
  62036. };
  62037. /**
  62038. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  62039. * @param options Sets of optional options forcing the compilation with different modes
  62040. * @returns A promise that resolves when the compilation completes
  62041. */
  62042. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  62043. var _this = this;
  62044. return new Promise(function (resolve) {
  62045. _this.forceCompilation(function () {
  62046. resolve();
  62047. }, options);
  62048. });
  62049. };
  62050. /**
  62051. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  62052. * @param subMesh The submesh we want to render in the shadow map
  62053. * @param useInstances Defines wether will draw in the map using instances
  62054. * @returns true if ready otherwise, false
  62055. */
  62056. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  62057. var defines = [];
  62058. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  62059. defines.push("#define FLOAT");
  62060. }
  62061. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  62062. defines.push("#define ESM");
  62063. }
  62064. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  62065. defines.push("#define DEPTHTEXTURE");
  62066. }
  62067. var attribs = [BABYLON.VertexBuffer.PositionKind];
  62068. var mesh = subMesh.getMesh();
  62069. var material = subMesh.getMaterial();
  62070. // Normal bias.
  62071. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  62072. attribs.push(BABYLON.VertexBuffer.NormalKind);
  62073. defines.push("#define NORMAL");
  62074. if (mesh.nonUniformScaling) {
  62075. defines.push("#define NONUNIFORMSCALING");
  62076. }
  62077. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  62078. defines.push("#define DIRECTIONINLIGHTDATA");
  62079. }
  62080. }
  62081. // Alpha test
  62082. if (material && material.needAlphaTesting()) {
  62083. var alphaTexture = material.getAlphaTestTexture();
  62084. if (alphaTexture) {
  62085. defines.push("#define ALPHATEST");
  62086. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  62087. attribs.push(BABYLON.VertexBuffer.UVKind);
  62088. defines.push("#define UV1");
  62089. }
  62090. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  62091. if (alphaTexture.coordinatesIndex === 1) {
  62092. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  62093. defines.push("#define UV2");
  62094. }
  62095. }
  62096. }
  62097. }
  62098. // Bones
  62099. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  62100. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  62101. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  62102. if (mesh.numBoneInfluencers > 4) {
  62103. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  62104. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  62105. }
  62106. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  62107. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  62108. }
  62109. else {
  62110. defines.push("#define NUM_BONE_INFLUENCERS 0");
  62111. }
  62112. // Morph targets
  62113. var manager = mesh.morphTargetManager;
  62114. var morphInfluencers = 0;
  62115. if (manager) {
  62116. if (manager.numInfluencers > 0) {
  62117. defines.push("#define MORPHTARGETS");
  62118. morphInfluencers = manager.numInfluencers;
  62119. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  62120. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  62121. }
  62122. }
  62123. // Instances
  62124. if (useInstances) {
  62125. defines.push("#define INSTANCES");
  62126. attribs.push("world0");
  62127. attribs.push("world1");
  62128. attribs.push("world2");
  62129. attribs.push("world3");
  62130. }
  62131. // Get correct effect
  62132. var join = defines.join("\n");
  62133. if (this._cachedDefines !== join) {
  62134. this._cachedDefines = join;
  62135. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  62136. }
  62137. if (!this._effect.isReady()) {
  62138. return false;
  62139. }
  62140. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  62141. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  62142. this._initializeBlurRTTAndPostProcesses();
  62143. }
  62144. }
  62145. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  62146. return false;
  62147. }
  62148. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  62149. return false;
  62150. }
  62151. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  62152. return false;
  62153. }
  62154. return true;
  62155. };
  62156. /**
  62157. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  62158. * @param defines Defines of the material we want to update
  62159. * @param lightIndex Index of the light in the enabled light list of the material
  62160. */
  62161. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  62162. var scene = this._scene;
  62163. var light = this._light;
  62164. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  62165. return;
  62166. }
  62167. defines["SHADOW" + lightIndex] = true;
  62168. if (this.useContactHardeningShadow) {
  62169. defines["SHADOWPCSS" + lightIndex] = true;
  62170. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  62171. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  62172. }
  62173. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  62174. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  62175. }
  62176. // else default to high.
  62177. }
  62178. if (this.usePercentageCloserFiltering) {
  62179. defines["SHADOWPCF" + lightIndex] = true;
  62180. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  62181. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  62182. }
  62183. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  62184. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  62185. }
  62186. // else default to high.
  62187. }
  62188. else if (this.usePoissonSampling) {
  62189. defines["SHADOWPOISSON" + lightIndex] = true;
  62190. }
  62191. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  62192. defines["SHADOWESM" + lightIndex] = true;
  62193. }
  62194. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  62195. defines["SHADOWCLOSEESM" + lightIndex] = true;
  62196. }
  62197. if (light.needCube()) {
  62198. defines["SHADOWCUBE" + lightIndex] = true;
  62199. }
  62200. };
  62201. /**
  62202. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  62203. * defined in the generator but impacting the effect).
  62204. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  62205. * @param effect The effect we are binfing the information for
  62206. */
  62207. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  62208. var light = this._light;
  62209. var scene = this._scene;
  62210. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  62211. return;
  62212. }
  62213. var camera = scene.activeCamera;
  62214. if (!camera) {
  62215. return;
  62216. }
  62217. var shadowMap = this.getShadowMap();
  62218. if (!shadowMap) {
  62219. return;
  62220. }
  62221. if (!light.needCube()) {
  62222. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  62223. }
  62224. // Only PCF uses depth stencil texture.
  62225. if (this._filter === ShadowGenerator.FILTER_PCF) {
  62226. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  62227. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  62228. }
  62229. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  62230. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  62231. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  62232. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  62233. }
  62234. else {
  62235. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  62236. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  62237. }
  62238. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  62239. };
  62240. /**
  62241. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  62242. * (eq to shadow prjection matrix * light transform matrix)
  62243. * @returns The transform matrix used to create the shadow map
  62244. */
  62245. ShadowGenerator.prototype.getTransformMatrix = function () {
  62246. var scene = this._scene;
  62247. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  62248. return this._transformMatrix;
  62249. }
  62250. this._currentRenderID = scene.getRenderId();
  62251. this._currentFaceIndexCache = this._currentFaceIndex;
  62252. var lightPosition = this._light.position;
  62253. if (this._light.computeTransformedInformation()) {
  62254. lightPosition = this._light.transformedPosition;
  62255. }
  62256. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  62257. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  62258. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  62259. }
  62260. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  62261. this._cachedPosition.copyFrom(lightPosition);
  62262. this._cachedDirection.copyFrom(this._lightDirection);
  62263. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  62264. var shadowMap = this.getShadowMap();
  62265. if (shadowMap) {
  62266. var renderList = shadowMap.renderList;
  62267. if (renderList) {
  62268. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  62269. }
  62270. }
  62271. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  62272. }
  62273. return this._transformMatrix;
  62274. };
  62275. /**
  62276. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  62277. * Cube and 2D textures for instance.
  62278. */
  62279. ShadowGenerator.prototype.recreateShadowMap = function () {
  62280. var shadowMap = this._shadowMap;
  62281. if (!shadowMap) {
  62282. return;
  62283. }
  62284. // Track render list.
  62285. var renderList = shadowMap.renderList;
  62286. // Clean up existing data.
  62287. this._disposeRTTandPostProcesses();
  62288. // Reinitializes.
  62289. this._initializeGenerator();
  62290. // Reaffect the filter to ensure a correct fallback if necessary.
  62291. this.filter = this.filter;
  62292. // Reaffect the filter.
  62293. this._applyFilterValues();
  62294. // Reaffect Render List.
  62295. this._shadowMap.renderList = renderList;
  62296. };
  62297. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  62298. if (this._shadowMap2) {
  62299. this._shadowMap2.dispose();
  62300. this._shadowMap2 = null;
  62301. }
  62302. if (this._boxBlurPostprocess) {
  62303. this._boxBlurPostprocess.dispose();
  62304. this._boxBlurPostprocess = null;
  62305. }
  62306. if (this._kernelBlurXPostprocess) {
  62307. this._kernelBlurXPostprocess.dispose();
  62308. this._kernelBlurXPostprocess = null;
  62309. }
  62310. if (this._kernelBlurYPostprocess) {
  62311. this._kernelBlurYPostprocess.dispose();
  62312. this._kernelBlurYPostprocess = null;
  62313. }
  62314. this._blurPostProcesses = [];
  62315. };
  62316. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  62317. if (this._shadowMap) {
  62318. this._shadowMap.dispose();
  62319. this._shadowMap = null;
  62320. }
  62321. this._disposeBlurPostProcesses();
  62322. };
  62323. /**
  62324. * Disposes the ShadowGenerator.
  62325. * Returns nothing.
  62326. */
  62327. ShadowGenerator.prototype.dispose = function () {
  62328. this._disposeRTTandPostProcesses();
  62329. if (this._light) {
  62330. this._light._shadowGenerator = null;
  62331. this._light._markMeshesAsLightDirty();
  62332. }
  62333. };
  62334. /**
  62335. * Serializes the shadow generator setup to a json object.
  62336. * @returns The serialized JSON object
  62337. */
  62338. ShadowGenerator.prototype.serialize = function () {
  62339. var serializationObject = {};
  62340. var shadowMap = this.getShadowMap();
  62341. if (!shadowMap) {
  62342. return serializationObject;
  62343. }
  62344. serializationObject.lightId = this._light.id;
  62345. serializationObject.mapSize = shadowMap.getRenderSize();
  62346. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  62347. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  62348. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  62349. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  62350. serializationObject.usePoissonSampling = this.usePoissonSampling;
  62351. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  62352. serializationObject.depthScale = this.depthScale;
  62353. serializationObject.darkness = this.getDarkness();
  62354. serializationObject.blurBoxOffset = this.blurBoxOffset;
  62355. serializationObject.blurKernel = this.blurKernel;
  62356. serializationObject.blurScale = this.blurScale;
  62357. serializationObject.useKernelBlur = this.useKernelBlur;
  62358. serializationObject.transparencyShadow = this._transparencyShadow;
  62359. serializationObject.bias = this.bias;
  62360. serializationObject.normalBias = this.normalBias;
  62361. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  62362. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  62363. serializationObject.filteringQuality = this.filteringQuality;
  62364. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  62365. serializationObject.renderList = [];
  62366. if (shadowMap.renderList) {
  62367. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  62368. var mesh = shadowMap.renderList[meshIndex];
  62369. serializationObject.renderList.push(mesh.id);
  62370. }
  62371. }
  62372. return serializationObject;
  62373. };
  62374. /**
  62375. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  62376. * @param parsedShadowGenerator The JSON object to parse
  62377. * @param scene The scene to create the shadow map for
  62378. * @returns The parsed shadow generator
  62379. */
  62380. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  62381. //casting to point light, as light is missing the position attr and typescript complains.
  62382. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  62383. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  62384. var shadowMap = shadowGenerator.getShadowMap();
  62385. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  62386. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  62387. meshes.forEach(function (mesh) {
  62388. if (!shadowMap) {
  62389. return;
  62390. }
  62391. if (!shadowMap.renderList) {
  62392. shadowMap.renderList = [];
  62393. }
  62394. shadowMap.renderList.push(mesh);
  62395. });
  62396. }
  62397. if (parsedShadowGenerator.usePoissonSampling) {
  62398. shadowGenerator.usePoissonSampling = true;
  62399. }
  62400. else if (parsedShadowGenerator.useExponentialShadowMap) {
  62401. shadowGenerator.useExponentialShadowMap = true;
  62402. }
  62403. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  62404. shadowGenerator.useBlurExponentialShadowMap = true;
  62405. }
  62406. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  62407. shadowGenerator.useCloseExponentialShadowMap = true;
  62408. }
  62409. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  62410. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  62411. }
  62412. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  62413. shadowGenerator.usePercentageCloserFiltering = true;
  62414. }
  62415. else if (parsedShadowGenerator.useContactHardeningShadow) {
  62416. shadowGenerator.useContactHardeningShadow = true;
  62417. }
  62418. if (parsedShadowGenerator.filteringQuality) {
  62419. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  62420. }
  62421. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  62422. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  62423. }
  62424. else if (parsedShadowGenerator.useVarianceShadowMap) {
  62425. shadowGenerator.useExponentialShadowMap = true;
  62426. }
  62427. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  62428. shadowGenerator.useBlurExponentialShadowMap = true;
  62429. }
  62430. if (parsedShadowGenerator.depthScale) {
  62431. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  62432. }
  62433. if (parsedShadowGenerator.blurScale) {
  62434. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  62435. }
  62436. if (parsedShadowGenerator.blurBoxOffset) {
  62437. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  62438. }
  62439. if (parsedShadowGenerator.useKernelBlur) {
  62440. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  62441. }
  62442. if (parsedShadowGenerator.blurKernel) {
  62443. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  62444. }
  62445. if (parsedShadowGenerator.bias !== undefined) {
  62446. shadowGenerator.bias = parsedShadowGenerator.bias;
  62447. }
  62448. if (parsedShadowGenerator.normalBias !== undefined) {
  62449. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  62450. }
  62451. if (parsedShadowGenerator.darkness) {
  62452. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  62453. }
  62454. if (parsedShadowGenerator.transparencyShadow) {
  62455. shadowGenerator.setTransparencyShadow(true);
  62456. }
  62457. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  62458. return shadowGenerator;
  62459. };
  62460. /**
  62461. * Shadow generator mode None: no filtering applied.
  62462. */
  62463. ShadowGenerator.FILTER_NONE = 0;
  62464. /**
  62465. * Shadow generator mode ESM: Exponential Shadow Mapping.
  62466. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62467. */
  62468. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  62469. /**
  62470. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  62471. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  62472. */
  62473. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  62474. /**
  62475. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  62476. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62477. */
  62478. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  62479. /**
  62480. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  62481. * edge artifacts on steep falloff.
  62482. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62483. */
  62484. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  62485. /**
  62486. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  62487. * edge artifacts on steep falloff.
  62488. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62489. */
  62490. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  62491. /**
  62492. * Shadow generator mode PCF: Percentage Closer Filtering
  62493. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  62494. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  62495. */
  62496. ShadowGenerator.FILTER_PCF = 6;
  62497. /**
  62498. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  62499. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  62500. * Contact Hardening
  62501. */
  62502. ShadowGenerator.FILTER_PCSS = 7;
  62503. /**
  62504. * Reserved for PCF and PCSS
  62505. * Highest Quality.
  62506. *
  62507. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  62508. *
  62509. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  62510. */
  62511. ShadowGenerator.QUALITY_HIGH = 0;
  62512. /**
  62513. * Reserved for PCF and PCSS
  62514. * Good tradeoff for quality/perf cross devices
  62515. *
  62516. * Execute PCF on a 3*3 kernel.
  62517. *
  62518. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  62519. */
  62520. ShadowGenerator.QUALITY_MEDIUM = 1;
  62521. /**
  62522. * Reserved for PCF and PCSS
  62523. * The lowest quality but the fastest.
  62524. *
  62525. * Execute PCF on a 1*1 kernel.
  62526. *
  62527. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  62528. */
  62529. ShadowGenerator.QUALITY_LOW = 2;
  62530. return ShadowGenerator;
  62531. }());
  62532. BABYLON.ShadowGenerator = ShadowGenerator;
  62533. })(BABYLON || (BABYLON = {}));
  62534. //# sourceMappingURL=babylon.shadowGenerator.js.map
  62535. "use strict";
  62536. var BABYLON;
  62537. (function (BABYLON) {
  62538. var DefaultLoadingScreen = /** @class */ (function () {
  62539. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  62540. if (_loadingText === void 0) { _loadingText = ""; }
  62541. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  62542. var _this = this;
  62543. this._renderingCanvas = _renderingCanvas;
  62544. this._loadingText = _loadingText;
  62545. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  62546. // Resize
  62547. this._resizeLoadingUI = function () {
  62548. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  62549. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  62550. if (!_this._loadingDiv) {
  62551. return;
  62552. }
  62553. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  62554. _this._loadingDiv.style.left = canvasRect.left + "px";
  62555. _this._loadingDiv.style.top = canvasRect.top + "px";
  62556. _this._loadingDiv.style.width = canvasRect.width + "px";
  62557. _this._loadingDiv.style.height = canvasRect.height + "px";
  62558. };
  62559. }
  62560. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  62561. if (this._loadingDiv) {
  62562. // Do not add a loading screen if there is already one
  62563. return;
  62564. }
  62565. this._loadingDiv = document.createElement("div");
  62566. this._loadingDiv.id = "babylonjsLoadingDiv";
  62567. this._loadingDiv.style.opacity = "0";
  62568. this._loadingDiv.style.transition = "opacity 1.5s ease";
  62569. this._loadingDiv.style.pointerEvents = "none";
  62570. // Loading text
  62571. this._loadingTextDiv = document.createElement("div");
  62572. this._loadingTextDiv.style.position = "absolute";
  62573. this._loadingTextDiv.style.left = "0";
  62574. this._loadingTextDiv.style.top = "50%";
  62575. this._loadingTextDiv.style.marginTop = "80px";
  62576. this._loadingTextDiv.style.width = "100%";
  62577. this._loadingTextDiv.style.height = "20px";
  62578. this._loadingTextDiv.style.fontFamily = "Arial";
  62579. this._loadingTextDiv.style.fontSize = "14px";
  62580. this._loadingTextDiv.style.color = "white";
  62581. this._loadingTextDiv.style.textAlign = "center";
  62582. this._loadingTextDiv.innerHTML = "Loading";
  62583. this._loadingDiv.appendChild(this._loadingTextDiv);
  62584. //set the predefined text
  62585. this._loadingTextDiv.innerHTML = this._loadingText;
  62586. // Generating keyframes
  62587. var style = document.createElement('style');
  62588. style.type = 'text/css';
  62589. 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 }";
  62590. style.innerHTML = keyFrames;
  62591. document.getElementsByTagName('head')[0].appendChild(style);
  62592. // Loading img
  62593. var imgBack = new Image();
  62594. imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMTZEaa/1AAAYq0lEQVR4Xu2dCZRcVZnHScAJUZSwjSOIbAJmEAZwQCCMoAInYRGIg8AwegQx7AFzUBBmzAFlE4EAwxz2GRk2w7AnAURZBiEOZgyEQDAQAjmEJqTpNd3V1V3Vmd+/6utKV7/1vnpVXd2p/zn3vOV+27vfu/fd/W3QQAPrBZqbm7fJZrN79vf3T+/r67uf4wO9vb37WXQDIwWtra0Tenp6voQTv5XP56/BkfcR3iLk1g6B7hEeI+zP5V+ZiAbqBZ2dnZ8lV+6Gg87CobfhpOc4byf0FjwYE9DneBkWcXrM2tmzNzTxDdQKJPyETCazI46YgiMuI9zJuXJltuChFIHsP/PSfIfTjU19A2mira1tcxy3ey6XO5vEnkV4kes11XBmENDVj97XOT2O03FmWgMuoNLzGRJva8IUnPkzjjcT/kLoKCZzfQB7XiX8M2G8md7AUJgzJ+Z6e88gZ1xGuj3HsY17PcVkrG9gp7CUF/F8PUvxqdZDrFq1ahNVfKjwTCYxZuDE2wjKlc2WViMePM+HPNsFPOdf22OPblD5OZQHvphnV65cjTMzxaQY3eA5V9OO/hmnm1lSjE7woFsQbiXki4++foHnXkW4mLC1JUl947333tsMY3emqfB9jtPJlXN5U0+bOXPmWCPxgOccSy4+AfqPio+9/oFnbyatbqVE28GSZfjQ1NT0KQzaHMcdyPfyaNoE12HcvdxT29K3Fkv8A2vWrPmcifAFZNtD91yRY+SBZ+9UsMtEgD+jTpeenp6JXI6xpKkuUDqRcA6Kr0Wpens+InQTnIpV6Fdi+BQT64ulS5eOIzefD62na7CeoGcnLCM8ykt5OWlzcPv772/BS/w3nP+K+xU11+DvQe5dcrQlTfWAwbNMb8XA8AyGX80xtLlA6TAJuteMbVhhia1v5VMcr+LWMeoZ4xiYw7q6urbhHbgG+paCkIRQehHu4pO3O5fVydEomF5Ulx548JfVD2wqfKE2I3R3ob/f2GoC1DWhdz7HG3i5j2pvb9+Z24m6HvVZQtYsZFWcowlzePEP4jJdR/OQhxTVpAs9NMXxmZxuZKo8IG4s+v8R2tUFphSBTBWzH+OAFwn/gS3TuN55xYoVqfc6dXd3fwHZ1xFaTX0iyGbwjJqXXAammxP00EXx6UMGEx7ram7+vKnzBZ/87Xiwp40tEdDTgYwlHG/CmadSjO7L+XiialOZAej7POFG2VK0Khngl6Pn8/LL0YEtlFh4n8oDAqvaAYH8tzH2iNDm1IIFn8Ax50G7xtgCAU07CfAG4RHOz+vLZL7e0dGxlYlKHaj8BHo25xgrsfV5wrYH4KmouxV+ZZDnCUdwmXxMGgFvFUVWD+jQuOot6rI0tb4gcfaG9v+MrcAn+wj38gL8C7cObmlp2ZRjOkWYD6ypuAf6zjFHLSJ0c/6YQ813DM/yZXgehreiVgP8cvSfsOeExYsXuzs6n8v9j8mqBRZQmdjXVPuira1NHSpn8UDf4Xu0vd2uCtDzacJOlDDf5ng94X8JTWarB8R1EK7ju7udiYgEz/v3pLFKm4oHUHhh3iZdfshpaEYpA4pvKLLXBujLYKRq71XLhUHg27z12rW9B6L/QhLrWWxRH7nzeDK8awi/5HRTEx0K6MZQ694LHk0DqrgfADkreIYz1q5c+UlTEQzesIuMryrggYQWjNL3RGO7p2tuFMeqjaOidgzyCz1yJMTJ6L6d66WEVCcHIO/dQkI75Chs2g97Hoc3jRz9Lge1ED5l4r0gckqRPB0gTw34t1B+h3IqxZkmrn2SULUa7ezZszdE5xfR9130Xsm5ilrnHrmkQOcKvrkncxqrIiY6wlewbw7BOUfDo/b84zzvj9C7J7eCS0NrUiRKCPjUE7ScMBdlF/B2HqBi0ERXBcuXL99YnQz9fX2ah3Up4UnsWGEmDRuUhoTn+Z5PfvbZZ2N/fuCZRJgnfhNVBu73EZoIKt7l0L2UBsYeDZg016nb5EUCWuXQewinUtTuyq2aTStF14a8SD+VDQVj6hDYxjuXf4Hjl83sSMCmTp8j4FtoMuRQ5dAZcii3kk/0s2bBhxIcBxjxUlib1hWInEDO/6qKV+y4geO5HAMntEE/pq+nZyo0ywsG1SmwL4Orf+0yqGCfmvR73LAn9lAeBjQTEhkA+1h49a08iRflcq4H5iuXFU9cz4lqihC/LXS/NZa6Bc+pz5gql5ub6VXD2tZWTSPeyS7XgeLhXrMnEhj6MSHSwaIhFGZH8oA/JzzFeexvJbRN2HW03moT6cEChx6w4QY2rurn85JWrxsiCy0FwjcIqos8w7GZNPulkawDEbFHlaBtjzODEDrVztuKXMmADPWA3RaljyJeNdKq98ilAez8iJdyGqfO31V4NoV/EvyaCqR54V2EshE5Lqcb+TrkstkTLD4WKB4PNNZQ8P05HAelMXNSPWChC8JsYvwthJo0jSoF6fIqjjqe08Aat+LIkd+AVjn09zxbZFqK3tjXAUbXUaWDjTUSyN4J45YZX2Igo4cEOVfFson2ALIxSjR0jog5YNgpfNHM90BxIjDyWIB8Z2NfB01HISJ20wPaw4w1FlavXq1v8aPGXhFw9JNRFTDItifU/RwwpfmKxYsDK180kU4x0lhAXvOSJUs+bezlIDL2N4xi4GpjK4MGCuzUA+SPxzn3m4iKgKyV2DCV08DeMWg0B+zHHOt2DpjS3Mz1BfFOM25C5ZH4LxldJBB0g7GVARkaXgv8VsKqZtIMPpN9RUnJgRzU5Wfp22vifcG3+2vQvmdsdQXsX2pm+oKX+GYjjQXkPWqsXshpRhcJ0RpbGShSHiSuheP37ZYHsGusVHOrU1lMxkO9od4eE+8LlSzQqfetpnPAooBN/2Um+gISp89MkF8K4G3RrMJYoOhbYGxlQEGhSOGogfoLwipExGtUZVVBYIVAluaAaUpuWA+YujlPF22Ra/iBLYEOsV6tV4w0FiitfmLsXiBMU0NiAVrfsp77Zd8MHPgbDoHtva6uLs1jiv1piAKy5tCG+4KJ9wVO/p6RDzvy+b5rzSwP9Okh/WKPERiCWzfk4K8bUSTiOljAyCdx5DZG4gE8W5Dov+NYUfsV/j50fUC4dmXIQDh0qQ6PVgJsOcLM8oA410Ggvo6Ojr81di+g2TKuQOiyJOKWxlpCJpM5zUjKAL3awTsamQfEbYhjtDGKa5tPsyn/wAuiURftlBO56h6aunEwCMxxvV1d+2Fr7Jce2vAu5LUtLeoGi/19gtbToCaR97BoD6BvUs+WkXqgbw6OuhC6wH5l4rRGaCFOvYnjYbyxnpcsCvDVhYOxo6+zszNwSNHVTtJEmSiwzlMAQmNPwIPW42Dds2hfEK/5WJo0Fth+5VNxFHSlkoTzFRh/N3wnq0OGWxXtdoO8enFwaI4jsyidYgNZTxhrMEjEJ4w+En65ESWRXZ7Q4K/COqDAPlhka87WedB8KawmngTIHREOJs5pMiRp+p/GGgxL1FiA9hxjK6G1tVVdhJGAV15+cPXq1f7dahVC20Wg4miCp0uTe3Xh4Hwu93rY1B7SR/t7xQbP5R1FGgpy8IlKe+MJhZ9Aa7u5jPm+pGLX2BMDOZ+hDXgQiXIJ5xoXHZg96anEEFcvOTi0SMUXS4w0FijSTzTWYEA3hkTSEtDI2qw6RoytDLA6jctCvzKqJ8oPFOO7kAhnYe9cZGiWiZ/N9ezguWaSL4h3TUfvKJIfoN0I4sjigYSdZyxlcDVMgEczEY41ER6oZFBOh2Yqegf2zYoziFC3DuZZrjSTPLDtMlxaNPmPP/54W2OPxksrVozP5fLPGr8vEOpbxJCr3jQSJyDvGRNRhv7iHh8vE5LMpKznHBz4zSTOaXwe+mXGGh9tbWvVQf+iyfCAON/ZlTj4v43ECfB94Le4CuMrWVpTtw7O9fZOM5M8oD7xVSOLBdLuNWN1g7bgJUF8+4qpBjf7Te9M6hD4tBDc0289Wh2MHbuaSR7gsHOMLBaQ9W/G6o5MJrNDPu9dcYdQ33Yc95I6OFV5hnp2cGCliDingX5KU+9MShd0dmqta/k8J4zwnV2JsuuNxAnI83VwNpO52kiSoC4djA255cuXBzYPycGzjTQWkPdNY00OfRcQVLafRnd39ySLLsG1i20AyPZ3cDb7AyNJgnp1cOhUHUhcFiL045v9jTUa8Gjlm29fsQQhb3DzJLUEhC+oiK7EISPOwapoEh+7JQJti5YfGXs0YNC62ouC1h9lsrlToClsjc/RM7uSe0kd3EmlzTO/Kqk8Q106mM/Yw2aOB9jnOg6sWTHxJ9FraSJMy6nGz7RbZUDYmN7e3BnQ5Gisez7u3J9c0JwA6Pb0aCFvNObgwKk6NoU59uJwaJ8y1viAT4vCtEFXYO8SFQGtCZpllyXQtNqL+4lmZ/BN/5qJKQFZozEHe9JtAGSaw4wsFnie4JmUQcjleh8yZq0Fnmq3y0D02IzPMgnonYqYIfA4pC+TcXrgIahLB+PEb5s5HrjaR0b7kbHGB0pK7TDO1/T39x1lUZGAPlUH0xTbz+KSoC4dDDx2DQCHzTCaWOB5zjbW+KCSpW0IS0BIJmy6zWCk7WDuxZ4r5oO6dHB7e/sBZo4H2OfUsYOv9jHW+ECJdkAtA/c6MpmMd+XaEKj7km9M4F5TEfBzSKovDLKG1cHobw+b6EDa3WOksYBPAhevBUJMxl8GJTRhFyMLBKSJFn5ls9nvmogS0DfaHOzb3h8AcUuNNBLQNiWa0gRv4MwMMyBwCqxAfCIH82JdYSJKQN+ocjA5NHD2I/e1aj/23iPyhbG6A+bAgXsZoUEII/UAkkQORu71JqIE7o22HBw4VaelpWU74mPPDc/39d1trO5Qb4vJ8QXxbwat06WofcTInMCzeToAtN4VXUn/l1AXDkan9tDSfmL6C81BZooHxDkN9CMveLFZFFAWWZtDwVta3G0sJcAbe3bmYEiniShBXabcL+wflQDD5mD0yKlvk0b/Tk33AG5F7idG+/ibRe54oEl1nLG6A+ZYe1jyAIuG/u2LB3MazxwAfL5vJFGJinxQUwcju6c/n3+FNPm5JhJyy2k/sQTp5nm+2HBJCGi1X1WpwzuBoQXAN+IcjDz8mdePKi/WhH1uxd7GcCjIVBcWpUYDfZ0VbclEJSr2akMBhVrdX6j+Jx3DpSh7vKB8CIiqKwcrcXGqdr05k3RKbU9ryTQVkUB3aHMrEshw7kGCXiv8xxG0h6Uzent6Fpn6MhA17A6GT/3yTxNO1coJbgWur3JFf1fXNuTes5AZe18xXobFHJKv04JZc3O7CtIcgGL9KW03u3QCfL4D4b292dhrpoYgsYOhEz4kaOuHqXKqiagYiN9QnUlyKgX84JUYsQFP9GKzMFRSe8XJb9upE9Dn62CK/KQT75wdTLz+NXgPNdrDuYzeUd0ByN4Wp07n+EdCRZuTY1/ymZQDwIjQye9pA32xdw6IiUgHc639mN8kzCLRjkxzQRzitUpkZ8LZBP1CILUd55EVvdgsCrzJl5i8mgCja+Zgjst4Pq3DUnMmtSWqyNIuQruRU3+CbO08n+pvBAZAjf1IU5kcGJc0YRMBfVV3MPd2RN4+YbvYukI/3sSpe+LUmbw0ryG/6ts1oSLeYrMw6C0xeaFAGc+Wq3hbfeRk582b55lrzf3UHJwWkD0Wp+6BQ3+BfXEXw6UCdHX4TVB0BoJi9Y1Cp59XbUWN8HW7lRjLli3zbINE+1hNiCRI1cGakIhT99ani/A6z1z1nDoUqNQfbO40kyqDfrCBwMg3E5rsCy+8sFlHR8dEnFzRTq/I8hQ9NFFOtGhXVOxgFeUqfknUK7Ctpjl1ANKJ/vmUkvrdwRZmWjpA4J9MTyja2toKY8TQa/ufxP/Whdd5c5cQJHIwfBsTvkKiaqd6/fRyOHKqavdL0H+V2sxmWvrQCAeKItfmQlNyDG/8SVwnetMHyxmA7lm0K2I7GFrlVBW/V6FPP9GqeU4V0Kt2+O2yhctUN6AJBEWD9ngMnessJxh5AfCoQe+8q+xQOYLuWbQrQh2MXP1XYh8S9DKC2sI1z6kCatW3/RCZ6Vj9fNPMqx2wQVNJQlcNEl/mGG5pv48bi7HxMVSOoHsW7QqPg5GlvnJtk6/B9+HMqYUfaXE6rampqWy4dVhgi8FfLprnBXEex+i/wCSkNiSNDSpUxxt7Ccj2nQQYAwUHc9yE3HEotuifDklnfFYMdGNC/lWCxotDf4PvB/jHZTs71c+f2n+ryqCPPcb5/pKdGrTvbH2MUjH4ByOLBDpON9YSFi5cuI1FOwFbbyTox5T6y+iwFL8CqvWvwVtolWgSv/N4sXbl5ZP3r8hRLT50d56KgYJDCYXVhYOhtqqReKDdZuGJtSQSOk8f67x581SspvH3lpoBe9Vefbg/lzveaXmnAf6tEDMNGRp3LnV3ch29o10lQIf+bOKZc+XnmMGARF2EK4vUwQiSw33n7ZlqDWwcaK9Ob29vd26vwj+OT8m3kKFxdd9tlILSJ1Wo8Y8RZT/YiKOY4le5P3SGZJAc7telg7FroL16Jc/n/a1cBBCxsSblwT8LOfofcCh4AQ4x1uoCXZtgVKnYDXLMUECnPSQD29VBcrhfVw7GHrVXb6WylGg0SvUZcrr+YPYuwWVfaE9ltmpA2Q6EQq2UY+yigzf2oqCH4v4MIysD94fdwdig9uqDnB4T5/d+gwHPGNVFcOopyJiPLOfmGTwa0Ek8qS8RKDKORLFWH95utwbDd94SRqqN/Cv4PDXbTFfXfUZWBvRUPJCRBJiIqfnnccy0Dz74wHkWoypY2D4ZGU8gK+kKjQKQ8RcTW1uQI2fmc7nH7LIMFEW+sw6xdyN4CgvNByNIDjp+ZyRVhzlV7dVLaZc7t1cRoW0w9of/No6ptbuRdZupqC3QPZY33HchMkbJiRPssgyaHkN82XaJXPtOJuN+JRuixQI6Cu1VXiZtJehcFGpeNPyXI6cqPWTIvsxU1R7o912akevre4OHfTHot3fEfRbD3y8+Qu0djO5Ce5UXNGl7dTt4z0RGqnOuhgLZgmcPk2FHrrd3jgwkAVQ58e1ioxjcHeMLPWQcq+5gZKm9+hJHjXo5z4xQBQsxxyDjEfir+nNq5GfQo/nYh6f9e4NUgGEFx3DEzvw1nPrOhSJ+kh6GUBUHw6//Kmls96dJ2qv6FxNF9z8g405kVLVXDfkaiFAd4JIkttYUGFpyDOf91Ch/YVEe8DA/gORpuywDfLNMjBOQt4qEupbTPTX4YeJig+/qrnoxkfMeIdH2UHGBfP0H6kFepElc1rY5lBQYXZbzuO7BWYH7b3V3d/+TX1FEG/JSExEJdOi7qsnrx3DuNM8Zdg2NqnN/BjK0EXlVhxORr56wP6Lv/DT+X1FzYLynaOWe2s1TjCQW4An9t6Jk4hBVdH6YpB9YNXoS+SRk/JaQZHd5J2CnesLuyGaze3KZ2hTemoNcpO+uB3pAQuzvC7SeJSfc0258Wo97aX9PT+TmMEMB73jsO0wJzXnVx4llL7pe5kWaFtSqGHHgu6rpPr5jsdx+hyI59G+hA4C25GDO1V69mbf/77h0+lZpzZX44B+Ye1X1cWKz92pKrYlcjtzc6gfN+ufhApd/ErcwTvuTRNI0m4c4Tg77u6gfbCHdTuQcrRFaRKiFU7Xl1O/RqX9RObevRxR43gmEBYUn9wEJIMeF/jk0yVKTta2tE0jg43kx1OatWifEYKDrHYKGDnfkMrU1xHUPaoh7k8i+030EvoV3c6i4aTCoc/9+9NVkFgh6BmZFaig08he3oxYkwBEkQGCzg7gfG6kzaDvuSyLfgIyqt1cF6SAspoS4iJf3c9xaf3JrGEgUzZcOGgvO4agzjTQUkI9V5z4851MuLhBvUUp1gR7tjXEHL+shXFZnduNIBomi6T73FVLLByQePu4N3CxMbVxyzfeQUTYZrdpA3yvoPVf/1jdTGggC6aXx0ieLSecFcWoj72vkhU4IcswU7gVORksb6FHnufbouJ4Xbv+gf1g0EADav9uSeO9YenpA3IfURFVZ0gqEms1rRg0qCzM4TuYy1T061jt0dXXpX0xJ96FMDXIqQXtJ3tSfze6OaY0KU1ogfTUgUJMK0lBIL06dS/F/LJeRe0k2kAAk7BgSWN2GVW/aCOjRuPCbBHVGBG6J3ECKIN3VlfjroguqA+RrMsFvCNqisf5mRox2qPlB4s8vuiMdIE/fVjVvLlRnhKlqYLig7QIpOiva40PAqR2E22neJFrN10AVgWMOIDgPuMOjmRFa+HVaR0fHliaugXoEOe80nBWrZg2dZkZoYffuaW5u1kCVkadmbT70AGdqJodWOhxHqP2eFg1UDvsLatnSFq41M+KKnp6eXbhsdB2OdGiCeX8+/2ecqgnmk/VXNYtqYLSAnNposzpjgw3+H/belpVa8J7TAAAAAElFTkSuQmCC";
  62595. imgBack.style.position = "absolute";
  62596. imgBack.style.left = "50%";
  62597. imgBack.style.top = "50%";
  62598. imgBack.style.marginLeft = "-60px";
  62599. imgBack.style.marginTop = "-60px";
  62600. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  62601. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  62602. imgBack.style.transformOrigin = "50% 50%";
  62603. imgBack.style.webkitTransformOrigin = "50% 50%";
  62604. this._loadingDiv.appendChild(imgBack);
  62605. this._resizeLoadingUI();
  62606. window.addEventListener("resize", this._resizeLoadingUI);
  62607. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  62608. document.body.appendChild(this._loadingDiv);
  62609. this._loadingDiv.style.opacity = "1";
  62610. };
  62611. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  62612. var _this = this;
  62613. if (!this._loadingDiv) {
  62614. return;
  62615. }
  62616. var onTransitionEnd = function () {
  62617. if (!_this._loadingDiv) {
  62618. return;
  62619. }
  62620. document.body.removeChild(_this._loadingDiv);
  62621. window.removeEventListener("resize", _this._resizeLoadingUI);
  62622. _this._loadingDiv = null;
  62623. };
  62624. this._loadingDiv.style.opacity = "0";
  62625. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  62626. };
  62627. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  62628. set: function (text) {
  62629. this._loadingText = text;
  62630. if (this._loadingTextDiv) {
  62631. this._loadingTextDiv.innerHTML = this._loadingText;
  62632. }
  62633. },
  62634. enumerable: true,
  62635. configurable: true
  62636. });
  62637. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  62638. get: function () {
  62639. return this._loadingDivBackgroundColor;
  62640. },
  62641. set: function (color) {
  62642. this._loadingDivBackgroundColor = color;
  62643. if (!this._loadingDiv) {
  62644. return;
  62645. }
  62646. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  62647. },
  62648. enumerable: true,
  62649. configurable: true
  62650. });
  62651. return DefaultLoadingScreen;
  62652. }());
  62653. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  62654. })(BABYLON || (BABYLON = {}));
  62655. //# sourceMappingURL=babylon.loadingScreen.js.map
  62656. "use strict";
  62657. var BABYLON;
  62658. (function (BABYLON) {
  62659. var SceneLoaderProgressEvent = /** @class */ (function () {
  62660. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  62661. this.lengthComputable = lengthComputable;
  62662. this.loaded = loaded;
  62663. this.total = total;
  62664. }
  62665. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  62666. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  62667. };
  62668. return SceneLoaderProgressEvent;
  62669. }());
  62670. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  62671. var SceneLoader = /** @class */ (function () {
  62672. function SceneLoader() {
  62673. }
  62674. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  62675. get: function () {
  62676. return 0;
  62677. },
  62678. enumerable: true,
  62679. configurable: true
  62680. });
  62681. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  62682. get: function () {
  62683. return 1;
  62684. },
  62685. enumerable: true,
  62686. configurable: true
  62687. });
  62688. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  62689. get: function () {
  62690. return 2;
  62691. },
  62692. enumerable: true,
  62693. configurable: true
  62694. });
  62695. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  62696. get: function () {
  62697. return 3;
  62698. },
  62699. enumerable: true,
  62700. configurable: true
  62701. });
  62702. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  62703. get: function () {
  62704. return SceneLoader._ForceFullSceneLoadingForIncremental;
  62705. },
  62706. set: function (value) {
  62707. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  62708. },
  62709. enumerable: true,
  62710. configurable: true
  62711. });
  62712. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  62713. get: function () {
  62714. return SceneLoader._ShowLoadingScreen;
  62715. },
  62716. set: function (value) {
  62717. SceneLoader._ShowLoadingScreen = value;
  62718. },
  62719. enumerable: true,
  62720. configurable: true
  62721. });
  62722. Object.defineProperty(SceneLoader, "loggingLevel", {
  62723. get: function () {
  62724. return SceneLoader._loggingLevel;
  62725. },
  62726. set: function (value) {
  62727. SceneLoader._loggingLevel = value;
  62728. },
  62729. enumerable: true,
  62730. configurable: true
  62731. });
  62732. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  62733. get: function () {
  62734. return SceneLoader._CleanBoneMatrixWeights;
  62735. },
  62736. set: function (value) {
  62737. SceneLoader._CleanBoneMatrixWeights = value;
  62738. },
  62739. enumerable: true,
  62740. configurable: true
  62741. });
  62742. SceneLoader._getDefaultPlugin = function () {
  62743. return SceneLoader._registeredPlugins[".babylon"];
  62744. };
  62745. SceneLoader._getPluginForExtension = function (extension) {
  62746. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  62747. if (registeredPlugin) {
  62748. return registeredPlugin;
  62749. }
  62750. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  62751. return SceneLoader._getDefaultPlugin();
  62752. };
  62753. SceneLoader._getPluginForDirectLoad = function (data) {
  62754. for (var extension in SceneLoader._registeredPlugins) {
  62755. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  62756. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  62757. return SceneLoader._registeredPlugins[extension];
  62758. }
  62759. }
  62760. return SceneLoader._getDefaultPlugin();
  62761. };
  62762. SceneLoader._getPluginForFilename = function (sceneFilename) {
  62763. if (sceneFilename.name) {
  62764. sceneFilename = sceneFilename.name;
  62765. }
  62766. var queryStringPosition = sceneFilename.indexOf("?");
  62767. if (queryStringPosition !== -1) {
  62768. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  62769. }
  62770. var dotPosition = sceneFilename.lastIndexOf(".");
  62771. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  62772. return SceneLoader._getPluginForExtension(extension);
  62773. };
  62774. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  62775. SceneLoader._getDirectLoad = function (sceneFilename) {
  62776. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  62777. return sceneFilename.substr(5);
  62778. }
  62779. return null;
  62780. };
  62781. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  62782. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  62783. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  62784. var plugin;
  62785. if (registeredPlugin.plugin.createPlugin) {
  62786. plugin = registeredPlugin.plugin.createPlugin();
  62787. }
  62788. else {
  62789. plugin = registeredPlugin.plugin;
  62790. }
  62791. var useArrayBuffer = registeredPlugin.isBinary;
  62792. var database;
  62793. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  62794. var dataCallback = function (data, responseURL) {
  62795. if (scene.isDisposed) {
  62796. onError("Scene has been disposed");
  62797. return;
  62798. }
  62799. scene.database = database;
  62800. onSuccess(plugin, data, responseURL);
  62801. };
  62802. var request = null;
  62803. var pluginDisposed = false;
  62804. var onDisposeObservable = plugin.onDisposeObservable;
  62805. if (onDisposeObservable) {
  62806. onDisposeObservable.add(function () {
  62807. pluginDisposed = true;
  62808. if (request) {
  62809. request.abort();
  62810. request = null;
  62811. }
  62812. onDispose();
  62813. });
  62814. }
  62815. var manifestChecked = function () {
  62816. if (pluginDisposed) {
  62817. return;
  62818. }
  62819. var url = rootUrl + sceneFilename;
  62820. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  62821. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  62822. } : undefined, database, useArrayBuffer, function (request, exception) {
  62823. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  62824. });
  62825. };
  62826. if (directLoad) {
  62827. dataCallback(directLoad);
  62828. return plugin;
  62829. }
  62830. if (rootUrl.indexOf("file:") === -1) {
  62831. var canUseOfflineSupport = scene.getEngine().enableOfflineSupport;
  62832. if (canUseOfflineSupport) {
  62833. // Also check for exceptions
  62834. var exceptionFound = false;
  62835. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  62836. var regex = _a[_i];
  62837. if (regex.test(rootUrl + sceneFilename)) {
  62838. exceptionFound = true;
  62839. break;
  62840. }
  62841. }
  62842. canUseOfflineSupport = !exceptionFound;
  62843. }
  62844. if (canUseOfflineSupport) {
  62845. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  62846. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  62847. }
  62848. else {
  62849. manifestChecked();
  62850. }
  62851. }
  62852. else {
  62853. var fileOrString = sceneFilename;
  62854. if (fileOrString.name) {
  62855. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  62856. }
  62857. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  62858. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  62859. }
  62860. else {
  62861. onError("Unable to find file named " + sceneFilename);
  62862. }
  62863. }
  62864. return plugin;
  62865. };
  62866. // Public functions
  62867. SceneLoader.GetPluginForExtension = function (extension) {
  62868. return SceneLoader._getPluginForExtension(extension).plugin;
  62869. };
  62870. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  62871. return !!SceneLoader._registeredPlugins[extension];
  62872. };
  62873. SceneLoader.RegisterPlugin = function (plugin) {
  62874. if (typeof plugin.extensions === "string") {
  62875. var extension = plugin.extensions;
  62876. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  62877. plugin: plugin,
  62878. isBinary: false
  62879. };
  62880. }
  62881. else {
  62882. var extensions = plugin.extensions;
  62883. Object.keys(extensions).forEach(function (extension) {
  62884. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  62885. plugin: plugin,
  62886. isBinary: extensions[extension].isBinary
  62887. };
  62888. });
  62889. }
  62890. };
  62891. /**
  62892. * Import meshes into a scene
  62893. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  62894. * @param rootUrl a string that defines the root url for scene and resources
  62895. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62896. * @param scene the instance of BABYLON.Scene to append to
  62897. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  62898. * @param onProgress a callback with a progress event for each file being loaded
  62899. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62900. * @param pluginExtension the extension used to determine the plugin
  62901. * @returns The loaded plugin
  62902. */
  62903. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  62904. if (onSuccess === void 0) { onSuccess = null; }
  62905. if (onProgress === void 0) { onProgress = null; }
  62906. if (onError === void 0) { onError = null; }
  62907. if (pluginExtension === void 0) { pluginExtension = null; }
  62908. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  62909. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  62910. return null;
  62911. }
  62912. var loadingToken = {};
  62913. scene._addPendingData(loadingToken);
  62914. var disposeHandler = function () {
  62915. scene._removePendingData(loadingToken);
  62916. };
  62917. var errorHandler = function (message, exception) {
  62918. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  62919. if (onError) {
  62920. onError(scene, errorMessage, exception);
  62921. }
  62922. else {
  62923. BABYLON.Tools.Error(errorMessage);
  62924. // should the exception be thrown?
  62925. }
  62926. disposeHandler();
  62927. };
  62928. var progressHandler = onProgress ? function (event) {
  62929. try {
  62930. onProgress(event);
  62931. }
  62932. catch (e) {
  62933. errorHandler("Error in onProgress callback", e);
  62934. }
  62935. } : undefined;
  62936. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  62937. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  62938. if (onSuccess) {
  62939. try {
  62940. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  62941. }
  62942. catch (e) {
  62943. errorHandler("Error in onSuccess callback", e);
  62944. }
  62945. }
  62946. scene._removePendingData(loadingToken);
  62947. };
  62948. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  62949. if (plugin.rewriteRootURL) {
  62950. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  62951. }
  62952. if (sceneFilename === "") {
  62953. if (sceneFilename === "") {
  62954. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  62955. }
  62956. }
  62957. if (plugin.importMesh) {
  62958. var syncedPlugin = plugin;
  62959. var meshes = new Array();
  62960. var particleSystems = new Array();
  62961. var skeletons = new Array();
  62962. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  62963. return;
  62964. }
  62965. scene.loadingPluginName = plugin.name;
  62966. successHandler(meshes, particleSystems, skeletons, []);
  62967. }
  62968. else {
  62969. var asyncedPlugin = plugin;
  62970. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  62971. scene.loadingPluginName = plugin.name;
  62972. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  62973. }).catch(function (error) {
  62974. errorHandler(error.message, error);
  62975. });
  62976. }
  62977. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  62978. };
  62979. /**
  62980. * Import meshes into a scene
  62981. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  62982. * @param rootUrl a string that defines the root url for scene and resources
  62983. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62984. * @param scene the instance of BABYLON.Scene to append to
  62985. * @param onProgress a callback with a progress event for each file being loaded
  62986. * @param pluginExtension the extension used to determine the plugin
  62987. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  62988. */
  62989. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  62990. if (onProgress === void 0) { onProgress = null; }
  62991. if (pluginExtension === void 0) { pluginExtension = null; }
  62992. return new Promise(function (resolve, reject) {
  62993. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  62994. resolve({
  62995. meshes: meshes,
  62996. particleSystems: particleSystems,
  62997. skeletons: skeletons,
  62998. animationGroups: animationGroups
  62999. });
  63000. }, onProgress, function (scene, message, exception) {
  63001. reject(exception || new Error(message));
  63002. });
  63003. });
  63004. };
  63005. /**
  63006. * Load a scene
  63007. * @param rootUrl a string that defines the root url for scene and resources
  63008. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  63009. * @param engine is the instance of BABYLON.Engine to use to create the scene
  63010. * @param onSuccess a callback with the scene when import succeeds
  63011. * @param onProgress a callback with a progress event for each file being loaded
  63012. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  63013. * @param pluginExtension the extension used to determine the plugin
  63014. * @returns The loaded plugin
  63015. */
  63016. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  63017. if (onSuccess === void 0) { onSuccess = null; }
  63018. if (onProgress === void 0) { onProgress = null; }
  63019. if (onError === void 0) { onError = null; }
  63020. if (pluginExtension === void 0) { pluginExtension = null; }
  63021. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  63022. };
  63023. /**
  63024. * Load a scene
  63025. * @param rootUrl a string that defines the root url for scene and resources
  63026. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  63027. * @param engine is the instance of BABYLON.Engine to use to create the scene
  63028. * @param onProgress a callback with a progress event for each file being loaded
  63029. * @param pluginExtension the extension used to determine the plugin
  63030. * @returns The loaded scene
  63031. */
  63032. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  63033. if (onProgress === void 0) { onProgress = null; }
  63034. if (pluginExtension === void 0) { pluginExtension = null; }
  63035. return new Promise(function (resolve, reject) {
  63036. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  63037. resolve(scene);
  63038. }, onProgress, function (scene, message, exception) {
  63039. reject(exception || new Error(message));
  63040. }, pluginExtension);
  63041. });
  63042. };
  63043. /**
  63044. * Append a scene
  63045. * @param rootUrl a string that defines the root url for scene and resources
  63046. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  63047. * @param scene is the instance of BABYLON.Scene to append to
  63048. * @param onSuccess a callback with the scene when import succeeds
  63049. * @param onProgress a callback with a progress event for each file being loaded
  63050. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  63051. * @param pluginExtension the extension used to determine the plugin
  63052. * @returns The loaded plugin
  63053. */
  63054. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  63055. if (onSuccess === void 0) { onSuccess = null; }
  63056. if (onProgress === void 0) { onProgress = null; }
  63057. if (onError === void 0) { onError = null; }
  63058. if (pluginExtension === void 0) { pluginExtension = null; }
  63059. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  63060. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  63061. return null;
  63062. }
  63063. if (SceneLoader.ShowLoadingScreen) {
  63064. scene.getEngine().displayLoadingUI();
  63065. }
  63066. var loadingToken = {};
  63067. scene._addPendingData(loadingToken);
  63068. var disposeHandler = function () {
  63069. scene._removePendingData(loadingToken);
  63070. scene.getEngine().hideLoadingUI();
  63071. };
  63072. var errorHandler = function (message, exception) {
  63073. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  63074. if (onError) {
  63075. onError(scene, errorMessage, exception);
  63076. }
  63077. else {
  63078. BABYLON.Tools.Error(errorMessage);
  63079. // should the exception be thrown?
  63080. }
  63081. disposeHandler();
  63082. };
  63083. var progressHandler = onProgress ? function (event) {
  63084. try {
  63085. onProgress(event);
  63086. }
  63087. catch (e) {
  63088. errorHandler("Error in onProgress callback", e);
  63089. }
  63090. } : undefined;
  63091. var successHandler = function () {
  63092. if (onSuccess) {
  63093. try {
  63094. onSuccess(scene);
  63095. }
  63096. catch (e) {
  63097. errorHandler("Error in onSuccess callback", e);
  63098. }
  63099. }
  63100. scene._removePendingData(loadingToken);
  63101. };
  63102. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  63103. if (sceneFilename === "") {
  63104. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  63105. }
  63106. if (plugin.load) {
  63107. var syncedPlugin = plugin;
  63108. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  63109. return;
  63110. }
  63111. scene.loadingPluginName = plugin.name;
  63112. successHandler();
  63113. }
  63114. else {
  63115. var asyncedPlugin = plugin;
  63116. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  63117. scene.loadingPluginName = plugin.name;
  63118. successHandler();
  63119. }).catch(function (error) {
  63120. errorHandler(error.message, error);
  63121. });
  63122. }
  63123. if (SceneLoader.ShowLoadingScreen) {
  63124. scene.executeWhenReady(function () {
  63125. scene.getEngine().hideLoadingUI();
  63126. });
  63127. }
  63128. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  63129. };
  63130. /**
  63131. * Append a scene
  63132. * @param rootUrl a string that defines the root url for scene and resources
  63133. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  63134. * @param scene is the instance of BABYLON.Scene to append to
  63135. * @param onProgress a callback with a progress event for each file being loaded
  63136. * @param pluginExtension the extension used to determine the plugin
  63137. * @returns The given scene
  63138. */
  63139. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  63140. if (onProgress === void 0) { onProgress = null; }
  63141. if (pluginExtension === void 0) { pluginExtension = null; }
  63142. return new Promise(function (resolve, reject) {
  63143. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  63144. resolve(scene);
  63145. }, onProgress, function (scene, message, exception) {
  63146. reject(exception || new Error(message));
  63147. }, pluginExtension);
  63148. });
  63149. };
  63150. /**
  63151. * Load a scene into an asset container
  63152. * @param rootUrl a string that defines the root url for scene and resources
  63153. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  63154. * @param scene is the instance of BABYLON.Scene to append to
  63155. * @param onSuccess a callback with the scene when import succeeds
  63156. * @param onProgress a callback with a progress event for each file being loaded
  63157. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  63158. * @param pluginExtension the extension used to determine the plugin
  63159. * @returns The loaded plugin
  63160. */
  63161. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  63162. if (onSuccess === void 0) { onSuccess = null; }
  63163. if (onProgress === void 0) { onProgress = null; }
  63164. if (onError === void 0) { onError = null; }
  63165. if (pluginExtension === void 0) { pluginExtension = null; }
  63166. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  63167. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  63168. return null;
  63169. }
  63170. var loadingToken = {};
  63171. scene._addPendingData(loadingToken);
  63172. var disposeHandler = function () {
  63173. scene._removePendingData(loadingToken);
  63174. };
  63175. var errorHandler = function (message, exception) {
  63176. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  63177. if (onError) {
  63178. onError(scene, errorMessage, exception);
  63179. }
  63180. else {
  63181. BABYLON.Tools.Error(errorMessage);
  63182. // should the exception be thrown?
  63183. }
  63184. disposeHandler();
  63185. };
  63186. var progressHandler = onProgress ? function (event) {
  63187. try {
  63188. onProgress(event);
  63189. }
  63190. catch (e) {
  63191. errorHandler("Error in onProgress callback", e);
  63192. }
  63193. } : undefined;
  63194. var successHandler = function (assets) {
  63195. if (onSuccess) {
  63196. try {
  63197. onSuccess(assets);
  63198. }
  63199. catch (e) {
  63200. errorHandler("Error in onSuccess callback", e);
  63201. }
  63202. }
  63203. scene._removePendingData(loadingToken);
  63204. };
  63205. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  63206. if (plugin.loadAssetContainer) {
  63207. var syncedPlugin = plugin;
  63208. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  63209. if (!assetContainer) {
  63210. return;
  63211. }
  63212. scene.loadingPluginName = plugin.name;
  63213. successHandler(assetContainer);
  63214. }
  63215. else if (plugin.loadAssetContainerAsync) {
  63216. var asyncedPlugin = plugin;
  63217. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  63218. scene.loadingPluginName = plugin.name;
  63219. successHandler(assetContainer);
  63220. }).catch(function (error) {
  63221. errorHandler(error.message, error);
  63222. });
  63223. }
  63224. else {
  63225. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  63226. }
  63227. if (SceneLoader.ShowLoadingScreen) {
  63228. scene.executeWhenReady(function () {
  63229. scene.getEngine().hideLoadingUI();
  63230. });
  63231. }
  63232. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  63233. };
  63234. /**
  63235. * Load a scene into an asset container
  63236. * @param rootUrl a string that defines the root url for scene and resources
  63237. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  63238. * @param scene is the instance of BABYLON.Scene to append to
  63239. * @param onProgress a callback with a progress event for each file being loaded
  63240. * @param pluginExtension the extension used to determine the plugin
  63241. * @returns The loaded asset container
  63242. */
  63243. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  63244. if (onProgress === void 0) { onProgress = null; }
  63245. if (pluginExtension === void 0) { pluginExtension = null; }
  63246. return new Promise(function (resolve, reject) {
  63247. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  63248. resolve(assetContainer);
  63249. }, onProgress, function (scene, message, exception) {
  63250. reject(exception || new Error(message));
  63251. }, pluginExtension);
  63252. });
  63253. };
  63254. // Flags
  63255. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  63256. SceneLoader._ShowLoadingScreen = true;
  63257. SceneLoader._CleanBoneMatrixWeights = false;
  63258. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  63259. // Members
  63260. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  63261. SceneLoader._registeredPlugins = {};
  63262. return SceneLoader;
  63263. }());
  63264. BABYLON.SceneLoader = SceneLoader;
  63265. ;
  63266. })(BABYLON || (BABYLON = {}));
  63267. //# sourceMappingURL=babylon.sceneLoader.js.map
  63268. "use strict";
  63269. var BABYLON;
  63270. (function (BABYLON) {
  63271. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  63272. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  63273. var parsedMaterial = parsedData.materials[index];
  63274. if (parsedMaterial.id === id) {
  63275. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  63276. }
  63277. }
  63278. return null;
  63279. };
  63280. var isDescendantOf = function (mesh, names, hierarchyIds) {
  63281. for (var i in names) {
  63282. if (mesh.name === names[i]) {
  63283. hierarchyIds.push(mesh.id);
  63284. return true;
  63285. }
  63286. }
  63287. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  63288. hierarchyIds.push(mesh.id);
  63289. return true;
  63290. }
  63291. return false;
  63292. };
  63293. var logOperation = function (operation, producer) {
  63294. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  63295. };
  63296. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  63297. if (addToScene === void 0) { addToScene = false; }
  63298. var container = new BABYLON.AssetContainer(scene);
  63299. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  63300. // when SceneLoader.debugLogging = true (default), or exception encountered.
  63301. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  63302. // and avoid problems with multiple concurrent .babylon loads.
  63303. var log = "importScene has failed JSON parse";
  63304. try {
  63305. var parsedData = JSON.parse(data);
  63306. log = "";
  63307. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  63308. var index;
  63309. var cache;
  63310. // Lights
  63311. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  63312. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  63313. var parsedLight = parsedData.lights[index];
  63314. var light = BABYLON.Light.Parse(parsedLight, scene);
  63315. if (light) {
  63316. container.lights.push(light);
  63317. log += (index === 0 ? "\n\tLights:" : "");
  63318. log += "\n\t\t" + light.toString(fullDetails);
  63319. }
  63320. }
  63321. }
  63322. // Animations
  63323. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  63324. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  63325. var parsedAnimation = parsedData.animations[index];
  63326. var animation = BABYLON.Animation.Parse(parsedAnimation);
  63327. scene.animations.push(animation);
  63328. container.animations.push(animation);
  63329. log += (index === 0 ? "\n\tAnimations:" : "");
  63330. log += "\n\t\t" + animation.toString(fullDetails);
  63331. }
  63332. }
  63333. // Materials
  63334. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  63335. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  63336. var parsedMaterial = parsedData.materials[index];
  63337. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  63338. container.materials.push(mat);
  63339. log += (index === 0 ? "\n\tMaterials:" : "");
  63340. log += "\n\t\t" + mat.toString(fullDetails);
  63341. }
  63342. }
  63343. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  63344. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  63345. var parsedMultiMaterial = parsedData.multiMaterials[index];
  63346. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  63347. container.multiMaterials.push(mmat);
  63348. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  63349. log += "\n\t\t" + mmat.toString(fullDetails);
  63350. }
  63351. }
  63352. // Morph targets
  63353. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  63354. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  63355. var managerData = _a[_i];
  63356. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  63357. }
  63358. }
  63359. // Skeletons
  63360. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  63361. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  63362. var parsedSkeleton = parsedData.skeletons[index];
  63363. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  63364. container.skeletons.push(skeleton);
  63365. log += (index === 0 ? "\n\tSkeletons:" : "");
  63366. log += "\n\t\t" + skeleton.toString(fullDetails);
  63367. }
  63368. }
  63369. // Geometries
  63370. var geometries = parsedData.geometries;
  63371. if (geometries !== undefined && geometries !== null) {
  63372. var addedGeometry = new Array();
  63373. // Boxes
  63374. var boxes = geometries.boxes;
  63375. if (boxes !== undefined && boxes !== null) {
  63376. for (index = 0, cache = boxes.length; index < cache; index++) {
  63377. var parsedBox = boxes[index];
  63378. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  63379. }
  63380. }
  63381. // Spheres
  63382. var spheres = geometries.spheres;
  63383. if (spheres !== undefined && spheres !== null) {
  63384. for (index = 0, cache = spheres.length; index < cache; index++) {
  63385. var parsedSphere = spheres[index];
  63386. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  63387. }
  63388. }
  63389. // Cylinders
  63390. var cylinders = geometries.cylinders;
  63391. if (cylinders !== undefined && cylinders !== null) {
  63392. for (index = 0, cache = cylinders.length; index < cache; index++) {
  63393. var parsedCylinder = cylinders[index];
  63394. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  63395. }
  63396. }
  63397. // Toruses
  63398. var toruses = geometries.toruses;
  63399. if (toruses !== undefined && toruses !== null) {
  63400. for (index = 0, cache = toruses.length; index < cache; index++) {
  63401. var parsedTorus = toruses[index];
  63402. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  63403. }
  63404. }
  63405. // Grounds
  63406. var grounds = geometries.grounds;
  63407. if (grounds !== undefined && grounds !== null) {
  63408. for (index = 0, cache = grounds.length; index < cache; index++) {
  63409. var parsedGround = grounds[index];
  63410. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  63411. }
  63412. }
  63413. // Planes
  63414. var planes = geometries.planes;
  63415. if (planes !== undefined && planes !== null) {
  63416. for (index = 0, cache = planes.length; index < cache; index++) {
  63417. var parsedPlane = planes[index];
  63418. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  63419. }
  63420. }
  63421. // TorusKnots
  63422. var torusKnots = geometries.torusKnots;
  63423. if (torusKnots !== undefined && torusKnots !== null) {
  63424. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  63425. var parsedTorusKnot = torusKnots[index];
  63426. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  63427. }
  63428. }
  63429. // VertexData
  63430. var vertexData = geometries.vertexData;
  63431. if (vertexData !== undefined && vertexData !== null) {
  63432. for (index = 0, cache = vertexData.length; index < cache; index++) {
  63433. var parsedVertexData = vertexData[index];
  63434. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  63435. }
  63436. }
  63437. addedGeometry.forEach(function (g) {
  63438. if (g) {
  63439. container.geometries.push(g);
  63440. }
  63441. });
  63442. }
  63443. // Transform nodes
  63444. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  63445. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  63446. var parsedTransformNode = parsedData.transformNodes[index];
  63447. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  63448. container.transformNodes.push(node);
  63449. }
  63450. }
  63451. // Meshes
  63452. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  63453. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  63454. var parsedMesh = parsedData.meshes[index];
  63455. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  63456. container.meshes.push(mesh);
  63457. log += (index === 0 ? "\n\tMeshes:" : "");
  63458. log += "\n\t\t" + mesh.toString(fullDetails);
  63459. }
  63460. }
  63461. // Cameras
  63462. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  63463. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  63464. var parsedCamera = parsedData.cameras[index];
  63465. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  63466. container.cameras.push(camera);
  63467. log += (index === 0 ? "\n\tCameras:" : "");
  63468. log += "\n\t\t" + camera.toString(fullDetails);
  63469. }
  63470. }
  63471. // Browsing all the graph to connect the dots
  63472. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  63473. var camera = scene.cameras[index];
  63474. if (camera._waitingParentId) {
  63475. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  63476. camera._waitingParentId = null;
  63477. }
  63478. }
  63479. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  63480. var light_1 = scene.lights[index];
  63481. if (light_1 && light_1._waitingParentId) {
  63482. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  63483. light_1._waitingParentId = null;
  63484. }
  63485. }
  63486. // Sounds
  63487. // TODO: add sound
  63488. var loadedSounds = [];
  63489. var loadedSound;
  63490. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  63491. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  63492. var parsedSound = parsedData.sounds[index];
  63493. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63494. if (!parsedSound.url)
  63495. parsedSound.url = parsedSound.name;
  63496. if (!loadedSounds[parsedSound.url]) {
  63497. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  63498. loadedSounds[parsedSound.url] = loadedSound;
  63499. container.sounds.push(loadedSound);
  63500. }
  63501. else {
  63502. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  63503. }
  63504. }
  63505. else {
  63506. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  63507. }
  63508. }
  63509. }
  63510. loadedSounds = [];
  63511. // Connect parents & children and parse actions
  63512. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  63513. var transformNode = scene.transformNodes[index];
  63514. if (transformNode._waitingParentId) {
  63515. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  63516. transformNode._waitingParentId = null;
  63517. }
  63518. }
  63519. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63520. var mesh = scene.meshes[index];
  63521. if (mesh._waitingParentId) {
  63522. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  63523. mesh._waitingParentId = null;
  63524. }
  63525. if (mesh._waitingActions) {
  63526. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  63527. mesh._waitingActions = null;
  63528. }
  63529. }
  63530. // freeze world matrix application
  63531. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63532. var currentMesh = scene.meshes[index];
  63533. if (currentMesh._waitingFreezeWorldMatrix) {
  63534. currentMesh.freezeWorldMatrix();
  63535. currentMesh._waitingFreezeWorldMatrix = null;
  63536. }
  63537. else {
  63538. currentMesh.computeWorldMatrix(true);
  63539. }
  63540. }
  63541. // Particles Systems
  63542. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  63543. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  63544. var parsedParticleSystem = parsedData.particleSystems[index];
  63545. if (parsedParticleSystem.activeParticleCount) {
  63546. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  63547. container.particleSystems.push(ps);
  63548. }
  63549. else {
  63550. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  63551. container.particleSystems.push(ps);
  63552. }
  63553. }
  63554. }
  63555. // Lens flares
  63556. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  63557. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  63558. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  63559. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  63560. container.lensFlareSystems.push(lf);
  63561. }
  63562. }
  63563. // Shadows
  63564. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  63565. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  63566. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  63567. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  63568. container.shadowGenerators.push(sg);
  63569. }
  63570. }
  63571. // Lights exclusions / inclusions
  63572. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  63573. var light_2 = scene.lights[index];
  63574. // Excluded check
  63575. if (light_2._excludedMeshesIds.length > 0) {
  63576. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  63577. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  63578. if (excludedMesh) {
  63579. light_2.excludedMeshes.push(excludedMesh);
  63580. }
  63581. }
  63582. light_2._excludedMeshesIds = [];
  63583. }
  63584. // Included check
  63585. if (light_2._includedOnlyMeshesIds.length > 0) {
  63586. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  63587. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  63588. if (includedOnlyMesh) {
  63589. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  63590. }
  63591. }
  63592. light_2._includedOnlyMeshesIds = [];
  63593. }
  63594. }
  63595. // Actions (scene)
  63596. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  63597. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  63598. }
  63599. if (!addToScene) {
  63600. container.removeAllFromScene();
  63601. }
  63602. }
  63603. catch (err) {
  63604. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  63605. if (onError) {
  63606. onError(msg, err);
  63607. }
  63608. else {
  63609. BABYLON.Tools.Log(msg);
  63610. throw err;
  63611. }
  63612. }
  63613. finally {
  63614. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63615. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63616. }
  63617. }
  63618. return container;
  63619. };
  63620. BABYLON.SceneLoader.RegisterPlugin({
  63621. name: "babylon.js",
  63622. extensions: ".babylon",
  63623. canDirectLoad: function (data) {
  63624. if (data.indexOf("babylon") !== -1) {
  63625. return true;
  63626. }
  63627. return false;
  63628. },
  63629. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  63630. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  63631. // when SceneLoader.debugLogging = true (default), or exception encountered.
  63632. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  63633. // and avoid problems with multiple concurrent .babylon loads.
  63634. var log = "importMesh has failed JSON parse";
  63635. try {
  63636. var parsedData = JSON.parse(data);
  63637. log = "";
  63638. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  63639. if (!meshesNames) {
  63640. meshesNames = null;
  63641. }
  63642. else if (!Array.isArray(meshesNames)) {
  63643. meshesNames = [meshesNames];
  63644. }
  63645. var hierarchyIds = new Array();
  63646. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  63647. var loadedSkeletonsIds = [];
  63648. var loadedMaterialsIds = [];
  63649. var index;
  63650. var cache;
  63651. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  63652. var parsedMesh = parsedData.meshes[index];
  63653. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  63654. if (meshesNames !== null) {
  63655. // Remove found mesh name from list.
  63656. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  63657. }
  63658. //Geometry?
  63659. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  63660. //does the file contain geometries?
  63661. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  63662. //find the correct geometry and add it to the scene
  63663. var found = false;
  63664. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  63665. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  63666. return;
  63667. }
  63668. else {
  63669. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  63670. if (parsedGeometryData.id === parsedMesh.geometryId) {
  63671. switch (geometryType) {
  63672. case "boxes":
  63673. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  63674. break;
  63675. case "spheres":
  63676. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  63677. break;
  63678. case "cylinders":
  63679. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  63680. break;
  63681. case "toruses":
  63682. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  63683. break;
  63684. case "grounds":
  63685. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  63686. break;
  63687. case "planes":
  63688. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  63689. break;
  63690. case "torusKnots":
  63691. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  63692. break;
  63693. case "vertexData":
  63694. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  63695. break;
  63696. }
  63697. found = true;
  63698. }
  63699. });
  63700. }
  63701. });
  63702. if (found === false) {
  63703. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  63704. }
  63705. }
  63706. }
  63707. // Material ?
  63708. if (parsedMesh.materialId) {
  63709. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  63710. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  63711. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  63712. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  63713. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  63714. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  63715. var subMatId = parsedMultiMaterial.materials[matIndex];
  63716. loadedMaterialsIds.push(subMatId);
  63717. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  63718. if (mat) {
  63719. log += "\n\tMaterial " + mat.toString(fullDetails);
  63720. }
  63721. }
  63722. loadedMaterialsIds.push(parsedMultiMaterial.id);
  63723. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  63724. if (mmat) {
  63725. materialFound = true;
  63726. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  63727. }
  63728. break;
  63729. }
  63730. }
  63731. }
  63732. if (materialFound === false) {
  63733. loadedMaterialsIds.push(parsedMesh.materialId);
  63734. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  63735. if (!mat) {
  63736. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  63737. }
  63738. else {
  63739. log += "\n\tMaterial " + mat.toString(fullDetails);
  63740. }
  63741. }
  63742. }
  63743. // Skeleton ?
  63744. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  63745. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  63746. if (skeletonAlreadyLoaded === false) {
  63747. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  63748. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  63749. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  63750. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  63751. skeletons.push(skeleton);
  63752. loadedSkeletonsIds.push(parsedSkeleton.id);
  63753. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  63754. }
  63755. }
  63756. }
  63757. }
  63758. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  63759. meshes.push(mesh);
  63760. log += "\n\tMesh " + mesh.toString(fullDetails);
  63761. }
  63762. }
  63763. // Connecting parents
  63764. var currentMesh;
  63765. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63766. currentMesh = scene.meshes[index];
  63767. if (currentMesh._waitingParentId) {
  63768. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  63769. currentMesh._waitingParentId = null;
  63770. }
  63771. }
  63772. // freeze and compute world matrix application
  63773. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63774. currentMesh = scene.meshes[index];
  63775. if (currentMesh._waitingFreezeWorldMatrix) {
  63776. currentMesh.freezeWorldMatrix();
  63777. currentMesh._waitingFreezeWorldMatrix = null;
  63778. }
  63779. else {
  63780. currentMesh.computeWorldMatrix(true);
  63781. }
  63782. }
  63783. }
  63784. // Particles
  63785. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  63786. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  63787. var parsedParticleSystem = parsedData.particleSystems[index];
  63788. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  63789. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  63790. }
  63791. }
  63792. }
  63793. return true;
  63794. }
  63795. catch (err) {
  63796. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  63797. if (onError) {
  63798. onError(msg, err);
  63799. }
  63800. else {
  63801. BABYLON.Tools.Log(msg);
  63802. throw err;
  63803. }
  63804. }
  63805. finally {
  63806. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63807. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63808. }
  63809. }
  63810. return false;
  63811. },
  63812. load: function (scene, data, rootUrl, onError) {
  63813. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  63814. // when SceneLoader.debugLogging = true (default), or exception encountered.
  63815. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  63816. // and avoid problems with multiple concurrent .babylon loads.
  63817. var log = "importScene has failed JSON parse";
  63818. try {
  63819. var parsedData = JSON.parse(data);
  63820. log = "";
  63821. // Scene
  63822. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  63823. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  63824. }
  63825. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  63826. scene.autoClear = parsedData.autoClear;
  63827. }
  63828. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  63829. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  63830. }
  63831. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  63832. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  63833. }
  63834. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  63835. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  63836. }
  63837. // Fog
  63838. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  63839. scene.fogMode = parsedData.fogMode;
  63840. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  63841. scene.fogStart = parsedData.fogStart;
  63842. scene.fogEnd = parsedData.fogEnd;
  63843. scene.fogDensity = parsedData.fogDensity;
  63844. log += "\tFog mode for scene: ";
  63845. switch (scene.fogMode) {
  63846. // getters not compiling, so using hardcoded
  63847. case 1:
  63848. log += "exp\n";
  63849. break;
  63850. case 2:
  63851. log += "exp2\n";
  63852. break;
  63853. case 3:
  63854. log += "linear\n";
  63855. break;
  63856. }
  63857. }
  63858. //Physics
  63859. if (parsedData.physicsEnabled) {
  63860. var physicsPlugin;
  63861. if (parsedData.physicsEngine === "cannon") {
  63862. physicsPlugin = new BABYLON.CannonJSPlugin();
  63863. }
  63864. else if (parsedData.physicsEngine === "oimo") {
  63865. physicsPlugin = new BABYLON.OimoJSPlugin();
  63866. }
  63867. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  63868. //else - default engine, which is currently oimo
  63869. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  63870. scene.enablePhysics(physicsGravity, physicsPlugin);
  63871. }
  63872. // Metadata
  63873. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  63874. scene.metadata = parsedData.metadata;
  63875. }
  63876. //collisions, if defined. otherwise, default is true
  63877. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  63878. scene.collisionsEnabled = parsedData.collisionsEnabled;
  63879. }
  63880. scene.workerCollisions = !!parsedData.workerCollisions;
  63881. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  63882. if (!container) {
  63883. return false;
  63884. }
  63885. if (parsedData.autoAnimate) {
  63886. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  63887. }
  63888. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  63889. scene.setActiveCameraByID(parsedData.activeCameraID);
  63890. }
  63891. // Environment texture
  63892. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  63893. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  63894. if (parsedData.createDefaultSkybox === true) {
  63895. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  63896. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  63897. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  63898. }
  63899. }
  63900. // Finish
  63901. return true;
  63902. }
  63903. catch (err) {
  63904. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  63905. if (onError) {
  63906. onError(msg, err);
  63907. }
  63908. else {
  63909. BABYLON.Tools.Log(msg);
  63910. throw err;
  63911. }
  63912. }
  63913. finally {
  63914. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63915. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63916. }
  63917. }
  63918. return false;
  63919. },
  63920. loadAssetContainer: function (scene, data, rootUrl, onError) {
  63921. var container = loadAssetContainer(scene, data, rootUrl, onError);
  63922. return container;
  63923. }
  63924. });
  63925. })(BABYLON || (BABYLON = {}));
  63926. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  63927. "use strict";
  63928. var BABYLON;
  63929. (function (BABYLON) {
  63930. var FilesInput = /** @class */ (function () {
  63931. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  63932. this.onProcessFileCallback = function () { return true; };
  63933. this._engine = engine;
  63934. this._currentScene = scene;
  63935. this._sceneLoadedCallback = sceneLoadedCallback;
  63936. this._progressCallback = progressCallback;
  63937. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  63938. this._textureLoadingCallback = textureLoadingCallback;
  63939. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  63940. this._onReloadCallback = onReloadCallback;
  63941. this._errorCallback = errorCallback;
  63942. }
  63943. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  63944. var _this = this;
  63945. if (elementToMonitor) {
  63946. this._elementToMonitor = elementToMonitor;
  63947. this._dragEnterHandler = function (e) { _this.drag(e); };
  63948. this._dragOverHandler = function (e) { _this.drag(e); };
  63949. this._dropHandler = function (e) { _this.drop(e); };
  63950. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  63951. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  63952. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  63953. }
  63954. };
  63955. FilesInput.prototype.dispose = function () {
  63956. if (!this._elementToMonitor) {
  63957. return;
  63958. }
  63959. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  63960. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  63961. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  63962. };
  63963. FilesInput.prototype.renderFunction = function () {
  63964. if (this._additionalRenderLoopLogicCallback) {
  63965. this._additionalRenderLoopLogicCallback();
  63966. }
  63967. if (this._currentScene) {
  63968. if (this._textureLoadingCallback) {
  63969. var remaining = this._currentScene.getWaitingItemsCount();
  63970. if (remaining > 0) {
  63971. this._textureLoadingCallback(remaining);
  63972. }
  63973. }
  63974. this._currentScene.render();
  63975. }
  63976. };
  63977. FilesInput.prototype.drag = function (e) {
  63978. e.stopPropagation();
  63979. e.preventDefault();
  63980. };
  63981. FilesInput.prototype.drop = function (eventDrop) {
  63982. eventDrop.stopPropagation();
  63983. eventDrop.preventDefault();
  63984. this.loadFiles(eventDrop);
  63985. };
  63986. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  63987. var _this = this;
  63988. var reader = folder.createReader();
  63989. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  63990. reader.readEntries(function (entries) {
  63991. remaining.count += entries.length;
  63992. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  63993. var entry = entries_1[_i];
  63994. if (entry.isFile) {
  63995. entry.file(function (file) {
  63996. file.correctName = relativePath + file.name;
  63997. files.push(file);
  63998. if (--remaining.count === 0) {
  63999. callback();
  64000. }
  64001. });
  64002. }
  64003. else if (entry.isDirectory) {
  64004. _this._traverseFolder(entry, files, remaining, callback);
  64005. }
  64006. }
  64007. if (--remaining.count) {
  64008. callback();
  64009. }
  64010. });
  64011. };
  64012. FilesInput.prototype._processFiles = function (files) {
  64013. for (var i = 0; i < files.length; i++) {
  64014. var name = files[i].correctName.toLowerCase();
  64015. var extension = name.split('.').pop();
  64016. if (!this.onProcessFileCallback(files[i], name, extension)) {
  64017. continue;
  64018. }
  64019. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  64020. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  64021. this._sceneFileToLoad = files[i];
  64022. }
  64023. else {
  64024. FilesInput.FilesToLoad[name] = files[i];
  64025. }
  64026. }
  64027. };
  64028. FilesInput.prototype.loadFiles = function (event) {
  64029. var _this = this;
  64030. if (this._startingProcessingFilesCallback)
  64031. this._startingProcessingFilesCallback();
  64032. // Handling data transfer via drag'n'drop
  64033. if (event && event.dataTransfer && event.dataTransfer.files) {
  64034. this._filesToLoad = event.dataTransfer.files;
  64035. }
  64036. // Handling files from input files
  64037. if (event && event.target && event.target.files) {
  64038. this._filesToLoad = event.target.files;
  64039. }
  64040. if (this._filesToLoad && this._filesToLoad.length > 0) {
  64041. var files_1 = new Array();
  64042. var folders = [];
  64043. var items = event.dataTransfer ? event.dataTransfer.items : null;
  64044. for (var i = 0; i < this._filesToLoad.length; i++) {
  64045. var fileToLoad = this._filesToLoad[i];
  64046. var name_1 = fileToLoad.name.toLowerCase();
  64047. var entry = void 0;
  64048. fileToLoad.correctName = name_1;
  64049. if (items) {
  64050. var item = items[i];
  64051. if (item.getAsEntry) {
  64052. entry = item.getAsEntry();
  64053. }
  64054. else if (item.webkitGetAsEntry) {
  64055. entry = item.webkitGetAsEntry();
  64056. }
  64057. }
  64058. if (!entry) {
  64059. files_1.push(fileToLoad);
  64060. }
  64061. else {
  64062. if (entry.isDirectory) {
  64063. folders.push(entry);
  64064. }
  64065. else {
  64066. files_1.push(fileToLoad);
  64067. }
  64068. }
  64069. }
  64070. if (folders.length === 0) {
  64071. this._processFiles(files_1);
  64072. this._processReload();
  64073. }
  64074. else {
  64075. var remaining = { count: folders.length };
  64076. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  64077. var folder = folders_1[_i];
  64078. this._traverseFolder(folder, files_1, remaining, function () {
  64079. _this._processFiles(files_1);
  64080. if (remaining.count === 0) {
  64081. _this._processReload();
  64082. }
  64083. });
  64084. }
  64085. }
  64086. }
  64087. };
  64088. FilesInput.prototype._processReload = function () {
  64089. if (this._onReloadCallback) {
  64090. this._onReloadCallback(this._sceneFileToLoad);
  64091. }
  64092. else {
  64093. this.reload();
  64094. }
  64095. };
  64096. FilesInput.prototype.reload = function () {
  64097. var _this = this;
  64098. // If a scene file has been provided
  64099. if (this._sceneFileToLoad) {
  64100. if (this._currentScene) {
  64101. if (BABYLON.Tools.errorsCount > 0) {
  64102. BABYLON.Tools.ClearLogCache();
  64103. }
  64104. this._engine.stopRenderLoop();
  64105. this._currentScene.dispose();
  64106. }
  64107. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  64108. if (_this._progressCallback) {
  64109. _this._progressCallback(progress);
  64110. }
  64111. }).then(function (scene) {
  64112. _this._currentScene = scene;
  64113. if (_this._sceneLoadedCallback) {
  64114. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  64115. }
  64116. // Wait for textures and shaders to be ready
  64117. _this._currentScene.executeWhenReady(function () {
  64118. _this._engine.runRenderLoop(function () {
  64119. _this.renderFunction();
  64120. });
  64121. });
  64122. }).catch(function (error) {
  64123. if (_this._errorCallback) {
  64124. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  64125. }
  64126. });
  64127. }
  64128. else {
  64129. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  64130. }
  64131. };
  64132. FilesInput.FilesToLoad = {};
  64133. return FilesInput;
  64134. }());
  64135. BABYLON.FilesInput = FilesInput;
  64136. })(BABYLON || (BABYLON = {}));
  64137. //# sourceMappingURL=babylon.filesInput.js.map
  64138. "use strict";
  64139. var BABYLON;
  64140. (function (BABYLON) {
  64141. /**
  64142. * This class implement a typical dictionary using a string as key and the generic type T as value.
  64143. * The underlying implementation relies on an associative array to ensure the best performances.
  64144. * The value can be anything including 'null' but except 'undefined'
  64145. */
  64146. var StringDictionary = /** @class */ (function () {
  64147. function StringDictionary() {
  64148. this._count = 0;
  64149. this._data = {};
  64150. }
  64151. /**
  64152. * This will clear this dictionary and copy the content from the 'source' one.
  64153. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  64154. * @param source the dictionary to take the content from and copy to this dictionary
  64155. */
  64156. StringDictionary.prototype.copyFrom = function (source) {
  64157. var _this = this;
  64158. this.clear();
  64159. source.forEach(function (t, v) { return _this.add(t, v); });
  64160. };
  64161. /**
  64162. * Get a value based from its key
  64163. * @param key the given key to get the matching value from
  64164. * @return the value if found, otherwise undefined is returned
  64165. */
  64166. StringDictionary.prototype.get = function (key) {
  64167. var val = this._data[key];
  64168. if (val !== undefined) {
  64169. return val;
  64170. }
  64171. return undefined;
  64172. };
  64173. /**
  64174. * Get a value from its key or add it if it doesn't exist.
  64175. * This method will ensure you that a given key/data will be present in the dictionary.
  64176. * @param key the given key to get the matching value from
  64177. * @param factory the factory that will create the value if the key is not present in the dictionary.
  64178. * The factory will only be invoked if there's no data for the given key.
  64179. * @return the value corresponding to the key.
  64180. */
  64181. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  64182. var val = this.get(key);
  64183. if (val !== undefined) {
  64184. return val;
  64185. }
  64186. val = factory(key);
  64187. if (val) {
  64188. this.add(key, val);
  64189. }
  64190. return val;
  64191. };
  64192. /**
  64193. * Get a value from its key if present in the dictionary otherwise add it
  64194. * @param key the key to get the value from
  64195. * @param val if there's no such key/value pair in the dictionary add it with this value
  64196. * @return the value corresponding to the key
  64197. */
  64198. StringDictionary.prototype.getOrAdd = function (key, val) {
  64199. var curVal = this.get(key);
  64200. if (curVal !== undefined) {
  64201. return curVal;
  64202. }
  64203. this.add(key, val);
  64204. return val;
  64205. };
  64206. /**
  64207. * Check if there's a given key in the dictionary
  64208. * @param key the key to check for
  64209. * @return true if the key is present, false otherwise
  64210. */
  64211. StringDictionary.prototype.contains = function (key) {
  64212. return this._data[key] !== undefined;
  64213. };
  64214. /**
  64215. * Add a new key and its corresponding value
  64216. * @param key the key to add
  64217. * @param value the value corresponding to the key
  64218. * @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
  64219. */
  64220. StringDictionary.prototype.add = function (key, value) {
  64221. if (this._data[key] !== undefined) {
  64222. return false;
  64223. }
  64224. this._data[key] = value;
  64225. ++this._count;
  64226. return true;
  64227. };
  64228. StringDictionary.prototype.set = function (key, value) {
  64229. if (this._data[key] === undefined) {
  64230. return false;
  64231. }
  64232. this._data[key] = value;
  64233. return true;
  64234. };
  64235. /**
  64236. * Get the element of the given key and remove it from the dictionary
  64237. * @param key
  64238. */
  64239. StringDictionary.prototype.getAndRemove = function (key) {
  64240. var val = this.get(key);
  64241. if (val !== undefined) {
  64242. delete this._data[key];
  64243. --this._count;
  64244. return val;
  64245. }
  64246. return null;
  64247. };
  64248. /**
  64249. * Remove a key/value from the dictionary.
  64250. * @param key the key to remove
  64251. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  64252. */
  64253. StringDictionary.prototype.remove = function (key) {
  64254. if (this.contains(key)) {
  64255. delete this._data[key];
  64256. --this._count;
  64257. return true;
  64258. }
  64259. return false;
  64260. };
  64261. /**
  64262. * Clear the whole content of the dictionary
  64263. */
  64264. StringDictionary.prototype.clear = function () {
  64265. this._data = {};
  64266. this._count = 0;
  64267. };
  64268. Object.defineProperty(StringDictionary.prototype, "count", {
  64269. get: function () {
  64270. return this._count;
  64271. },
  64272. enumerable: true,
  64273. configurable: true
  64274. });
  64275. /**
  64276. * Execute a callback on each key/val of the dictionary.
  64277. * Note that you can remove any element in this dictionary in the callback implementation
  64278. * @param callback the callback to execute on a given key/value pair
  64279. */
  64280. StringDictionary.prototype.forEach = function (callback) {
  64281. for (var cur in this._data) {
  64282. var val = this._data[cur];
  64283. callback(cur, val);
  64284. }
  64285. };
  64286. /**
  64287. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  64288. * If the callback returns null or undefined the method will iterate to the next key/value pair
  64289. * Note that you can remove any element in this dictionary in the callback implementation
  64290. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  64291. */
  64292. StringDictionary.prototype.first = function (callback) {
  64293. for (var cur in this._data) {
  64294. var val = this._data[cur];
  64295. var res = callback(cur, val);
  64296. if (res) {
  64297. return res;
  64298. }
  64299. }
  64300. return null;
  64301. };
  64302. return StringDictionary;
  64303. }());
  64304. BABYLON.StringDictionary = StringDictionary;
  64305. })(BABYLON || (BABYLON = {}));
  64306. //# sourceMappingURL=babylon.stringDictionary.js.map
  64307. "use strict";
  64308. var BABYLON;
  64309. (function (BABYLON) {
  64310. var Tags = /** @class */ (function () {
  64311. function Tags() {
  64312. }
  64313. Tags.EnableFor = function (obj) {
  64314. obj._tags = obj._tags || {};
  64315. obj.hasTags = function () {
  64316. return Tags.HasTags(obj);
  64317. };
  64318. obj.addTags = function (tagsString) {
  64319. return Tags.AddTagsTo(obj, tagsString);
  64320. };
  64321. obj.removeTags = function (tagsString) {
  64322. return Tags.RemoveTagsFrom(obj, tagsString);
  64323. };
  64324. obj.matchesTagsQuery = function (tagsQuery) {
  64325. return Tags.MatchesQuery(obj, tagsQuery);
  64326. };
  64327. };
  64328. Tags.DisableFor = function (obj) {
  64329. delete obj._tags;
  64330. delete obj.hasTags;
  64331. delete obj.addTags;
  64332. delete obj.removeTags;
  64333. delete obj.matchesTagsQuery;
  64334. };
  64335. Tags.HasTags = function (obj) {
  64336. if (!obj._tags) {
  64337. return false;
  64338. }
  64339. return !BABYLON.Tools.IsEmpty(obj._tags);
  64340. };
  64341. Tags.GetTags = function (obj, asString) {
  64342. if (asString === void 0) { asString = true; }
  64343. if (!obj._tags) {
  64344. return null;
  64345. }
  64346. if (asString) {
  64347. var tagsArray = [];
  64348. for (var tag in obj._tags) {
  64349. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  64350. tagsArray.push(tag);
  64351. }
  64352. }
  64353. return tagsArray.join(" ");
  64354. }
  64355. else {
  64356. return obj._tags;
  64357. }
  64358. };
  64359. // the tags 'true' and 'false' are reserved and cannot be used as tags
  64360. // a tag cannot start with '||', '&&', and '!'
  64361. // it cannot contain whitespaces
  64362. Tags.AddTagsTo = function (obj, tagsString) {
  64363. if (!tagsString) {
  64364. return;
  64365. }
  64366. if (typeof tagsString !== "string") {
  64367. return;
  64368. }
  64369. var tags = tagsString.split(" ");
  64370. tags.forEach(function (tag, index, array) {
  64371. Tags._AddTagTo(obj, tag);
  64372. });
  64373. };
  64374. Tags._AddTagTo = function (obj, tag) {
  64375. tag = tag.trim();
  64376. if (tag === "" || tag === "true" || tag === "false") {
  64377. return;
  64378. }
  64379. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  64380. return;
  64381. }
  64382. Tags.EnableFor(obj);
  64383. obj._tags[tag] = true;
  64384. };
  64385. Tags.RemoveTagsFrom = function (obj, tagsString) {
  64386. if (!Tags.HasTags(obj)) {
  64387. return;
  64388. }
  64389. var tags = tagsString.split(" ");
  64390. for (var t in tags) {
  64391. Tags._RemoveTagFrom(obj, tags[t]);
  64392. }
  64393. };
  64394. Tags._RemoveTagFrom = function (obj, tag) {
  64395. delete obj._tags[tag];
  64396. };
  64397. Tags.MatchesQuery = function (obj, tagsQuery) {
  64398. if (tagsQuery === undefined) {
  64399. return true;
  64400. }
  64401. if (tagsQuery === "") {
  64402. return Tags.HasTags(obj);
  64403. }
  64404. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  64405. };
  64406. return Tags;
  64407. }());
  64408. BABYLON.Tags = Tags;
  64409. })(BABYLON || (BABYLON = {}));
  64410. //# sourceMappingURL=babylon.tags.js.map
  64411. "use strict";
  64412. var BABYLON;
  64413. (function (BABYLON) {
  64414. var AndOrNotEvaluator = /** @class */ (function () {
  64415. function AndOrNotEvaluator() {
  64416. }
  64417. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  64418. if (!query.match(/\([^\(\)]*\)/g)) {
  64419. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  64420. }
  64421. else {
  64422. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  64423. // remove parenthesis
  64424. r = r.slice(1, r.length - 1);
  64425. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  64426. });
  64427. }
  64428. if (query === "true") {
  64429. return true;
  64430. }
  64431. if (query === "false") {
  64432. return false;
  64433. }
  64434. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  64435. };
  64436. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  64437. evaluateCallback = evaluateCallback || (function (r) {
  64438. return r === "true" ? true : false;
  64439. });
  64440. var result;
  64441. var or = parenthesisContent.split("||");
  64442. for (var i in or) {
  64443. if (or.hasOwnProperty(i)) {
  64444. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  64445. var and = ori.split("&&");
  64446. if (and.length > 1) {
  64447. for (var j = 0; j < and.length; ++j) {
  64448. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  64449. if (andj !== "true" && andj !== "false") {
  64450. if (andj[0] === "!") {
  64451. result = !evaluateCallback(andj.substring(1));
  64452. }
  64453. else {
  64454. result = evaluateCallback(andj);
  64455. }
  64456. }
  64457. else {
  64458. result = andj === "true" ? true : false;
  64459. }
  64460. if (!result) {
  64461. ori = "false";
  64462. break;
  64463. }
  64464. }
  64465. }
  64466. if (result || ori === "true") {
  64467. result = true;
  64468. break;
  64469. }
  64470. // result equals false (or undefined)
  64471. if (ori !== "true" && ori !== "false") {
  64472. if (ori[0] === "!") {
  64473. result = !evaluateCallback(ori.substring(1));
  64474. }
  64475. else {
  64476. result = evaluateCallback(ori);
  64477. }
  64478. }
  64479. else {
  64480. result = ori === "true" ? true : false;
  64481. }
  64482. }
  64483. }
  64484. // the whole parenthesis scope is replaced by 'true' or 'false'
  64485. return result ? "true" : "false";
  64486. };
  64487. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  64488. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  64489. // remove whitespaces
  64490. r = r.replace(/[\s]/g, function () { return ""; });
  64491. return r.length % 2 ? "!" : "";
  64492. });
  64493. booleanString = booleanString.trim();
  64494. if (booleanString === "!true") {
  64495. booleanString = "false";
  64496. }
  64497. else if (booleanString === "!false") {
  64498. booleanString = "true";
  64499. }
  64500. return booleanString;
  64501. };
  64502. return AndOrNotEvaluator;
  64503. }());
  64504. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  64505. })(BABYLON || (BABYLON = {}));
  64506. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  64507. "use strict";
  64508. var BABYLON;
  64509. (function (BABYLON) {
  64510. var Database = /** @class */ (function () {
  64511. function Database(urlToScene, callbackManifestChecked) {
  64512. // Handling various flavors of prefixed version of IndexedDB
  64513. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  64514. this.callbackManifestChecked = callbackManifestChecked;
  64515. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  64516. this.db = null;
  64517. this._enableSceneOffline = false;
  64518. this._enableTexturesOffline = false;
  64519. this.manifestVersionFound = 0;
  64520. this.mustUpdateRessources = false;
  64521. this.hasReachedQuota = false;
  64522. if (!Database.IDBStorageEnabled) {
  64523. this.callbackManifestChecked(true);
  64524. }
  64525. else {
  64526. this.checkManifestFile();
  64527. }
  64528. }
  64529. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  64530. get: function () {
  64531. return this._enableSceneOffline;
  64532. },
  64533. enumerable: true,
  64534. configurable: true
  64535. });
  64536. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  64537. get: function () {
  64538. return this._enableTexturesOffline;
  64539. },
  64540. enumerable: true,
  64541. configurable: true
  64542. });
  64543. Database.prototype.checkManifestFile = function () {
  64544. var _this = this;
  64545. var noManifestFile = function () {
  64546. _this._enableSceneOffline = false;
  64547. _this._enableTexturesOffline = false;
  64548. _this.callbackManifestChecked(false);
  64549. };
  64550. var timeStampUsed = false;
  64551. var manifestURL = this.currentSceneUrl + ".manifest";
  64552. var xhr = new XMLHttpRequest();
  64553. if (navigator.onLine) {
  64554. // Adding a timestamp to by-pass browsers' cache
  64555. timeStampUsed = true;
  64556. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  64557. }
  64558. xhr.open("GET", manifestURL, true);
  64559. xhr.addEventListener("load", function () {
  64560. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  64561. try {
  64562. var manifestFile = JSON.parse(xhr.response);
  64563. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  64564. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  64565. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  64566. _this.manifestVersionFound = manifestFile.version;
  64567. }
  64568. if (_this.callbackManifestChecked) {
  64569. _this.callbackManifestChecked(true);
  64570. }
  64571. }
  64572. catch (ex) {
  64573. noManifestFile();
  64574. }
  64575. }
  64576. else {
  64577. noManifestFile();
  64578. }
  64579. }, false);
  64580. xhr.addEventListener("error", function (event) {
  64581. if (timeStampUsed) {
  64582. timeStampUsed = false;
  64583. // Let's retry without the timeStamp
  64584. // It could fail when coupled with HTML5 Offline API
  64585. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  64586. xhr.open("GET", retryManifestURL, true);
  64587. xhr.send();
  64588. }
  64589. else {
  64590. noManifestFile();
  64591. }
  64592. }, false);
  64593. try {
  64594. xhr.send();
  64595. }
  64596. catch (ex) {
  64597. BABYLON.Tools.Error("Error on XHR send request.");
  64598. this.callbackManifestChecked(false);
  64599. }
  64600. };
  64601. Database.prototype.openAsync = function (successCallback, errorCallback) {
  64602. var _this = this;
  64603. var handleError = function () {
  64604. _this.isSupported = false;
  64605. if (errorCallback)
  64606. errorCallback();
  64607. };
  64608. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  64609. // Your browser doesn't support IndexedDB
  64610. this.isSupported = false;
  64611. if (errorCallback)
  64612. errorCallback();
  64613. }
  64614. else {
  64615. // If the DB hasn't been opened or created yet
  64616. if (!this.db) {
  64617. this.hasReachedQuota = false;
  64618. this.isSupported = true;
  64619. var request = this.idbFactory.open("babylonjs", 1);
  64620. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  64621. request.onerror = function (event) {
  64622. handleError();
  64623. };
  64624. // executes when a version change transaction cannot complete due to other active transactions
  64625. request.onblocked = function (event) {
  64626. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  64627. handleError();
  64628. };
  64629. // DB has been opened successfully
  64630. request.onsuccess = function (event) {
  64631. _this.db = request.result;
  64632. successCallback();
  64633. };
  64634. // Initialization of the DB. Creating Scenes & Textures stores
  64635. request.onupgradeneeded = function (event) {
  64636. _this.db = (event.target).result;
  64637. if (_this.db) {
  64638. try {
  64639. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  64640. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  64641. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  64642. }
  64643. catch (ex) {
  64644. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  64645. handleError();
  64646. }
  64647. }
  64648. };
  64649. }
  64650. else {
  64651. if (successCallback)
  64652. successCallback();
  64653. }
  64654. }
  64655. };
  64656. Database.prototype.loadImageFromDB = function (url, image) {
  64657. var _this = this;
  64658. var completeURL = Database.ReturnFullUrlLocation(url);
  64659. var saveAndLoadImage = function () {
  64660. if (!_this.hasReachedQuota && _this.db !== null) {
  64661. // the texture is not yet in the DB, let's try to save it
  64662. _this._saveImageIntoDBAsync(completeURL, image);
  64663. }
  64664. else {
  64665. image.src = url;
  64666. }
  64667. };
  64668. if (!this.mustUpdateRessources) {
  64669. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  64670. }
  64671. else {
  64672. saveAndLoadImage();
  64673. }
  64674. };
  64675. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  64676. if (this.isSupported && this.db !== null) {
  64677. var texture;
  64678. var transaction = this.db.transaction(["textures"]);
  64679. transaction.onabort = function (event) {
  64680. image.src = url;
  64681. };
  64682. transaction.oncomplete = function (event) {
  64683. var blobTextureURL;
  64684. if (texture) {
  64685. var URL = window.URL || window.webkitURL;
  64686. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  64687. image.onerror = function () {
  64688. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  64689. image.src = url;
  64690. };
  64691. image.src = blobTextureURL;
  64692. }
  64693. else {
  64694. notInDBCallback();
  64695. }
  64696. };
  64697. var getRequest = transaction.objectStore("textures").get(url);
  64698. getRequest.onsuccess = function (event) {
  64699. texture = (event.target).result;
  64700. };
  64701. getRequest.onerror = function (event) {
  64702. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  64703. image.src = url;
  64704. };
  64705. }
  64706. else {
  64707. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64708. image.src = url;
  64709. }
  64710. };
  64711. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  64712. var _this = this;
  64713. if (this.isSupported) {
  64714. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  64715. var generateBlobUrl = function () {
  64716. var blobTextureURL;
  64717. if (blob) {
  64718. var URL = window.URL || window.webkitURL;
  64719. try {
  64720. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  64721. }
  64722. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  64723. catch (ex) {
  64724. blobTextureURL = URL.createObjectURL(blob);
  64725. }
  64726. }
  64727. if (blobTextureURL) {
  64728. image.src = blobTextureURL;
  64729. }
  64730. };
  64731. if (Database.IsUASupportingBlobStorage) {
  64732. var xhr = new XMLHttpRequest(), blob;
  64733. xhr.open("GET", url, true);
  64734. xhr.responseType = "blob";
  64735. xhr.addEventListener("load", function () {
  64736. if (xhr.status === 200 && _this.db) {
  64737. // Blob as response (XHR2)
  64738. blob = xhr.response;
  64739. var transaction = _this.db.transaction(["textures"], "readwrite");
  64740. // the transaction could abort because of a QuotaExceededError error
  64741. transaction.onabort = function (event) {
  64742. try {
  64743. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  64744. var srcElement = (event.srcElement || event.target);
  64745. var error = srcElement.error;
  64746. if (error && error.name === "QuotaExceededError") {
  64747. _this.hasReachedQuota = true;
  64748. }
  64749. }
  64750. catch (ex) { }
  64751. generateBlobUrl();
  64752. };
  64753. transaction.oncomplete = function (event) {
  64754. generateBlobUrl();
  64755. };
  64756. var newTexture = { textureUrl: url, data: blob };
  64757. try {
  64758. // Put the blob into the dabase
  64759. var addRequest = transaction.objectStore("textures").put(newTexture);
  64760. addRequest.onsuccess = function (event) {
  64761. };
  64762. addRequest.onerror = function (event) {
  64763. generateBlobUrl();
  64764. };
  64765. }
  64766. catch (ex) {
  64767. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  64768. if (ex.code === 25) {
  64769. Database.IsUASupportingBlobStorage = false;
  64770. }
  64771. image.src = url;
  64772. }
  64773. }
  64774. else {
  64775. image.src = url;
  64776. }
  64777. }, false);
  64778. xhr.addEventListener("error", function (event) {
  64779. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  64780. image.src = url;
  64781. }, false);
  64782. xhr.send();
  64783. }
  64784. else {
  64785. image.src = url;
  64786. }
  64787. }
  64788. else {
  64789. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64790. image.src = url;
  64791. }
  64792. };
  64793. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  64794. var _this = this;
  64795. var updateVersion = function () {
  64796. // the version is not yet in the DB or we need to update it
  64797. _this._saveVersionIntoDBAsync(url, versionLoaded);
  64798. };
  64799. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  64800. };
  64801. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  64802. var _this = this;
  64803. if (this.isSupported && this.db) {
  64804. var version;
  64805. try {
  64806. var transaction = this.db.transaction(["versions"]);
  64807. transaction.oncomplete = function (event) {
  64808. if (version) {
  64809. // If the version in the JSON file is > than the version in DB
  64810. if (_this.manifestVersionFound > version.data) {
  64811. _this.mustUpdateRessources = true;
  64812. updateInDBCallback();
  64813. }
  64814. else {
  64815. callback(version.data);
  64816. }
  64817. }
  64818. else {
  64819. _this.mustUpdateRessources = true;
  64820. updateInDBCallback();
  64821. }
  64822. };
  64823. transaction.onabort = function (event) {
  64824. callback(-1);
  64825. };
  64826. var getRequest = transaction.objectStore("versions").get(url);
  64827. getRequest.onsuccess = function (event) {
  64828. version = (event.target).result;
  64829. };
  64830. getRequest.onerror = function (event) {
  64831. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  64832. callback(-1);
  64833. };
  64834. }
  64835. catch (ex) {
  64836. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  64837. callback(-1);
  64838. }
  64839. }
  64840. else {
  64841. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64842. callback(-1);
  64843. }
  64844. };
  64845. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  64846. var _this = this;
  64847. if (this.isSupported && !this.hasReachedQuota && this.db) {
  64848. try {
  64849. // Open a transaction to the database
  64850. var transaction = this.db.transaction(["versions"], "readwrite");
  64851. // the transaction could abort because of a QuotaExceededError error
  64852. transaction.onabort = function (event) {
  64853. try {
  64854. var error = event.srcElement['error'];
  64855. if (error && error.name === "QuotaExceededError") {
  64856. _this.hasReachedQuota = true;
  64857. }
  64858. }
  64859. catch (ex) { }
  64860. callback(-1);
  64861. };
  64862. transaction.oncomplete = function (event) {
  64863. callback(_this.manifestVersionFound);
  64864. };
  64865. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  64866. // Put the scene into the database
  64867. var addRequest = transaction.objectStore("versions").put(newVersion);
  64868. addRequest.onsuccess = function (event) {
  64869. };
  64870. addRequest.onerror = function (event) {
  64871. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  64872. };
  64873. }
  64874. catch (ex) {
  64875. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  64876. callback(-1);
  64877. }
  64878. }
  64879. else {
  64880. callback(-1);
  64881. }
  64882. };
  64883. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  64884. var _this = this;
  64885. var completeUrl = Database.ReturnFullUrlLocation(url);
  64886. var saveAndLoadFile = function () {
  64887. // the scene is not yet in the DB, let's try to save it
  64888. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  64889. };
  64890. this._checkVersionFromDB(completeUrl, function (version) {
  64891. if (version !== -1) {
  64892. if (!_this.mustUpdateRessources) {
  64893. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  64894. }
  64895. else {
  64896. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  64897. }
  64898. }
  64899. else {
  64900. if (errorCallback) {
  64901. errorCallback();
  64902. }
  64903. }
  64904. });
  64905. };
  64906. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  64907. if (this.isSupported && this.db) {
  64908. var targetStore;
  64909. if (url.indexOf(".babylon") !== -1) {
  64910. targetStore = "scenes";
  64911. }
  64912. else {
  64913. targetStore = "textures";
  64914. }
  64915. var file;
  64916. var transaction = this.db.transaction([targetStore]);
  64917. transaction.oncomplete = function (event) {
  64918. if (file) {
  64919. callback(file.data);
  64920. }
  64921. else {
  64922. notInDBCallback();
  64923. }
  64924. };
  64925. transaction.onabort = function (event) {
  64926. notInDBCallback();
  64927. };
  64928. var getRequest = transaction.objectStore(targetStore).get(url);
  64929. getRequest.onsuccess = function (event) {
  64930. file = (event.target).result;
  64931. };
  64932. getRequest.onerror = function (event) {
  64933. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  64934. notInDBCallback();
  64935. };
  64936. }
  64937. else {
  64938. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64939. callback();
  64940. }
  64941. };
  64942. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  64943. var _this = this;
  64944. if (this.isSupported) {
  64945. var targetStore;
  64946. if (url.indexOf(".babylon") !== -1) {
  64947. targetStore = "scenes";
  64948. }
  64949. else {
  64950. targetStore = "textures";
  64951. }
  64952. // Create XHR
  64953. var xhr = new XMLHttpRequest();
  64954. var fileData;
  64955. xhr.open("GET", url, true);
  64956. if (useArrayBuffer) {
  64957. xhr.responseType = "arraybuffer";
  64958. }
  64959. if (progressCallback) {
  64960. xhr.onprogress = progressCallback;
  64961. }
  64962. xhr.addEventListener("load", function () {
  64963. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  64964. // Blob as response (XHR2)
  64965. //fileData = xhr.responseText;
  64966. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  64967. if (!_this.hasReachedQuota && _this.db) {
  64968. // Open a transaction to the database
  64969. var transaction = _this.db.transaction([targetStore], "readwrite");
  64970. // the transaction could abort because of a QuotaExceededError error
  64971. transaction.onabort = function (event) {
  64972. try {
  64973. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  64974. var error = event.srcElement['error'];
  64975. if (error && error.name === "QuotaExceededError") {
  64976. _this.hasReachedQuota = true;
  64977. }
  64978. }
  64979. catch (ex) { }
  64980. callback(fileData);
  64981. };
  64982. transaction.oncomplete = function (event) {
  64983. callback(fileData);
  64984. };
  64985. var newFile;
  64986. if (targetStore === "scenes") {
  64987. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  64988. }
  64989. else {
  64990. newFile = { textureUrl: url, data: fileData };
  64991. }
  64992. try {
  64993. // Put the scene into the database
  64994. var addRequest = transaction.objectStore(targetStore).put(newFile);
  64995. addRequest.onsuccess = function (event) {
  64996. };
  64997. addRequest.onerror = function (event) {
  64998. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  64999. };
  65000. }
  65001. catch (ex) {
  65002. callback(fileData);
  65003. }
  65004. }
  65005. else {
  65006. callback(fileData);
  65007. }
  65008. }
  65009. else {
  65010. callback();
  65011. }
  65012. }, false);
  65013. xhr.addEventListener("error", function (event) {
  65014. BABYLON.Tools.Error("error on XHR request.");
  65015. callback();
  65016. }, false);
  65017. xhr.send();
  65018. }
  65019. else {
  65020. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  65021. callback();
  65022. }
  65023. };
  65024. Database.IsUASupportingBlobStorage = true;
  65025. Database.IDBStorageEnabled = true;
  65026. Database.parseURL = function (url) {
  65027. var a = document.createElement('a');
  65028. a.href = url;
  65029. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  65030. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  65031. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  65032. return absLocation;
  65033. };
  65034. Database.ReturnFullUrlLocation = function (url) {
  65035. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  65036. return (Database.parseURL(window.location.href) + url);
  65037. }
  65038. else {
  65039. return url;
  65040. }
  65041. };
  65042. return Database;
  65043. }());
  65044. BABYLON.Database = Database;
  65045. })(BABYLON || (BABYLON = {}));
  65046. //# sourceMappingURL=babylon.database.js.map
  65047. "use strict";
  65048. var BABYLON;
  65049. (function (BABYLON) {
  65050. var FresnelParameters = /** @class */ (function () {
  65051. function FresnelParameters() {
  65052. this._isEnabled = true;
  65053. this.leftColor = BABYLON.Color3.White();
  65054. this.rightColor = BABYLON.Color3.Black();
  65055. this.bias = 0;
  65056. this.power = 1;
  65057. }
  65058. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  65059. get: function () {
  65060. return this._isEnabled;
  65061. },
  65062. set: function (value) {
  65063. if (this._isEnabled === value) {
  65064. return;
  65065. }
  65066. this._isEnabled = value;
  65067. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  65068. },
  65069. enumerable: true,
  65070. configurable: true
  65071. });
  65072. FresnelParameters.prototype.clone = function () {
  65073. var newFresnelParameters = new FresnelParameters();
  65074. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  65075. return newFresnelParameters;
  65076. };
  65077. FresnelParameters.prototype.serialize = function () {
  65078. var serializationObject = {};
  65079. serializationObject.isEnabled = this.isEnabled;
  65080. serializationObject.leftColor = this.leftColor.asArray();
  65081. serializationObject.rightColor = this.rightColor.asArray();
  65082. serializationObject.bias = this.bias;
  65083. serializationObject.power = this.power;
  65084. return serializationObject;
  65085. };
  65086. FresnelParameters.Parse = function (parsedFresnelParameters) {
  65087. var fresnelParameters = new FresnelParameters();
  65088. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  65089. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  65090. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  65091. fresnelParameters.bias = parsedFresnelParameters.bias;
  65092. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  65093. return fresnelParameters;
  65094. };
  65095. return FresnelParameters;
  65096. }());
  65097. BABYLON.FresnelParameters = FresnelParameters;
  65098. })(BABYLON || (BABYLON = {}));
  65099. //# sourceMappingURL=babylon.fresnelParameters.js.map
  65100. "use strict";
  65101. var BABYLON;
  65102. (function (BABYLON) {
  65103. var MultiMaterial = /** @class */ (function (_super) {
  65104. __extends(MultiMaterial, _super);
  65105. function MultiMaterial(name, scene) {
  65106. var _this = _super.call(this, name, scene, true) || this;
  65107. scene.multiMaterials.push(_this);
  65108. _this.subMaterials = new Array();
  65109. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  65110. return _this;
  65111. }
  65112. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  65113. get: function () {
  65114. return this._subMaterials;
  65115. },
  65116. set: function (value) {
  65117. this._subMaterials = value;
  65118. this._hookArray(value);
  65119. },
  65120. enumerable: true,
  65121. configurable: true
  65122. });
  65123. MultiMaterial.prototype._hookArray = function (array) {
  65124. var _this = this;
  65125. var oldPush = array.push;
  65126. array.push = function () {
  65127. var items = [];
  65128. for (var _i = 0; _i < arguments.length; _i++) {
  65129. items[_i] = arguments[_i];
  65130. }
  65131. var result = oldPush.apply(array, items);
  65132. _this._markAllSubMeshesAsTexturesDirty();
  65133. return result;
  65134. };
  65135. var oldSplice = array.splice;
  65136. array.splice = function (index, deleteCount) {
  65137. var deleted = oldSplice.apply(array, [index, deleteCount]);
  65138. _this._markAllSubMeshesAsTexturesDirty();
  65139. return deleted;
  65140. };
  65141. };
  65142. // Properties
  65143. MultiMaterial.prototype.getSubMaterial = function (index) {
  65144. if (index < 0 || index >= this.subMaterials.length) {
  65145. return this.getScene().defaultMaterial;
  65146. }
  65147. return this.subMaterials[index];
  65148. };
  65149. MultiMaterial.prototype.getActiveTextures = function () {
  65150. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  65151. if (subMaterial) {
  65152. return subMaterial.getActiveTextures();
  65153. }
  65154. else {
  65155. return [];
  65156. }
  65157. }));
  65158. var _a;
  65159. };
  65160. // Methods
  65161. MultiMaterial.prototype.getClassName = function () {
  65162. return "MultiMaterial";
  65163. };
  65164. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  65165. for (var index = 0; index < this.subMaterials.length; index++) {
  65166. var subMaterial = this.subMaterials[index];
  65167. if (subMaterial) {
  65168. if (subMaterial.storeEffectOnSubMeshes) {
  65169. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  65170. return false;
  65171. }
  65172. continue;
  65173. }
  65174. if (!subMaterial.isReady(mesh)) {
  65175. return false;
  65176. }
  65177. }
  65178. }
  65179. return true;
  65180. };
  65181. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  65182. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  65183. for (var index = 0; index < this.subMaterials.length; index++) {
  65184. var subMaterial = null;
  65185. var current = this.subMaterials[index];
  65186. if (cloneChildren && current) {
  65187. subMaterial = current.clone(name + "-" + current.name);
  65188. }
  65189. else {
  65190. subMaterial = this.subMaterials[index];
  65191. }
  65192. newMultiMaterial.subMaterials.push(subMaterial);
  65193. }
  65194. return newMultiMaterial;
  65195. };
  65196. MultiMaterial.prototype.serialize = function () {
  65197. var serializationObject = {};
  65198. serializationObject.name = this.name;
  65199. serializationObject.id = this.id;
  65200. if (BABYLON.Tags) {
  65201. serializationObject.tags = BABYLON.Tags.GetTags(this);
  65202. }
  65203. serializationObject.materials = [];
  65204. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  65205. var subMat = this.subMaterials[matIndex];
  65206. if (subMat) {
  65207. serializationObject.materials.push(subMat.id);
  65208. }
  65209. else {
  65210. serializationObject.materials.push(null);
  65211. }
  65212. }
  65213. return serializationObject;
  65214. };
  65215. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  65216. var scene = this.getScene();
  65217. if (!scene) {
  65218. return;
  65219. }
  65220. var index = scene.multiMaterials.indexOf(this);
  65221. if (index >= 0) {
  65222. scene.multiMaterials.splice(index, 1);
  65223. }
  65224. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  65225. };
  65226. return MultiMaterial;
  65227. }(BABYLON.Material));
  65228. BABYLON.MultiMaterial = MultiMaterial;
  65229. })(BABYLON || (BABYLON = {}));
  65230. //# sourceMappingURL=babylon.multiMaterial.js.map
  65231. "use strict";
  65232. var BABYLON;
  65233. (function (BABYLON) {
  65234. var FreeCameraTouchInput = /** @class */ (function () {
  65235. function FreeCameraTouchInput() {
  65236. this._offsetX = null;
  65237. this._offsetY = null;
  65238. this._pointerPressed = new Array();
  65239. this.touchAngularSensibility = 200000.0;
  65240. this.touchMoveSensibility = 250.0;
  65241. }
  65242. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  65243. var _this = this;
  65244. var previousPosition = null;
  65245. if (this._pointerInput === undefined) {
  65246. this._onLostFocus = function (evt) {
  65247. _this._offsetX = null;
  65248. _this._offsetY = null;
  65249. };
  65250. this._pointerInput = function (p, s) {
  65251. var evt = p.event;
  65252. if (evt.pointerType === "mouse") {
  65253. return;
  65254. }
  65255. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  65256. if (!noPreventDefault) {
  65257. evt.preventDefault();
  65258. }
  65259. _this._pointerPressed.push(evt.pointerId);
  65260. if (_this._pointerPressed.length !== 1) {
  65261. return;
  65262. }
  65263. previousPosition = {
  65264. x: evt.clientX,
  65265. y: evt.clientY
  65266. };
  65267. }
  65268. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  65269. if (!noPreventDefault) {
  65270. evt.preventDefault();
  65271. }
  65272. var index = _this._pointerPressed.indexOf(evt.pointerId);
  65273. if (index === -1) {
  65274. return;
  65275. }
  65276. _this._pointerPressed.splice(index, 1);
  65277. if (index != 0) {
  65278. return;
  65279. }
  65280. previousPosition = null;
  65281. _this._offsetX = null;
  65282. _this._offsetY = null;
  65283. }
  65284. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  65285. if (!noPreventDefault) {
  65286. evt.preventDefault();
  65287. }
  65288. if (!previousPosition) {
  65289. return;
  65290. }
  65291. var index = _this._pointerPressed.indexOf(evt.pointerId);
  65292. if (index != 0) {
  65293. return;
  65294. }
  65295. _this._offsetX = evt.clientX - previousPosition.x;
  65296. _this._offsetY = -(evt.clientY - previousPosition.y);
  65297. }
  65298. };
  65299. }
  65300. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  65301. if (this._onLostFocus) {
  65302. element.addEventListener("blur", this._onLostFocus);
  65303. }
  65304. };
  65305. FreeCameraTouchInput.prototype.detachControl = function (element) {
  65306. if (this._pointerInput && element) {
  65307. if (this._observer) {
  65308. this.camera.getScene().onPointerObservable.remove(this._observer);
  65309. this._observer = null;
  65310. }
  65311. if (this._onLostFocus) {
  65312. element.removeEventListener("blur", this._onLostFocus);
  65313. this._onLostFocus = null;
  65314. }
  65315. this._pointerPressed = [];
  65316. this._offsetX = null;
  65317. this._offsetY = null;
  65318. }
  65319. };
  65320. FreeCameraTouchInput.prototype.checkInputs = function () {
  65321. if (this._offsetX && this._offsetY) {
  65322. var camera = this.camera;
  65323. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  65324. if (this._pointerPressed.length > 1) {
  65325. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  65326. }
  65327. else {
  65328. var speed = camera._computeLocalCameraSpeed();
  65329. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  65330. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  65331. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  65332. }
  65333. }
  65334. };
  65335. FreeCameraTouchInput.prototype.getClassName = function () {
  65336. return "FreeCameraTouchInput";
  65337. };
  65338. FreeCameraTouchInput.prototype.getSimpleName = function () {
  65339. return "touch";
  65340. };
  65341. __decorate([
  65342. BABYLON.serialize()
  65343. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  65344. __decorate([
  65345. BABYLON.serialize()
  65346. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  65347. return FreeCameraTouchInput;
  65348. }());
  65349. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  65350. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  65351. })(BABYLON || (BABYLON = {}));
  65352. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  65353. "use strict";
  65354. var BABYLON;
  65355. (function (BABYLON) {
  65356. // We're mainly based on the logic defined into the FreeCamera code
  65357. var TouchCamera = /** @class */ (function (_super) {
  65358. __extends(TouchCamera, _super);
  65359. //-- end properties for backward compatibility for inputs
  65360. function TouchCamera(name, position, scene) {
  65361. var _this = _super.call(this, name, position, scene) || this;
  65362. _this.inputs.addTouch();
  65363. _this._setupInputs();
  65364. return _this;
  65365. }
  65366. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  65367. //-- Begin properties for backward compatibility for inputs
  65368. get: function () {
  65369. var touch = this.inputs.attached["touch"];
  65370. if (touch)
  65371. return touch.touchAngularSensibility;
  65372. return 0;
  65373. },
  65374. set: function (value) {
  65375. var touch = this.inputs.attached["touch"];
  65376. if (touch)
  65377. touch.touchAngularSensibility = value;
  65378. },
  65379. enumerable: true,
  65380. configurable: true
  65381. });
  65382. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  65383. get: function () {
  65384. var touch = this.inputs.attached["touch"];
  65385. if (touch)
  65386. return touch.touchMoveSensibility;
  65387. return 0;
  65388. },
  65389. set: function (value) {
  65390. var touch = this.inputs.attached["touch"];
  65391. if (touch)
  65392. touch.touchMoveSensibility = value;
  65393. },
  65394. enumerable: true,
  65395. configurable: true
  65396. });
  65397. TouchCamera.prototype.getClassName = function () {
  65398. return "TouchCamera";
  65399. };
  65400. TouchCamera.prototype._setupInputs = function () {
  65401. var mouse = this.inputs.attached["mouse"];
  65402. if (mouse) {
  65403. mouse.touchEnabled = false;
  65404. }
  65405. };
  65406. return TouchCamera;
  65407. }(BABYLON.FreeCamera));
  65408. BABYLON.TouchCamera = TouchCamera;
  65409. })(BABYLON || (BABYLON = {}));
  65410. //# sourceMappingURL=babylon.touchCamera.js.map
  65411. "use strict";
  65412. var BABYLON;
  65413. (function (BABYLON) {
  65414. var ProceduralTexture = /** @class */ (function (_super) {
  65415. __extends(ProceduralTexture, _super);
  65416. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  65417. if (fallbackTexture === void 0) { fallbackTexture = null; }
  65418. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65419. if (isCube === void 0) { isCube = false; }
  65420. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  65421. _this.isCube = isCube;
  65422. _this.isEnabled = true;
  65423. _this._currentRefreshId = -1;
  65424. _this._refreshRate = 1;
  65425. _this._vertexBuffers = {};
  65426. _this._uniforms = new Array();
  65427. _this._samplers = new Array();
  65428. _this._textures = {};
  65429. _this._floats = {};
  65430. _this._floatsArrays = {};
  65431. _this._colors3 = {};
  65432. _this._colors4 = {};
  65433. _this._vectors2 = {};
  65434. _this._vectors3 = {};
  65435. _this._matrices = {};
  65436. _this._fallbackTextureUsed = false;
  65437. scene._proceduralTextures.push(_this);
  65438. _this._engine = scene.getEngine();
  65439. _this.name = name;
  65440. _this.isRenderTarget = true;
  65441. _this._size = size;
  65442. _this._generateMipMaps = generateMipMaps;
  65443. _this.setFragment(fragment);
  65444. _this._fallbackTexture = fallbackTexture;
  65445. if (isCube) {
  65446. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  65447. _this.setFloat("face", 0);
  65448. }
  65449. else {
  65450. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  65451. }
  65452. // VBO
  65453. var vertices = [];
  65454. vertices.push(1, 1);
  65455. vertices.push(-1, 1);
  65456. vertices.push(-1, -1);
  65457. vertices.push(1, -1);
  65458. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  65459. _this._createIndexBuffer();
  65460. return _this;
  65461. }
  65462. ProceduralTexture.prototype._createIndexBuffer = function () {
  65463. var engine = this._engine;
  65464. // Indices
  65465. var indices = [];
  65466. indices.push(0);
  65467. indices.push(1);
  65468. indices.push(2);
  65469. indices.push(0);
  65470. indices.push(2);
  65471. indices.push(3);
  65472. this._indexBuffer = engine.createIndexBuffer(indices);
  65473. };
  65474. ProceduralTexture.prototype._rebuild = function () {
  65475. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65476. if (vb) {
  65477. vb._rebuild();
  65478. }
  65479. this._createIndexBuffer();
  65480. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  65481. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  65482. }
  65483. };
  65484. ProceduralTexture.prototype.reset = function () {
  65485. if (this._effect === undefined) {
  65486. return;
  65487. }
  65488. var engine = this._engine;
  65489. engine._releaseEffect(this._effect);
  65490. };
  65491. ProceduralTexture.prototype.isReady = function () {
  65492. var _this = this;
  65493. var engine = this._engine;
  65494. var shaders;
  65495. if (!this._fragment) {
  65496. return false;
  65497. }
  65498. if (this._fallbackTextureUsed) {
  65499. return true;
  65500. }
  65501. if (this._fragment.fragmentElement !== undefined) {
  65502. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  65503. }
  65504. else {
  65505. shaders = { vertex: "procedural", fragment: this._fragment };
  65506. }
  65507. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  65508. _this.releaseInternalTexture();
  65509. if (_this._fallbackTexture) {
  65510. _this._texture = _this._fallbackTexture._texture;
  65511. if (_this._texture) {
  65512. _this._texture.incrementReferences();
  65513. }
  65514. }
  65515. _this._fallbackTextureUsed = true;
  65516. });
  65517. return this._effect.isReady();
  65518. };
  65519. ProceduralTexture.prototype.resetRefreshCounter = function () {
  65520. this._currentRefreshId = -1;
  65521. };
  65522. ProceduralTexture.prototype.setFragment = function (fragment) {
  65523. this._fragment = fragment;
  65524. };
  65525. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  65526. get: function () {
  65527. return this._refreshRate;
  65528. },
  65529. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  65530. set: function (value) {
  65531. this._refreshRate = value;
  65532. this.resetRefreshCounter();
  65533. },
  65534. enumerable: true,
  65535. configurable: true
  65536. });
  65537. ProceduralTexture.prototype._shouldRender = function () {
  65538. if (!this.isEnabled || !this.isReady() || !this._texture) {
  65539. return false;
  65540. }
  65541. if (this._fallbackTextureUsed) {
  65542. return false;
  65543. }
  65544. if (this._currentRefreshId === -1) {
  65545. this._currentRefreshId = 1;
  65546. return true;
  65547. }
  65548. if (this.refreshRate === this._currentRefreshId) {
  65549. this._currentRefreshId = 1;
  65550. return true;
  65551. }
  65552. this._currentRefreshId++;
  65553. return false;
  65554. };
  65555. ProceduralTexture.prototype.getRenderSize = function () {
  65556. return this._size;
  65557. };
  65558. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  65559. if (this._fallbackTextureUsed) {
  65560. return;
  65561. }
  65562. this.releaseInternalTexture();
  65563. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  65564. };
  65565. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  65566. if (this._uniforms.indexOf(uniformName) === -1) {
  65567. this._uniforms.push(uniformName);
  65568. }
  65569. };
  65570. ProceduralTexture.prototype.setTexture = function (name, texture) {
  65571. if (this._samplers.indexOf(name) === -1) {
  65572. this._samplers.push(name);
  65573. }
  65574. this._textures[name] = texture;
  65575. return this;
  65576. };
  65577. ProceduralTexture.prototype.setFloat = function (name, value) {
  65578. this._checkUniform(name);
  65579. this._floats[name] = value;
  65580. return this;
  65581. };
  65582. ProceduralTexture.prototype.setFloats = function (name, value) {
  65583. this._checkUniform(name);
  65584. this._floatsArrays[name] = value;
  65585. return this;
  65586. };
  65587. ProceduralTexture.prototype.setColor3 = function (name, value) {
  65588. this._checkUniform(name);
  65589. this._colors3[name] = value;
  65590. return this;
  65591. };
  65592. ProceduralTexture.prototype.setColor4 = function (name, value) {
  65593. this._checkUniform(name);
  65594. this._colors4[name] = value;
  65595. return this;
  65596. };
  65597. ProceduralTexture.prototype.setVector2 = function (name, value) {
  65598. this._checkUniform(name);
  65599. this._vectors2[name] = value;
  65600. return this;
  65601. };
  65602. ProceduralTexture.prototype.setVector3 = function (name, value) {
  65603. this._checkUniform(name);
  65604. this._vectors3[name] = value;
  65605. return this;
  65606. };
  65607. ProceduralTexture.prototype.setMatrix = function (name, value) {
  65608. this._checkUniform(name);
  65609. this._matrices[name] = value;
  65610. return this;
  65611. };
  65612. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  65613. var scene = this.getScene();
  65614. if (!scene) {
  65615. return;
  65616. }
  65617. var engine = this._engine;
  65618. // Render
  65619. engine.enableEffect(this._effect);
  65620. engine.setState(false);
  65621. // Texture
  65622. for (var name in this._textures) {
  65623. this._effect.setTexture(name, this._textures[name]);
  65624. }
  65625. // Float
  65626. for (name in this._floats) {
  65627. this._effect.setFloat(name, this._floats[name]);
  65628. }
  65629. // Floats
  65630. for (name in this._floatsArrays) {
  65631. this._effect.setArray(name, this._floatsArrays[name]);
  65632. }
  65633. // Color3
  65634. for (name in this._colors3) {
  65635. this._effect.setColor3(name, this._colors3[name]);
  65636. }
  65637. // Color4
  65638. for (name in this._colors4) {
  65639. var color = this._colors4[name];
  65640. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  65641. }
  65642. // Vector2
  65643. for (name in this._vectors2) {
  65644. this._effect.setVector2(name, this._vectors2[name]);
  65645. }
  65646. // Vector3
  65647. for (name in this._vectors3) {
  65648. this._effect.setVector3(name, this._vectors3[name]);
  65649. }
  65650. // Matrix
  65651. for (name in this._matrices) {
  65652. this._effect.setMatrix(name, this._matrices[name]);
  65653. }
  65654. if (!this._texture) {
  65655. return;
  65656. }
  65657. if (this.isCube) {
  65658. for (var face = 0; face < 6; face++) {
  65659. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  65660. // VBOs
  65661. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  65662. this._effect.setFloat("face", face);
  65663. // Clear
  65664. engine.clear(scene.clearColor, true, true, true);
  65665. // Draw order
  65666. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65667. // Mipmaps
  65668. if (face === 5) {
  65669. engine.generateMipMapsForCubemap(this._texture);
  65670. }
  65671. }
  65672. }
  65673. else {
  65674. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  65675. // VBOs
  65676. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  65677. // Clear
  65678. engine.clear(scene.clearColor, true, true, true);
  65679. // Draw order
  65680. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65681. }
  65682. // Unbind
  65683. engine.unBindFramebuffer(this._texture, this.isCube);
  65684. if (this.onGenerated) {
  65685. this.onGenerated();
  65686. }
  65687. };
  65688. ProceduralTexture.prototype.clone = function () {
  65689. var textureSize = this.getSize();
  65690. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  65691. // Base texture
  65692. newTexture.hasAlpha = this.hasAlpha;
  65693. newTexture.level = this.level;
  65694. // RenderTarget Texture
  65695. newTexture.coordinatesMode = this.coordinatesMode;
  65696. return newTexture;
  65697. };
  65698. ProceduralTexture.prototype.dispose = function () {
  65699. var scene = this.getScene();
  65700. if (!scene) {
  65701. return;
  65702. }
  65703. var index = scene._proceduralTextures.indexOf(this);
  65704. if (index >= 0) {
  65705. scene._proceduralTextures.splice(index, 1);
  65706. }
  65707. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65708. if (vertexBuffer) {
  65709. vertexBuffer.dispose();
  65710. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65711. }
  65712. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  65713. this._indexBuffer = null;
  65714. }
  65715. _super.prototype.dispose.call(this);
  65716. };
  65717. return ProceduralTexture;
  65718. }(BABYLON.Texture));
  65719. BABYLON.ProceduralTexture = ProceduralTexture;
  65720. })(BABYLON || (BABYLON = {}));
  65721. //# sourceMappingURL=babylon.proceduralTexture.js.map
  65722. "use strict";
  65723. var BABYLON;
  65724. (function (BABYLON) {
  65725. var CustomProceduralTexture = /** @class */ (function (_super) {
  65726. __extends(CustomProceduralTexture, _super);
  65727. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  65728. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  65729. _this._animate = true;
  65730. _this._time = 0;
  65731. _this._texturePath = texturePath;
  65732. //Try to load json
  65733. _this.loadJson(texturePath);
  65734. _this.refreshRate = 1;
  65735. return _this;
  65736. }
  65737. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  65738. var _this = this;
  65739. var noConfigFile = function () {
  65740. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  65741. try {
  65742. _this.setFragment(_this._texturePath);
  65743. }
  65744. catch (ex) {
  65745. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  65746. }
  65747. };
  65748. var configFileUrl = jsonUrl + "/config.json";
  65749. var xhr = new XMLHttpRequest();
  65750. xhr.open("GET", configFileUrl, true);
  65751. xhr.addEventListener("load", function () {
  65752. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  65753. try {
  65754. _this._config = JSON.parse(xhr.response);
  65755. _this.updateShaderUniforms();
  65756. _this.updateTextures();
  65757. _this.setFragment(_this._texturePath + "/custom");
  65758. _this._animate = _this._config.animate;
  65759. _this.refreshRate = _this._config.refreshrate;
  65760. }
  65761. catch (ex) {
  65762. noConfigFile();
  65763. }
  65764. }
  65765. else {
  65766. noConfigFile();
  65767. }
  65768. }, false);
  65769. xhr.addEventListener("error", function () {
  65770. noConfigFile();
  65771. }, false);
  65772. try {
  65773. xhr.send();
  65774. }
  65775. catch (ex) {
  65776. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  65777. }
  65778. };
  65779. CustomProceduralTexture.prototype.isReady = function () {
  65780. if (!_super.prototype.isReady.call(this)) {
  65781. return false;
  65782. }
  65783. for (var name in this._textures) {
  65784. var texture = this._textures[name];
  65785. if (!texture.isReady()) {
  65786. return false;
  65787. }
  65788. }
  65789. return true;
  65790. };
  65791. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  65792. var scene = this.getScene();
  65793. if (this._animate && scene) {
  65794. this._time += scene.getAnimationRatio() * 0.03;
  65795. this.updateShaderUniforms();
  65796. }
  65797. _super.prototype.render.call(this, useCameraPostProcess);
  65798. };
  65799. CustomProceduralTexture.prototype.updateTextures = function () {
  65800. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  65801. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  65802. }
  65803. };
  65804. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  65805. if (this._config) {
  65806. for (var j = 0; j < this._config.uniforms.length; j++) {
  65807. var uniform = this._config.uniforms[j];
  65808. switch (uniform.type) {
  65809. case "float":
  65810. this.setFloat(uniform.name, uniform.value);
  65811. break;
  65812. case "color3":
  65813. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  65814. break;
  65815. case "color4":
  65816. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  65817. break;
  65818. case "vector2":
  65819. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  65820. break;
  65821. case "vector3":
  65822. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  65823. break;
  65824. }
  65825. }
  65826. }
  65827. this.setFloat("time", this._time);
  65828. };
  65829. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  65830. get: function () {
  65831. return this._animate;
  65832. },
  65833. set: function (value) {
  65834. this._animate = value;
  65835. },
  65836. enumerable: true,
  65837. configurable: true
  65838. });
  65839. return CustomProceduralTexture;
  65840. }(BABYLON.ProceduralTexture));
  65841. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  65842. })(BABYLON || (BABYLON = {}));
  65843. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  65844. "use strict";
  65845. var BABYLON;
  65846. (function (BABYLON) {
  65847. var FreeCameraGamepadInput = /** @class */ (function () {
  65848. function FreeCameraGamepadInput() {
  65849. this.gamepadAngularSensibility = 200;
  65850. this.gamepadMoveSensibility = 40;
  65851. // private members
  65852. this._cameraTransform = BABYLON.Matrix.Identity();
  65853. this._deltaTransform = BABYLON.Vector3.Zero();
  65854. this._vector3 = BABYLON.Vector3.Zero();
  65855. this._vector2 = BABYLON.Vector2.Zero();
  65856. }
  65857. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  65858. var _this = this;
  65859. var manager = this.camera.getScene().gamepadManager;
  65860. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  65861. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  65862. // prioritize XBOX gamepads.
  65863. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  65864. _this.gamepad = gamepad;
  65865. }
  65866. }
  65867. });
  65868. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  65869. if (_this.gamepad === gamepad) {
  65870. _this.gamepad = null;
  65871. }
  65872. });
  65873. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  65874. };
  65875. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  65876. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  65877. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  65878. this.gamepad = null;
  65879. };
  65880. FreeCameraGamepadInput.prototype.checkInputs = function () {
  65881. if (this.gamepad && this.gamepad.leftStick) {
  65882. var camera = this.camera;
  65883. var LSValues = this.gamepad.leftStick;
  65884. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  65885. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  65886. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  65887. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  65888. var RSValues = this.gamepad.rightStick;
  65889. if (RSValues) {
  65890. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  65891. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  65892. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  65893. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  65894. }
  65895. else {
  65896. RSValues = { x: 0, y: 0 };
  65897. }
  65898. if (!camera.rotationQuaternion) {
  65899. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  65900. }
  65901. else {
  65902. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  65903. }
  65904. var speed = camera._computeLocalCameraSpeed() * 50.0;
  65905. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  65906. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  65907. camera.cameraDirection.addInPlace(this._deltaTransform);
  65908. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  65909. camera.cameraRotation.addInPlace(this._vector2);
  65910. }
  65911. };
  65912. FreeCameraGamepadInput.prototype.getClassName = function () {
  65913. return "FreeCameraGamepadInput";
  65914. };
  65915. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  65916. return "gamepad";
  65917. };
  65918. __decorate([
  65919. BABYLON.serialize()
  65920. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  65921. __decorate([
  65922. BABYLON.serialize()
  65923. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  65924. return FreeCameraGamepadInput;
  65925. }());
  65926. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  65927. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  65928. })(BABYLON || (BABYLON = {}));
  65929. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  65930. "use strict";
  65931. var BABYLON;
  65932. (function (BABYLON) {
  65933. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  65934. function ArcRotateCameraGamepadInput() {
  65935. this.gamepadRotationSensibility = 80;
  65936. this.gamepadMoveSensibility = 40;
  65937. }
  65938. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  65939. var _this = this;
  65940. var manager = this.camera.getScene().gamepadManager;
  65941. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  65942. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  65943. // prioritize XBOX gamepads.
  65944. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  65945. _this.gamepad = gamepad;
  65946. }
  65947. }
  65948. });
  65949. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  65950. if (_this.gamepad === gamepad) {
  65951. _this.gamepad = null;
  65952. }
  65953. });
  65954. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  65955. };
  65956. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  65957. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  65958. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  65959. this.gamepad = null;
  65960. };
  65961. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  65962. if (this.gamepad) {
  65963. var camera = this.camera;
  65964. var RSValues = this.gamepad.rightStick;
  65965. if (RSValues) {
  65966. if (RSValues.x != 0) {
  65967. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  65968. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  65969. camera.inertialAlphaOffset += normalizedRX;
  65970. }
  65971. }
  65972. if (RSValues.y != 0) {
  65973. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  65974. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  65975. camera.inertialBetaOffset += normalizedRY;
  65976. }
  65977. }
  65978. }
  65979. var LSValues = this.gamepad.leftStick;
  65980. if (LSValues && LSValues.y != 0) {
  65981. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  65982. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  65983. this.camera.inertialRadiusOffset -= normalizedLY;
  65984. }
  65985. }
  65986. }
  65987. };
  65988. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  65989. return "ArcRotateCameraGamepadInput";
  65990. };
  65991. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  65992. return "gamepad";
  65993. };
  65994. __decorate([
  65995. BABYLON.serialize()
  65996. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  65997. __decorate([
  65998. BABYLON.serialize()
  65999. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  66000. return ArcRotateCameraGamepadInput;
  66001. }());
  66002. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  66003. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  66004. })(BABYLON || (BABYLON = {}));
  66005. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  66006. "use strict";
  66007. var BABYLON;
  66008. (function (BABYLON) {
  66009. var GamepadManager = /** @class */ (function () {
  66010. function GamepadManager(_scene) {
  66011. var _this = this;
  66012. this._scene = _scene;
  66013. this._babylonGamepads = [];
  66014. this._oneGamepadConnected = false;
  66015. this._isMonitoring = false;
  66016. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  66017. if (!BABYLON.Tools.IsWindowObjectExist()) {
  66018. this._gamepadEventSupported = false;
  66019. }
  66020. else {
  66021. this._gamepadEventSupported = 'GamepadEvent' in window;
  66022. this._gamepadSupport = (navigator.getGamepads ||
  66023. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  66024. }
  66025. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  66026. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  66027. for (var i in _this._babylonGamepads) {
  66028. var gamepad = _this._babylonGamepads[i];
  66029. if (gamepad && gamepad._isConnected) {
  66030. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  66031. }
  66032. }
  66033. });
  66034. this._onGamepadConnectedEvent = function (evt) {
  66035. var gamepad = evt.gamepad;
  66036. if (gamepad.index in _this._babylonGamepads) {
  66037. if (_this._babylonGamepads[gamepad.index].isConnected) {
  66038. return;
  66039. }
  66040. }
  66041. var newGamepad;
  66042. if (_this._babylonGamepads[gamepad.index]) {
  66043. newGamepad = _this._babylonGamepads[gamepad.index];
  66044. newGamepad.browserGamepad = gamepad;
  66045. newGamepad._isConnected = true;
  66046. }
  66047. else {
  66048. newGamepad = _this._addNewGamepad(gamepad);
  66049. }
  66050. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  66051. _this._startMonitoringGamepads();
  66052. };
  66053. this._onGamepadDisconnectedEvent = function (evt) {
  66054. var gamepad = evt.gamepad;
  66055. // Remove the gamepad from the list of gamepads to monitor.
  66056. for (var i in _this._babylonGamepads) {
  66057. if (_this._babylonGamepads[i].index === gamepad.index) {
  66058. var disconnectedGamepad = _this._babylonGamepads[i];
  66059. disconnectedGamepad._isConnected = false;
  66060. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  66061. break;
  66062. }
  66063. }
  66064. };
  66065. if (this._gamepadSupport) {
  66066. //first add already-connected gamepads
  66067. this._updateGamepadObjects();
  66068. if (this._babylonGamepads.length) {
  66069. this._startMonitoringGamepads();
  66070. }
  66071. // Checking if the gamepad connected event is supported (like in Firefox)
  66072. if (this._gamepadEventSupported) {
  66073. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  66074. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  66075. }
  66076. else {
  66077. this._startMonitoringGamepads();
  66078. }
  66079. }
  66080. }
  66081. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  66082. get: function () {
  66083. return this._babylonGamepads;
  66084. },
  66085. enumerable: true,
  66086. configurable: true
  66087. });
  66088. GamepadManager.prototype.getGamepadByType = function (type) {
  66089. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  66090. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  66091. var gamepad = _a[_i];
  66092. if (gamepad && gamepad.type === type) {
  66093. return gamepad;
  66094. }
  66095. }
  66096. return null;
  66097. };
  66098. GamepadManager.prototype.dispose = function () {
  66099. if (this._gamepadEventSupported) {
  66100. if (this._onGamepadConnectedEvent) {
  66101. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  66102. }
  66103. if (this._onGamepadDisconnectedEvent) {
  66104. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  66105. }
  66106. this._onGamepadConnectedEvent = null;
  66107. this._onGamepadDisconnectedEvent = null;
  66108. }
  66109. this._babylonGamepads.forEach(function (gamepad) {
  66110. gamepad.dispose();
  66111. });
  66112. this.onGamepadConnectedObservable.clear();
  66113. this.onGamepadDisconnectedObservable.clear();
  66114. this._oneGamepadConnected = false;
  66115. this._stopMonitoringGamepads();
  66116. this._babylonGamepads = [];
  66117. };
  66118. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  66119. if (!this._oneGamepadConnected) {
  66120. this._oneGamepadConnected = true;
  66121. }
  66122. var newGamepad;
  66123. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  66124. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  66125. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  66126. }
  66127. else if (gamepad.pose) {
  66128. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  66129. }
  66130. else {
  66131. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  66132. }
  66133. this._babylonGamepads[newGamepad.index] = newGamepad;
  66134. return newGamepad;
  66135. };
  66136. GamepadManager.prototype._startMonitoringGamepads = function () {
  66137. if (!this._isMonitoring) {
  66138. this._isMonitoring = true;
  66139. //back-comp
  66140. if (!this._scene) {
  66141. this._checkGamepadsStatus();
  66142. }
  66143. }
  66144. };
  66145. GamepadManager.prototype._stopMonitoringGamepads = function () {
  66146. this._isMonitoring = false;
  66147. };
  66148. GamepadManager.prototype._checkGamepadsStatus = function () {
  66149. var _this = this;
  66150. // Hack to be compatible Chrome
  66151. this._updateGamepadObjects();
  66152. for (var i in this._babylonGamepads) {
  66153. var gamepad = this._babylonGamepads[i];
  66154. if (!gamepad || !gamepad.isConnected) {
  66155. continue;
  66156. }
  66157. gamepad.update();
  66158. }
  66159. if (this._isMonitoring && !this._scene) {
  66160. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  66161. }
  66162. };
  66163. // This function is called only on Chrome, which does not properly support
  66164. // connection/disconnection events and forces you to recopy again the gamepad object
  66165. GamepadManager.prototype._updateGamepadObjects = function () {
  66166. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  66167. for (var i = 0; i < gamepads.length; i++) {
  66168. if (gamepads[i]) {
  66169. if (!this._babylonGamepads[gamepads[i].index]) {
  66170. var newGamepad = this._addNewGamepad(gamepads[i]);
  66171. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  66172. }
  66173. else {
  66174. // Forced to copy again this object for Chrome for unknown reason
  66175. this._babylonGamepads[i].browserGamepad = gamepads[i];
  66176. if (!this._babylonGamepads[i].isConnected) {
  66177. this._babylonGamepads[i]._isConnected = true;
  66178. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  66179. }
  66180. }
  66181. }
  66182. }
  66183. };
  66184. return GamepadManager;
  66185. }());
  66186. BABYLON.GamepadManager = GamepadManager;
  66187. })(BABYLON || (BABYLON = {}));
  66188. //# sourceMappingURL=babylon.gamepadManager.js.map
  66189. "use strict";
  66190. var BABYLON;
  66191. (function (BABYLON) {
  66192. var StickValues = /** @class */ (function () {
  66193. function StickValues(x, y) {
  66194. this.x = x;
  66195. this.y = y;
  66196. }
  66197. return StickValues;
  66198. }());
  66199. BABYLON.StickValues = StickValues;
  66200. var Gamepad = /** @class */ (function () {
  66201. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  66202. if (leftStickX === void 0) { leftStickX = 0; }
  66203. if (leftStickY === void 0) { leftStickY = 1; }
  66204. if (rightStickX === void 0) { rightStickX = 2; }
  66205. if (rightStickY === void 0) { rightStickY = 3; }
  66206. this.id = id;
  66207. this.index = index;
  66208. this.browserGamepad = browserGamepad;
  66209. this._isConnected = true;
  66210. this._invertLeftStickY = false;
  66211. this.type = Gamepad.GAMEPAD;
  66212. this._leftStickAxisX = leftStickX;
  66213. this._leftStickAxisY = leftStickY;
  66214. this._rightStickAxisX = rightStickX;
  66215. this._rightStickAxisY = rightStickY;
  66216. if (this.browserGamepad.axes.length >= 2) {
  66217. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  66218. }
  66219. if (this.browserGamepad.axes.length >= 4) {
  66220. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  66221. }
  66222. }
  66223. Object.defineProperty(Gamepad.prototype, "isConnected", {
  66224. get: function () {
  66225. return this._isConnected;
  66226. },
  66227. enumerable: true,
  66228. configurable: true
  66229. });
  66230. Gamepad.prototype.onleftstickchanged = function (callback) {
  66231. this._onleftstickchanged = callback;
  66232. };
  66233. Gamepad.prototype.onrightstickchanged = function (callback) {
  66234. this._onrightstickchanged = callback;
  66235. };
  66236. Object.defineProperty(Gamepad.prototype, "leftStick", {
  66237. get: function () {
  66238. return this._leftStick;
  66239. },
  66240. set: function (newValues) {
  66241. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  66242. this._onleftstickchanged(newValues);
  66243. }
  66244. this._leftStick = newValues;
  66245. },
  66246. enumerable: true,
  66247. configurable: true
  66248. });
  66249. Object.defineProperty(Gamepad.prototype, "rightStick", {
  66250. get: function () {
  66251. return this._rightStick;
  66252. },
  66253. set: function (newValues) {
  66254. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  66255. this._onrightstickchanged(newValues);
  66256. }
  66257. this._rightStick = newValues;
  66258. },
  66259. enumerable: true,
  66260. configurable: true
  66261. });
  66262. Gamepad.prototype.update = function () {
  66263. if (this._leftStick) {
  66264. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  66265. if (this._invertLeftStickY) {
  66266. this.leftStick.y *= -1;
  66267. }
  66268. }
  66269. if (this._rightStick) {
  66270. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  66271. }
  66272. };
  66273. Gamepad.prototype.dispose = function () {
  66274. };
  66275. Gamepad.GAMEPAD = 0;
  66276. Gamepad.GENERIC = 1;
  66277. Gamepad.XBOX = 2;
  66278. Gamepad.POSE_ENABLED = 3;
  66279. return Gamepad;
  66280. }());
  66281. BABYLON.Gamepad = Gamepad;
  66282. var GenericPad = /** @class */ (function (_super) {
  66283. __extends(GenericPad, _super);
  66284. function GenericPad(id, index, browserGamepad) {
  66285. var _this = _super.call(this, id, index, browserGamepad) || this;
  66286. _this.onButtonDownObservable = new BABYLON.Observable();
  66287. _this.onButtonUpObservable = new BABYLON.Observable();
  66288. _this.type = Gamepad.GENERIC;
  66289. _this._buttons = new Array(browserGamepad.buttons.length);
  66290. return _this;
  66291. }
  66292. GenericPad.prototype.onbuttondown = function (callback) {
  66293. this._onbuttondown = callback;
  66294. };
  66295. GenericPad.prototype.onbuttonup = function (callback) {
  66296. this._onbuttonup = callback;
  66297. };
  66298. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  66299. if (newValue !== currentValue) {
  66300. if (newValue === 1) {
  66301. if (this._onbuttondown) {
  66302. this._onbuttondown(buttonIndex);
  66303. }
  66304. this.onButtonDownObservable.notifyObservers(buttonIndex);
  66305. }
  66306. if (newValue === 0) {
  66307. if (this._onbuttonup) {
  66308. this._onbuttonup(buttonIndex);
  66309. }
  66310. this.onButtonUpObservable.notifyObservers(buttonIndex);
  66311. }
  66312. }
  66313. return newValue;
  66314. };
  66315. GenericPad.prototype.update = function () {
  66316. _super.prototype.update.call(this);
  66317. for (var index = 0; index < this._buttons.length; index++) {
  66318. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  66319. }
  66320. };
  66321. GenericPad.prototype.dispose = function () {
  66322. _super.prototype.dispose.call(this);
  66323. this.onButtonDownObservable.clear();
  66324. this.onButtonUpObservable.clear();
  66325. };
  66326. return GenericPad;
  66327. }(Gamepad));
  66328. BABYLON.GenericPad = GenericPad;
  66329. })(BABYLON || (BABYLON = {}));
  66330. //# sourceMappingURL=babylon.gamepad.js.map
  66331. "use strict";
  66332. var BABYLON;
  66333. (function (BABYLON) {
  66334. var Xbox360Button;
  66335. (function (Xbox360Button) {
  66336. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  66337. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  66338. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  66339. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  66340. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  66341. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  66342. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  66343. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  66344. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  66345. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  66346. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  66347. var Xbox360Dpad;
  66348. (function (Xbox360Dpad) {
  66349. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  66350. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  66351. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  66352. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  66353. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  66354. var Xbox360Pad = /** @class */ (function (_super) {
  66355. __extends(Xbox360Pad, _super);
  66356. function Xbox360Pad(id, index, gamepad, xboxOne) {
  66357. if (xboxOne === void 0) { xboxOne = false; }
  66358. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  66359. _this._leftTrigger = 0;
  66360. _this._rightTrigger = 0;
  66361. _this.onButtonDownObservable = new BABYLON.Observable();
  66362. _this.onButtonUpObservable = new BABYLON.Observable();
  66363. _this.onPadDownObservable = new BABYLON.Observable();
  66364. _this.onPadUpObservable = new BABYLON.Observable();
  66365. _this._buttonA = 0;
  66366. _this._buttonB = 0;
  66367. _this._buttonX = 0;
  66368. _this._buttonY = 0;
  66369. _this._buttonBack = 0;
  66370. _this._buttonStart = 0;
  66371. _this._buttonLB = 0;
  66372. _this._buttonRB = 0;
  66373. _this._buttonLeftStick = 0;
  66374. _this._buttonRightStick = 0;
  66375. _this._dPadUp = 0;
  66376. _this._dPadDown = 0;
  66377. _this._dPadLeft = 0;
  66378. _this._dPadRight = 0;
  66379. _this._isXboxOnePad = false;
  66380. _this.type = BABYLON.Gamepad.XBOX;
  66381. _this._isXboxOnePad = xboxOne;
  66382. return _this;
  66383. }
  66384. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  66385. this._onlefttriggerchanged = callback;
  66386. };
  66387. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  66388. this._onrighttriggerchanged = callback;
  66389. };
  66390. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  66391. get: function () {
  66392. return this._leftTrigger;
  66393. },
  66394. set: function (newValue) {
  66395. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  66396. this._onlefttriggerchanged(newValue);
  66397. }
  66398. this._leftTrigger = newValue;
  66399. },
  66400. enumerable: true,
  66401. configurable: true
  66402. });
  66403. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  66404. get: function () {
  66405. return this._rightTrigger;
  66406. },
  66407. set: function (newValue) {
  66408. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  66409. this._onrighttriggerchanged(newValue);
  66410. }
  66411. this._rightTrigger = newValue;
  66412. },
  66413. enumerable: true,
  66414. configurable: true
  66415. });
  66416. Xbox360Pad.prototype.onbuttondown = function (callback) {
  66417. this._onbuttondown = callback;
  66418. };
  66419. Xbox360Pad.prototype.onbuttonup = function (callback) {
  66420. this._onbuttonup = callback;
  66421. };
  66422. Xbox360Pad.prototype.ondpaddown = function (callback) {
  66423. this._ondpaddown = callback;
  66424. };
  66425. Xbox360Pad.prototype.ondpadup = function (callback) {
  66426. this._ondpadup = callback;
  66427. };
  66428. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  66429. if (newValue !== currentValue) {
  66430. if (newValue === 1) {
  66431. if (this._onbuttondown) {
  66432. this._onbuttondown(buttonType);
  66433. }
  66434. this.onButtonDownObservable.notifyObservers(buttonType);
  66435. }
  66436. if (newValue === 0) {
  66437. if (this._onbuttonup) {
  66438. this._onbuttonup(buttonType);
  66439. }
  66440. this.onButtonUpObservable.notifyObservers(buttonType);
  66441. }
  66442. }
  66443. return newValue;
  66444. };
  66445. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  66446. if (newValue !== currentValue) {
  66447. if (newValue === 1) {
  66448. if (this._ondpaddown) {
  66449. this._ondpaddown(buttonType);
  66450. }
  66451. this.onPadDownObservable.notifyObservers(buttonType);
  66452. }
  66453. if (newValue === 0) {
  66454. if (this._ondpadup) {
  66455. this._ondpadup(buttonType);
  66456. }
  66457. this.onPadUpObservable.notifyObservers(buttonType);
  66458. }
  66459. }
  66460. return newValue;
  66461. };
  66462. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  66463. get: function () {
  66464. return this._buttonA;
  66465. },
  66466. set: function (value) {
  66467. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  66468. },
  66469. enumerable: true,
  66470. configurable: true
  66471. });
  66472. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  66473. get: function () {
  66474. return this._buttonB;
  66475. },
  66476. set: function (value) {
  66477. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  66478. },
  66479. enumerable: true,
  66480. configurable: true
  66481. });
  66482. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  66483. get: function () {
  66484. return this._buttonX;
  66485. },
  66486. set: function (value) {
  66487. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  66488. },
  66489. enumerable: true,
  66490. configurable: true
  66491. });
  66492. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  66493. get: function () {
  66494. return this._buttonY;
  66495. },
  66496. set: function (value) {
  66497. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  66498. },
  66499. enumerable: true,
  66500. configurable: true
  66501. });
  66502. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  66503. get: function () {
  66504. return this._buttonStart;
  66505. },
  66506. set: function (value) {
  66507. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  66508. },
  66509. enumerable: true,
  66510. configurable: true
  66511. });
  66512. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  66513. get: function () {
  66514. return this._buttonBack;
  66515. },
  66516. set: function (value) {
  66517. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  66518. },
  66519. enumerable: true,
  66520. configurable: true
  66521. });
  66522. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  66523. get: function () {
  66524. return this._buttonLB;
  66525. },
  66526. set: function (value) {
  66527. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  66528. },
  66529. enumerable: true,
  66530. configurable: true
  66531. });
  66532. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  66533. get: function () {
  66534. return this._buttonRB;
  66535. },
  66536. set: function (value) {
  66537. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  66538. },
  66539. enumerable: true,
  66540. configurable: true
  66541. });
  66542. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  66543. get: function () {
  66544. return this._buttonLeftStick;
  66545. },
  66546. set: function (value) {
  66547. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  66548. },
  66549. enumerable: true,
  66550. configurable: true
  66551. });
  66552. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  66553. get: function () {
  66554. return this._buttonRightStick;
  66555. },
  66556. set: function (value) {
  66557. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  66558. },
  66559. enumerable: true,
  66560. configurable: true
  66561. });
  66562. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  66563. get: function () {
  66564. return this._dPadUp;
  66565. },
  66566. set: function (value) {
  66567. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  66568. },
  66569. enumerable: true,
  66570. configurable: true
  66571. });
  66572. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  66573. get: function () {
  66574. return this._dPadDown;
  66575. },
  66576. set: function (value) {
  66577. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  66578. },
  66579. enumerable: true,
  66580. configurable: true
  66581. });
  66582. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  66583. get: function () {
  66584. return this._dPadLeft;
  66585. },
  66586. set: function (value) {
  66587. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  66588. },
  66589. enumerable: true,
  66590. configurable: true
  66591. });
  66592. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  66593. get: function () {
  66594. return this._dPadRight;
  66595. },
  66596. set: function (value) {
  66597. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  66598. },
  66599. enumerable: true,
  66600. configurable: true
  66601. });
  66602. Xbox360Pad.prototype.update = function () {
  66603. _super.prototype.update.call(this);
  66604. if (this._isXboxOnePad) {
  66605. this.buttonA = this.browserGamepad.buttons[0].value;
  66606. this.buttonB = this.browserGamepad.buttons[1].value;
  66607. this.buttonX = this.browserGamepad.buttons[2].value;
  66608. this.buttonY = this.browserGamepad.buttons[3].value;
  66609. this.buttonLB = this.browserGamepad.buttons[4].value;
  66610. this.buttonRB = this.browserGamepad.buttons[5].value;
  66611. this.leftTrigger = this.browserGamepad.axes[2];
  66612. this.rightTrigger = this.browserGamepad.axes[5];
  66613. this.buttonBack = this.browserGamepad.buttons[9].value;
  66614. this.buttonStart = this.browserGamepad.buttons[8].value;
  66615. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  66616. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  66617. this.dPadUp = this.browserGamepad.buttons[11].value;
  66618. this.dPadDown = this.browserGamepad.buttons[12].value;
  66619. this.dPadLeft = this.browserGamepad.buttons[13].value;
  66620. this.dPadRight = this.browserGamepad.buttons[14].value;
  66621. }
  66622. else {
  66623. this.buttonA = this.browserGamepad.buttons[0].value;
  66624. this.buttonB = this.browserGamepad.buttons[1].value;
  66625. this.buttonX = this.browserGamepad.buttons[2].value;
  66626. this.buttonY = this.browserGamepad.buttons[3].value;
  66627. this.buttonLB = this.browserGamepad.buttons[4].value;
  66628. this.buttonRB = this.browserGamepad.buttons[5].value;
  66629. this.leftTrigger = this.browserGamepad.buttons[6].value;
  66630. this.rightTrigger = this.browserGamepad.buttons[7].value;
  66631. this.buttonBack = this.browserGamepad.buttons[8].value;
  66632. this.buttonStart = this.browserGamepad.buttons[9].value;
  66633. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  66634. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  66635. this.dPadUp = this.browserGamepad.buttons[12].value;
  66636. this.dPadDown = this.browserGamepad.buttons[13].value;
  66637. this.dPadLeft = this.browserGamepad.buttons[14].value;
  66638. this.dPadRight = this.browserGamepad.buttons[15].value;
  66639. }
  66640. };
  66641. Xbox360Pad.prototype.dispose = function () {
  66642. _super.prototype.dispose.call(this);
  66643. this.onButtonDownObservable.clear();
  66644. this.onButtonUpObservable.clear();
  66645. this.onPadDownObservable.clear();
  66646. this.onPadUpObservable.clear();
  66647. };
  66648. return Xbox360Pad;
  66649. }(BABYLON.Gamepad));
  66650. BABYLON.Xbox360Pad = Xbox360Pad;
  66651. })(BABYLON || (BABYLON = {}));
  66652. //# sourceMappingURL=babylon.xboxGamepad.js.map
  66653. "use strict";
  66654. var BABYLON;
  66655. (function (BABYLON) {
  66656. var PoseEnabledControllerType;
  66657. (function (PoseEnabledControllerType) {
  66658. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  66659. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  66660. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  66661. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  66662. /**
  66663. * Google Daydream
  66664. */
  66665. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  66666. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  66667. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  66668. var PoseEnabledControllerHelper = /** @class */ (function () {
  66669. function PoseEnabledControllerHelper() {
  66670. }
  66671. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  66672. // Oculus Touch
  66673. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  66674. return new BABYLON.OculusTouchController(vrGamepad);
  66675. }
  66676. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  66677. return new BABYLON.WindowsMotionController(vrGamepad);
  66678. }
  66679. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  66680. return new BABYLON.ViveController(vrGamepad);
  66681. }
  66682. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  66683. return new BABYLON.GearVRController(vrGamepad);
  66684. }
  66685. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  66686. return new BABYLON.DaydreamController(vrGamepad);
  66687. }
  66688. else {
  66689. return new BABYLON.GenericController(vrGamepad);
  66690. }
  66691. };
  66692. return PoseEnabledControllerHelper;
  66693. }());
  66694. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  66695. var PoseEnabledController = /** @class */ (function (_super) {
  66696. __extends(PoseEnabledController, _super);
  66697. function PoseEnabledController(browserGamepad) {
  66698. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  66699. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  66700. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  66701. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  66702. // Represents device position and rotation in babylon space
  66703. _this.devicePosition = BABYLON.Vector3.Zero();
  66704. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  66705. _this.deviceScaleFactor = 1;
  66706. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  66707. _this._deviceToWorld = BABYLON.Matrix.Identity();
  66708. /**
  66709. * Node to be used when casting a ray from the controller
  66710. */
  66711. _this._pointingPoseNode = null;
  66712. _this._workingMatrix = BABYLON.Matrix.Identity();
  66713. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  66714. _this.controllerType = PoseEnabledControllerType.GENERIC;
  66715. _this.position = BABYLON.Vector3.Zero();
  66716. _this.rotationQuaternion = new BABYLON.Quaternion();
  66717. _this._calculatedPosition = BABYLON.Vector3.Zero();
  66718. _this._calculatedRotation = new BABYLON.Quaternion();
  66719. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  66720. return _this;
  66721. }
  66722. PoseEnabledController.prototype.update = function () {
  66723. _super.prototype.update.call(this);
  66724. var pose = this.browserGamepad.pose;
  66725. this.updateFromDevice(pose);
  66726. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  66727. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  66728. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  66729. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  66730. if (this._mesh) {
  66731. this._mesh.position.copyFrom(this.devicePosition);
  66732. if (this._mesh.rotationQuaternion) {
  66733. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  66734. }
  66735. }
  66736. };
  66737. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  66738. if (poseData) {
  66739. this.rawPose = poseData;
  66740. if (poseData.position) {
  66741. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  66742. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  66743. this._deviceRoomPosition.z *= -1;
  66744. }
  66745. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  66746. this._calculatedPosition.addInPlace(this.position);
  66747. }
  66748. var pose = this.rawPose;
  66749. if (poseData.orientation && pose.orientation) {
  66750. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  66751. if (this._mesh) {
  66752. if (this._mesh.getScene().useRightHandedSystem) {
  66753. this._deviceRoomRotationQuaternion.z *= -1;
  66754. this._deviceRoomRotationQuaternion.w *= -1;
  66755. }
  66756. else {
  66757. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  66758. }
  66759. }
  66760. // if the camera is set, rotate to the camera's rotation
  66761. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  66762. }
  66763. }
  66764. };
  66765. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  66766. if (this._mesh) {
  66767. this._mesh.parent = null;
  66768. }
  66769. this._mesh = mesh;
  66770. if (this._poseControlledCamera) {
  66771. this._mesh.parent = this._poseControlledCamera;
  66772. }
  66773. if (!this._mesh.rotationQuaternion) {
  66774. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  66775. }
  66776. };
  66777. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  66778. this._poseControlledCamera = camera;
  66779. if (this._mesh) {
  66780. this._mesh.parent = this._poseControlledCamera;
  66781. }
  66782. };
  66783. PoseEnabledController.prototype.dispose = function () {
  66784. if (this._mesh) {
  66785. this._mesh.dispose();
  66786. }
  66787. this._mesh = null;
  66788. _super.prototype.dispose.call(this);
  66789. };
  66790. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  66791. get: function () {
  66792. return this._mesh;
  66793. },
  66794. enumerable: true,
  66795. configurable: true
  66796. });
  66797. PoseEnabledController.prototype.getForwardRay = function (length) {
  66798. if (length === void 0) { length = 100; }
  66799. if (!this.mesh) {
  66800. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  66801. }
  66802. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  66803. var origin = m.getTranslation();
  66804. var forward = new BABYLON.Vector3(0, 0, -1);
  66805. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  66806. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  66807. return new BABYLON.Ray(origin, direction, length);
  66808. };
  66809. /**
  66810. * Name of the child mesh that can be used to cast a ray from the controller
  66811. */
  66812. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  66813. return PoseEnabledController;
  66814. }(BABYLON.Gamepad));
  66815. BABYLON.PoseEnabledController = PoseEnabledController;
  66816. })(BABYLON || (BABYLON = {}));
  66817. //# sourceMappingURL=babylon.poseEnabledController.js.map
  66818. "use strict";
  66819. var BABYLON;
  66820. (function (BABYLON) {
  66821. var WebVRController = /** @class */ (function (_super) {
  66822. __extends(WebVRController, _super);
  66823. function WebVRController(vrGamepad) {
  66824. var _this = _super.call(this, vrGamepad) || this;
  66825. // Observables
  66826. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  66827. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  66828. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  66829. _this.onPadStateChangedObservable = new BABYLON.Observable();
  66830. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  66831. _this.pad = { x: 0, y: 0 };
  66832. // avoid GC, store state in a tmp object
  66833. _this._changes = {
  66834. pressChanged: false,
  66835. touchChanged: false,
  66836. valueChanged: false,
  66837. changed: false
  66838. };
  66839. _this._buttons = new Array(vrGamepad.buttons.length);
  66840. _this.hand = vrGamepad.hand;
  66841. return _this;
  66842. }
  66843. WebVRController.prototype.onButtonStateChange = function (callback) {
  66844. this._onButtonStateChange = callback;
  66845. };
  66846. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  66847. get: function () {
  66848. return this._defaultModel;
  66849. },
  66850. enumerable: true,
  66851. configurable: true
  66852. });
  66853. WebVRController.prototype.update = function () {
  66854. _super.prototype.update.call(this);
  66855. for (var index = 0; index < this._buttons.length; index++) {
  66856. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  66857. }
  66858. ;
  66859. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  66860. this.pad.x = this.leftStick.x;
  66861. this.pad.y = this.leftStick.y;
  66862. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  66863. }
  66864. };
  66865. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  66866. if (!newState) {
  66867. newState = {
  66868. pressed: false,
  66869. touched: false,
  66870. value: 0
  66871. };
  66872. }
  66873. if (!currentState) {
  66874. this._buttons[buttonIndex] = {
  66875. pressed: newState.pressed,
  66876. touched: newState.touched,
  66877. value: newState.value
  66878. };
  66879. return;
  66880. }
  66881. this._checkChanges(newState, currentState);
  66882. if (this._changes.changed) {
  66883. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  66884. this._handleButtonChange(buttonIndex, newState, this._changes);
  66885. }
  66886. this._buttons[buttonIndex].pressed = newState.pressed;
  66887. this._buttons[buttonIndex].touched = newState.touched;
  66888. // oculus triggers are never 0, thou not touched.
  66889. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  66890. };
  66891. WebVRController.prototype._checkChanges = function (newState, currentState) {
  66892. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  66893. this._changes.touchChanged = newState.touched !== currentState.touched;
  66894. this._changes.valueChanged = newState.value !== currentState.value;
  66895. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  66896. return this._changes;
  66897. };
  66898. WebVRController.prototype.dispose = function () {
  66899. _super.prototype.dispose.call(this);
  66900. this.onTriggerStateChangedObservable.clear();
  66901. this.onMainButtonStateChangedObservable.clear();
  66902. this.onSecondaryButtonStateChangedObservable.clear();
  66903. this.onPadStateChangedObservable.clear();
  66904. this.onPadValuesChangedObservable.clear();
  66905. };
  66906. return WebVRController;
  66907. }(BABYLON.PoseEnabledController));
  66908. BABYLON.WebVRController = WebVRController;
  66909. })(BABYLON || (BABYLON = {}));
  66910. //# sourceMappingURL=babylon.webVRController.js.map
  66911. "use strict";
  66912. var BABYLON;
  66913. (function (BABYLON) {
  66914. var OculusTouchController = /** @class */ (function (_super) {
  66915. __extends(OculusTouchController, _super);
  66916. function OculusTouchController(vrGamepad) {
  66917. var _this = _super.call(this, vrGamepad) || this;
  66918. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  66919. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  66920. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  66921. return _this;
  66922. }
  66923. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66924. var _this = this;
  66925. var meshName;
  66926. // Hand
  66927. if (this.hand === 'left') {
  66928. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  66929. }
  66930. else {
  66931. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  66932. }
  66933. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  66934. /*
  66935. Parent Mesh name: oculus_touch_left
  66936. - body
  66937. - trigger
  66938. - thumbstick
  66939. - grip
  66940. - button_y
  66941. - button_x
  66942. - button_enter
  66943. */
  66944. _this._defaultModel = newMeshes[1];
  66945. _this.attachToMesh(_this._defaultModel);
  66946. if (meshLoaded) {
  66947. meshLoaded(_this._defaultModel);
  66948. }
  66949. });
  66950. };
  66951. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  66952. // helper getters for left and right hand.
  66953. get: function () {
  66954. if (this.hand === 'right') {
  66955. return this.onMainButtonStateChangedObservable;
  66956. }
  66957. else {
  66958. throw new Error('No A button on left hand');
  66959. }
  66960. },
  66961. enumerable: true,
  66962. configurable: true
  66963. });
  66964. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  66965. get: function () {
  66966. if (this.hand === 'right') {
  66967. return this.onSecondaryButtonStateChangedObservable;
  66968. }
  66969. else {
  66970. throw new Error('No B button on left hand');
  66971. }
  66972. },
  66973. enumerable: true,
  66974. configurable: true
  66975. });
  66976. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  66977. get: function () {
  66978. if (this.hand === 'left') {
  66979. return this.onMainButtonStateChangedObservable;
  66980. }
  66981. else {
  66982. throw new Error('No X button on right hand');
  66983. }
  66984. },
  66985. enumerable: true,
  66986. configurable: true
  66987. });
  66988. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  66989. get: function () {
  66990. if (this.hand === 'left') {
  66991. return this.onSecondaryButtonStateChangedObservable;
  66992. }
  66993. else {
  66994. throw new Error('No Y button on right hand');
  66995. }
  66996. },
  66997. enumerable: true,
  66998. configurable: true
  66999. });
  67000. /*
  67001. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  67002. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  67003. 2) secondary trigger (same)
  67004. 3) A (right) X (left), touch, pressed = value
  67005. 4) B / Y
  67006. 5) thumb rest
  67007. */
  67008. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67009. var notifyObject = state; //{ state: state, changes: changes };
  67010. var triggerDirection = this.hand === 'right' ? -1 : 1;
  67011. switch (buttonIdx) {
  67012. case 0:
  67013. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  67014. return;
  67015. case 1:// index trigger
  67016. if (this._defaultModel) {
  67017. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  67018. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  67019. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  67020. }
  67021. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  67022. return;
  67023. case 2:// secondary trigger
  67024. if (this._defaultModel) {
  67025. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  67026. }
  67027. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  67028. return;
  67029. case 3:
  67030. if (this._defaultModel) {
  67031. if (notifyObject.pressed) {
  67032. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  67033. }
  67034. else {
  67035. (this._defaultModel.getChildren()[1]).position.y = 0;
  67036. }
  67037. }
  67038. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  67039. return;
  67040. case 4:
  67041. if (this._defaultModel) {
  67042. if (notifyObject.pressed) {
  67043. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  67044. }
  67045. else {
  67046. (this._defaultModel.getChildren()[2]).position.y = 0;
  67047. }
  67048. }
  67049. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  67050. return;
  67051. case 5:
  67052. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  67053. return;
  67054. }
  67055. };
  67056. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  67057. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  67058. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  67059. return OculusTouchController;
  67060. }(BABYLON.WebVRController));
  67061. BABYLON.OculusTouchController = OculusTouchController;
  67062. })(BABYLON || (BABYLON = {}));
  67063. //# sourceMappingURL=babylon.oculusTouchController.js.map
  67064. "use strict";
  67065. var BABYLON;
  67066. (function (BABYLON) {
  67067. var ViveController = /** @class */ (function (_super) {
  67068. __extends(ViveController, _super);
  67069. function ViveController(vrGamepad) {
  67070. var _this = _super.call(this, vrGamepad) || this;
  67071. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  67072. _this._invertLeftStickY = true;
  67073. return _this;
  67074. }
  67075. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  67076. var _this = this;
  67077. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  67078. /*
  67079. Parent Mesh name: ViveWand
  67080. - body
  67081. - r_gripper
  67082. - l_gripper
  67083. - menu_button
  67084. - system_button
  67085. - trackpad
  67086. - trigger
  67087. - LED
  67088. */
  67089. _this._defaultModel = newMeshes[1];
  67090. _this.attachToMesh(_this._defaultModel);
  67091. if (meshLoaded) {
  67092. meshLoaded(_this._defaultModel);
  67093. }
  67094. });
  67095. };
  67096. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  67097. get: function () {
  67098. return this.onMainButtonStateChangedObservable;
  67099. },
  67100. enumerable: true,
  67101. configurable: true
  67102. });
  67103. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  67104. get: function () {
  67105. return this.onMainButtonStateChangedObservable;
  67106. },
  67107. enumerable: true,
  67108. configurable: true
  67109. });
  67110. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  67111. get: function () {
  67112. return this.onSecondaryButtonStateChangedObservable;
  67113. },
  67114. enumerable: true,
  67115. configurable: true
  67116. });
  67117. /**
  67118. * Vive mapping:
  67119. * 0: touchpad
  67120. * 1: trigger
  67121. * 2: left AND right buttons
  67122. * 3: menu button
  67123. */
  67124. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67125. var notifyObject = state; //{ state: state, changes: changes };
  67126. switch (buttonIdx) {
  67127. case 0:
  67128. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  67129. return;
  67130. case 1:// index trigger
  67131. if (this._defaultModel) {
  67132. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  67133. }
  67134. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  67135. return;
  67136. case 2:// left AND right button
  67137. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  67138. return;
  67139. case 3:
  67140. if (this._defaultModel) {
  67141. if (notifyObject.pressed) {
  67142. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  67143. }
  67144. else {
  67145. (this._defaultModel.getChildren()[2]).position.y = 0;
  67146. }
  67147. }
  67148. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  67149. return;
  67150. }
  67151. };
  67152. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  67153. ViveController.MODEL_FILENAME = 'wand.babylon';
  67154. return ViveController;
  67155. }(BABYLON.WebVRController));
  67156. BABYLON.ViveController = ViveController;
  67157. })(BABYLON || (BABYLON = {}));
  67158. //# sourceMappingURL=babylon.viveController.js.map
  67159. "use strict";
  67160. var BABYLON;
  67161. (function (BABYLON) {
  67162. var GenericController = /** @class */ (function (_super) {
  67163. __extends(GenericController, _super);
  67164. function GenericController(vrGamepad) {
  67165. return _super.call(this, vrGamepad) || this;
  67166. }
  67167. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  67168. var _this = this;
  67169. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  67170. _this._defaultModel = newMeshes[1];
  67171. _this.attachToMesh(_this._defaultModel);
  67172. if (meshLoaded) {
  67173. meshLoaded(_this._defaultModel);
  67174. }
  67175. });
  67176. };
  67177. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67178. console.log("Button id: " + buttonIdx + "state: ");
  67179. console.dir(state);
  67180. };
  67181. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  67182. GenericController.MODEL_FILENAME = 'generic.babylon';
  67183. return GenericController;
  67184. }(BABYLON.WebVRController));
  67185. BABYLON.GenericController = GenericController;
  67186. })(BABYLON || (BABYLON = {}));
  67187. //# sourceMappingURL=babylon.genericController.js.map
  67188. "use strict";
  67189. var BABYLON;
  67190. (function (BABYLON) {
  67191. var LoadedMeshInfo = /** @class */ (function () {
  67192. function LoadedMeshInfo() {
  67193. this.buttonMeshes = {};
  67194. this.axisMeshes = {};
  67195. }
  67196. return LoadedMeshInfo;
  67197. }());
  67198. var WindowsMotionController = /** @class */ (function (_super) {
  67199. __extends(WindowsMotionController, _super);
  67200. function WindowsMotionController(vrGamepad) {
  67201. var _this = _super.call(this, vrGamepad) || this;
  67202. _this._mapping = {
  67203. // Semantic button names
  67204. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  67205. // A mapping of the button name to glTF model node name
  67206. // that should be transformed by button value.
  67207. buttonMeshNames: {
  67208. 'trigger': 'SELECT',
  67209. 'menu': 'MENU',
  67210. 'grip': 'GRASP',
  67211. 'thumbstick': 'THUMBSTICK_PRESS',
  67212. 'trackpad': 'TOUCHPAD_PRESS'
  67213. },
  67214. // This mapping is used to translate from the Motion Controller to Babylon semantics
  67215. buttonObservableNames: {
  67216. 'trigger': 'onTriggerStateChangedObservable',
  67217. 'menu': 'onSecondaryButtonStateChangedObservable',
  67218. 'grip': 'onMainButtonStateChangedObservable',
  67219. 'thumbstick': 'onPadStateChangedObservable',
  67220. 'trackpad': 'onTrackpadChangedObservable'
  67221. },
  67222. // A mapping of the axis name to glTF model node name
  67223. // that should be transformed by axis value.
  67224. // This array mirrors the browserGamepad.axes array, such that
  67225. // the mesh corresponding to axis 0 is in this array index 0.
  67226. axisMeshNames: [
  67227. 'THUMBSTICK_X',
  67228. 'THUMBSTICK_Y',
  67229. 'TOUCHPAD_TOUCH_X',
  67230. 'TOUCHPAD_TOUCH_Y'
  67231. ],
  67232. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  67233. };
  67234. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  67235. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  67236. _this.trackpad = { x: 0, y: 0 };
  67237. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  67238. _this._loadedMeshInfo = null;
  67239. return _this;
  67240. }
  67241. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  67242. get: function () {
  67243. return this.onTriggerStateChangedObservable;
  67244. },
  67245. enumerable: true,
  67246. configurable: true
  67247. });
  67248. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  67249. get: function () {
  67250. return this.onSecondaryButtonStateChangedObservable;
  67251. },
  67252. enumerable: true,
  67253. configurable: true
  67254. });
  67255. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  67256. get: function () {
  67257. return this.onMainButtonStateChangedObservable;
  67258. },
  67259. enumerable: true,
  67260. configurable: true
  67261. });
  67262. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  67263. get: function () {
  67264. return this.onPadStateChangedObservable;
  67265. },
  67266. enumerable: true,
  67267. configurable: true
  67268. });
  67269. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  67270. get: function () {
  67271. return this.onTrackpadChangedObservable;
  67272. },
  67273. enumerable: true,
  67274. configurable: true
  67275. });
  67276. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  67277. get: function () {
  67278. return this.onTrackpadValuesChangedObservable;
  67279. },
  67280. enumerable: true,
  67281. configurable: true
  67282. });
  67283. /**
  67284. * Called once per frame by the engine.
  67285. */
  67286. WindowsMotionController.prototype.update = function () {
  67287. _super.prototype.update.call(this);
  67288. if (this.browserGamepad.axes) {
  67289. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  67290. this.trackpad.x = this.browserGamepad["axes"][2];
  67291. this.trackpad.y = this.browserGamepad["axes"][3];
  67292. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  67293. }
  67294. // Only need to animate axes if there is a loaded mesh
  67295. if (this._loadedMeshInfo) {
  67296. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  67297. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  67298. }
  67299. }
  67300. }
  67301. };
  67302. /**
  67303. * Called once for each button that changed state since the last frame
  67304. * @param buttonIdx Which button index changed
  67305. * @param state New state of the button
  67306. * @param changes Which properties on the state changed since last frame
  67307. */
  67308. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67309. var buttonName = this._mapping.buttons[buttonIdx];
  67310. if (!buttonName) {
  67311. return;
  67312. }
  67313. // Only emit events for buttons that we know how to map from index to name
  67314. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  67315. if (observable) {
  67316. observable.notifyObservers(state);
  67317. }
  67318. this.lerpButtonTransform(buttonName, state.value);
  67319. };
  67320. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  67321. // If there is no loaded mesh, there is nothing to transform.
  67322. if (!this._loadedMeshInfo) {
  67323. return;
  67324. }
  67325. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  67326. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  67327. return;
  67328. }
  67329. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  67330. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  67331. };
  67332. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  67333. if (!this._loadedMeshInfo) {
  67334. return;
  67335. }
  67336. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  67337. if (!meshInfo) {
  67338. return;
  67339. }
  67340. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  67341. return;
  67342. }
  67343. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  67344. var lerpValue = axisValue * 0.5 + 0.5;
  67345. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  67346. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  67347. };
  67348. /**
  67349. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  67350. * @param scene scene in which to add meshes
  67351. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  67352. */
  67353. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  67354. var _this = this;
  67355. if (forceDefault === void 0) { forceDefault = false; }
  67356. var path;
  67357. var filename;
  67358. // Checking if GLB loader is present
  67359. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  67360. // Determine the device specific folder based on the ID suffix
  67361. var device = 'default';
  67362. if (this.id && !forceDefault) {
  67363. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  67364. device = ((match && match[0]) || device);
  67365. }
  67366. // Hand
  67367. if (this.hand === 'left') {
  67368. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  67369. }
  67370. else {
  67371. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  67372. }
  67373. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  67374. }
  67375. else {
  67376. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  67377. path = BABYLON.GenericController.MODEL_BASE_URL;
  67378. filename = BABYLON.GenericController.MODEL_FILENAME;
  67379. }
  67380. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  67381. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  67382. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  67383. if (!_this._loadedMeshInfo) {
  67384. return;
  67385. }
  67386. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  67387. _this.attachToMesh(_this._defaultModel);
  67388. if (meshLoaded) {
  67389. meshLoaded(_this._defaultModel);
  67390. }
  67391. }, null, function (scene, message) {
  67392. BABYLON.Tools.Log(message);
  67393. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  67394. if (!forceDefault) {
  67395. _this.initControllerMesh(scene, meshLoaded, true);
  67396. }
  67397. });
  67398. };
  67399. /**
  67400. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  67401. * can be transformed by button presses and axes values, based on this._mapping.
  67402. *
  67403. * @param scene scene in which the meshes exist
  67404. * @param meshes list of meshes that make up the controller model to process
  67405. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  67406. */
  67407. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  67408. var loadedMeshInfo = null;
  67409. // Create a new mesh to contain the glTF hierarchy
  67410. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  67411. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  67412. var childMesh = null;
  67413. for (var i = 0; i < meshes.length; i++) {
  67414. var mesh = meshes[i];
  67415. if (!mesh.parent) {
  67416. // Exclude controller meshes from picking results
  67417. mesh.isPickable = false;
  67418. // Handle root node, attach to the new parentMesh
  67419. childMesh = mesh;
  67420. break;
  67421. }
  67422. }
  67423. if (childMesh) {
  67424. childMesh.setParent(parentMesh);
  67425. // Create our mesh info. Note that this method will always return non-null.
  67426. loadedMeshInfo = this.createMeshInfo(parentMesh);
  67427. }
  67428. else {
  67429. BABYLON.Tools.Warn('Could not find root node in model file.');
  67430. }
  67431. return loadedMeshInfo;
  67432. };
  67433. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  67434. var loadedMeshInfo = new LoadedMeshInfo();
  67435. var i;
  67436. loadedMeshInfo.rootNode = rootNode;
  67437. // Reset the caches
  67438. loadedMeshInfo.buttonMeshes = {};
  67439. loadedMeshInfo.axisMeshes = {};
  67440. // Button Meshes
  67441. for (i = 0; i < this._mapping.buttons.length; i++) {
  67442. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  67443. if (!buttonMeshName) {
  67444. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  67445. continue;
  67446. }
  67447. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  67448. if (!buttonMesh) {
  67449. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  67450. continue;
  67451. }
  67452. var buttonMeshInfo = {
  67453. index: i,
  67454. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  67455. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  67456. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  67457. };
  67458. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  67459. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  67460. }
  67461. else {
  67462. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  67463. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  67464. '(VALUE: ' + !!buttonMeshInfo.value +
  67465. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  67466. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  67467. ')');
  67468. }
  67469. }
  67470. // Axis Meshes
  67471. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  67472. var axisMeshName = this._mapping.axisMeshNames[i];
  67473. if (!axisMeshName) {
  67474. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  67475. continue;
  67476. }
  67477. var axisMesh = getChildByName(rootNode, axisMeshName);
  67478. if (!axisMesh) {
  67479. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  67480. continue;
  67481. }
  67482. var axisMeshInfo = {
  67483. index: i,
  67484. value: getImmediateChildByName(axisMesh, 'VALUE'),
  67485. min: getImmediateChildByName(axisMesh, 'MIN'),
  67486. max: getImmediateChildByName(axisMesh, 'MAX')
  67487. };
  67488. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  67489. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  67490. }
  67491. else {
  67492. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  67493. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  67494. '(VALUE: ' + !!axisMeshInfo.value +
  67495. ', MIN: ' + !!axisMeshInfo.min +
  67496. ', MAX:' + !!axisMeshInfo.max +
  67497. ')');
  67498. }
  67499. }
  67500. // Pointing Ray
  67501. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  67502. if (!loadedMeshInfo.pointingPoseNode) {
  67503. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  67504. }
  67505. return loadedMeshInfo;
  67506. // Look through all children recursively. This will return null if no mesh exists with the given name.
  67507. function getChildByName(node, name) {
  67508. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  67509. }
  67510. // Look through only immediate children. This will return null if no mesh exists with the given name.
  67511. function getImmediateChildByName(node, name) {
  67512. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  67513. }
  67514. };
  67515. WindowsMotionController.prototype.getForwardRay = function (length) {
  67516. if (length === void 0) { length = 100; }
  67517. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  67518. return _super.prototype.getForwardRay.call(this, length);
  67519. }
  67520. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  67521. var origin = m.getTranslation();
  67522. var forward = new BABYLON.Vector3(0, 0, -1);
  67523. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  67524. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  67525. return new BABYLON.Ray(origin, direction, length);
  67526. };
  67527. WindowsMotionController.prototype.dispose = function () {
  67528. _super.prototype.dispose.call(this);
  67529. this.onTrackpadChangedObservable.clear();
  67530. };
  67531. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  67532. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  67533. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  67534. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  67535. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  67536. return WindowsMotionController;
  67537. }(BABYLON.WebVRController));
  67538. BABYLON.WindowsMotionController = WindowsMotionController;
  67539. })(BABYLON || (BABYLON = {}));
  67540. //# sourceMappingURL=babylon.windowsMotionController.js.map
  67541. "use strict";
  67542. var BABYLON;
  67543. (function (BABYLON) {
  67544. var GearVRController = /** @class */ (function (_super) {
  67545. __extends(GearVRController, _super);
  67546. function GearVRController(vrGamepad) {
  67547. var _this = _super.call(this, vrGamepad) || this;
  67548. _this._buttonIndexToObservableNameMap = [
  67549. 'onTrackpadChangedObservable',
  67550. 'onTriggerStateChangedObservable' // Trigger
  67551. ];
  67552. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  67553. return _this;
  67554. }
  67555. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  67556. var _this = this;
  67557. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  67558. _this._defaultModel = newMeshes[1];
  67559. _this.attachToMesh(_this._defaultModel);
  67560. if (meshLoaded) {
  67561. meshLoaded(_this._defaultModel);
  67562. }
  67563. });
  67564. };
  67565. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67566. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  67567. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  67568. // Only emit events for buttons that we know how to map from index to observable
  67569. var observable = this[observableName];
  67570. if (observable) {
  67571. observable.notifyObservers(state);
  67572. }
  67573. }
  67574. };
  67575. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  67576. GearVRController.MODEL_FILENAME = 'generic.babylon';
  67577. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  67578. return GearVRController;
  67579. }(BABYLON.WebVRController));
  67580. BABYLON.GearVRController = GearVRController;
  67581. })(BABYLON || (BABYLON = {}));
  67582. //# sourceMappingURL=babylon.gearVRController.js.map
  67583. "use strict";
  67584. var BABYLON;
  67585. (function (BABYLON) {
  67586. /**
  67587. * Google Daydream controller
  67588. */
  67589. var DaydreamController = /** @class */ (function (_super) {
  67590. __extends(DaydreamController, _super);
  67591. function DaydreamController(vrGamepad) {
  67592. var _this = _super.call(this, vrGamepad) || this;
  67593. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  67594. return _this;
  67595. }
  67596. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  67597. var _this = this;
  67598. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  67599. _this._defaultModel = newMeshes[1];
  67600. _this.attachToMesh(_this._defaultModel);
  67601. if (meshLoaded) {
  67602. meshLoaded(_this._defaultModel);
  67603. }
  67604. });
  67605. };
  67606. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67607. // Daydream controller only has 1 GamepadButton (on the trackpad).
  67608. if (buttonIdx === 0) {
  67609. var observable = this.onTriggerStateChangedObservable;
  67610. if (observable) {
  67611. observable.notifyObservers(state);
  67612. }
  67613. }
  67614. else {
  67615. // If the app or home buttons are ever made available
  67616. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  67617. }
  67618. };
  67619. /**
  67620. * Base Url for the controller model.
  67621. */
  67622. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  67623. /**
  67624. * File name for the controller model.
  67625. */
  67626. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  67627. /**
  67628. * Gamepad Id prefix used to identify Daydream Controller.
  67629. */
  67630. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  67631. return DaydreamController;
  67632. }(BABYLON.WebVRController));
  67633. BABYLON.DaydreamController = DaydreamController;
  67634. })(BABYLON || (BABYLON = {}));
  67635. //# sourceMappingURL=babylon.daydreamController.js.map
  67636. "use strict";
  67637. var BABYLON;
  67638. (function (BABYLON) {
  67639. var FollowCamera = /** @class */ (function (_super) {
  67640. __extends(FollowCamera, _super);
  67641. function FollowCamera(name, position, scene, lockedTarget) {
  67642. if (lockedTarget === void 0) { lockedTarget = null; }
  67643. var _this = _super.call(this, name, position, scene) || this;
  67644. _this.radius = 12;
  67645. _this.rotationOffset = 0;
  67646. _this.heightOffset = 4;
  67647. _this.cameraAcceleration = 0.05;
  67648. _this.maxCameraSpeed = 20;
  67649. _this.lockedTarget = lockedTarget;
  67650. return _this;
  67651. }
  67652. FollowCamera.prototype.getRadians = function (degrees) {
  67653. return degrees * Math.PI / 180;
  67654. };
  67655. FollowCamera.prototype.follow = function (cameraTarget) {
  67656. if (!cameraTarget)
  67657. return;
  67658. var yRotation;
  67659. if (cameraTarget.rotationQuaternion) {
  67660. var rotMatrix = new BABYLON.Matrix();
  67661. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  67662. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  67663. }
  67664. else {
  67665. yRotation = cameraTarget.rotation.y;
  67666. }
  67667. var radians = this.getRadians(this.rotationOffset) + yRotation;
  67668. var targetPosition = cameraTarget.getAbsolutePosition();
  67669. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  67670. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  67671. var dx = targetX - this.position.x;
  67672. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  67673. var dz = (targetZ) - this.position.z;
  67674. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  67675. var vy = dy * this.cameraAcceleration;
  67676. var vz = dz * this.cameraAcceleration * 2;
  67677. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  67678. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67679. }
  67680. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  67681. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67682. }
  67683. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  67684. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67685. }
  67686. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  67687. this.setTarget(targetPosition);
  67688. };
  67689. FollowCamera.prototype._checkInputs = function () {
  67690. _super.prototype._checkInputs.call(this);
  67691. if (this.lockedTarget) {
  67692. this.follow(this.lockedTarget);
  67693. }
  67694. };
  67695. FollowCamera.prototype.getClassName = function () {
  67696. return "FollowCamera";
  67697. };
  67698. __decorate([
  67699. BABYLON.serialize()
  67700. ], FollowCamera.prototype, "radius", void 0);
  67701. __decorate([
  67702. BABYLON.serialize()
  67703. ], FollowCamera.prototype, "rotationOffset", void 0);
  67704. __decorate([
  67705. BABYLON.serialize()
  67706. ], FollowCamera.prototype, "heightOffset", void 0);
  67707. __decorate([
  67708. BABYLON.serialize()
  67709. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  67710. __decorate([
  67711. BABYLON.serialize()
  67712. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  67713. __decorate([
  67714. BABYLON.serializeAsMeshReference("lockedTargetId")
  67715. ], FollowCamera.prototype, "lockedTarget", void 0);
  67716. return FollowCamera;
  67717. }(BABYLON.TargetCamera));
  67718. BABYLON.FollowCamera = FollowCamera;
  67719. var ArcFollowCamera = /** @class */ (function (_super) {
  67720. __extends(ArcFollowCamera, _super);
  67721. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  67722. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  67723. _this.alpha = alpha;
  67724. _this.beta = beta;
  67725. _this.radius = radius;
  67726. _this.target = target;
  67727. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  67728. _this.follow();
  67729. return _this;
  67730. }
  67731. ArcFollowCamera.prototype.follow = function () {
  67732. if (!this.target) {
  67733. return;
  67734. }
  67735. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  67736. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  67737. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  67738. var targetPosition = this.target.getAbsolutePosition();
  67739. this.position = targetPosition.add(this._cartesianCoordinates);
  67740. this.setTarget(targetPosition);
  67741. };
  67742. ArcFollowCamera.prototype._checkInputs = function () {
  67743. _super.prototype._checkInputs.call(this);
  67744. this.follow();
  67745. };
  67746. ArcFollowCamera.prototype.getClassName = function () {
  67747. return "ArcFollowCamera";
  67748. };
  67749. return ArcFollowCamera;
  67750. }(BABYLON.TargetCamera));
  67751. BABYLON.ArcFollowCamera = ArcFollowCamera;
  67752. })(BABYLON || (BABYLON = {}));
  67753. //# sourceMappingURL=babylon.followCamera.js.map
  67754. "use strict";
  67755. var BABYLON;
  67756. (function (BABYLON) {
  67757. // We're mainly based on the logic defined into the FreeCamera code
  67758. var UniversalCamera = /** @class */ (function (_super) {
  67759. __extends(UniversalCamera, _super);
  67760. //-- end properties for backward compatibility for inputs
  67761. function UniversalCamera(name, position, scene) {
  67762. var _this = _super.call(this, name, position, scene) || this;
  67763. _this.inputs.addGamepad();
  67764. return _this;
  67765. }
  67766. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  67767. //-- Begin properties for backward compatibility for inputs
  67768. get: function () {
  67769. var gamepad = this.inputs.attached["gamepad"];
  67770. if (gamepad)
  67771. return gamepad.gamepadAngularSensibility;
  67772. return 0;
  67773. },
  67774. set: function (value) {
  67775. var gamepad = this.inputs.attached["gamepad"];
  67776. if (gamepad)
  67777. gamepad.gamepadAngularSensibility = value;
  67778. },
  67779. enumerable: true,
  67780. configurable: true
  67781. });
  67782. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  67783. get: function () {
  67784. var gamepad = this.inputs.attached["gamepad"];
  67785. if (gamepad)
  67786. return gamepad.gamepadMoveSensibility;
  67787. return 0;
  67788. },
  67789. set: function (value) {
  67790. var gamepad = this.inputs.attached["gamepad"];
  67791. if (gamepad)
  67792. gamepad.gamepadMoveSensibility = value;
  67793. },
  67794. enumerable: true,
  67795. configurable: true
  67796. });
  67797. UniversalCamera.prototype.getClassName = function () {
  67798. return "UniversalCamera";
  67799. };
  67800. return UniversalCamera;
  67801. }(BABYLON.TouchCamera));
  67802. BABYLON.UniversalCamera = UniversalCamera;
  67803. })(BABYLON || (BABYLON = {}));
  67804. //# sourceMappingURL=babylon.universalCamera.js.map
  67805. "use strict";
  67806. var BABYLON;
  67807. (function (BABYLON) {
  67808. // We're mainly based on the logic defined into the FreeCamera code
  67809. var GamepadCamera = /** @class */ (function (_super) {
  67810. __extends(GamepadCamera, _super);
  67811. //-- end properties for backward compatibility for inputs
  67812. function GamepadCamera(name, position, scene) {
  67813. return _super.call(this, name, position, scene) || this;
  67814. }
  67815. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  67816. //-- Begin properties for backward compatibility for inputs
  67817. get: function () {
  67818. var gamepad = this.inputs.attached["gamepad"];
  67819. if (gamepad)
  67820. return gamepad.gamepadAngularSensibility;
  67821. return 0;
  67822. },
  67823. set: function (value) {
  67824. var gamepad = this.inputs.attached["gamepad"];
  67825. if (gamepad)
  67826. gamepad.gamepadAngularSensibility = value;
  67827. },
  67828. enumerable: true,
  67829. configurable: true
  67830. });
  67831. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  67832. get: function () {
  67833. var gamepad = this.inputs.attached["gamepad"];
  67834. if (gamepad)
  67835. return gamepad.gamepadMoveSensibility;
  67836. return 0;
  67837. },
  67838. set: function (value) {
  67839. var gamepad = this.inputs.attached["gamepad"];
  67840. if (gamepad)
  67841. gamepad.gamepadMoveSensibility = value;
  67842. },
  67843. enumerable: true,
  67844. configurable: true
  67845. });
  67846. GamepadCamera.prototype.getClassName = function () {
  67847. return "GamepadCamera";
  67848. };
  67849. return GamepadCamera;
  67850. }(BABYLON.UniversalCamera));
  67851. BABYLON.GamepadCamera = GamepadCamera;
  67852. })(BABYLON || (BABYLON = {}));
  67853. //# sourceMappingURL=babylon.gamepadCamera.js.map
  67854. "use strict";
  67855. var BABYLON;
  67856. (function (BABYLON) {
  67857. var PostProcessRenderPipelineManager = /** @class */ (function () {
  67858. function PostProcessRenderPipelineManager() {
  67859. this._renderPipelines = {};
  67860. }
  67861. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  67862. this._renderPipelines[renderPipeline._name] = renderPipeline;
  67863. };
  67864. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  67865. if (unique === void 0) { unique = false; }
  67866. var renderPipeline = this._renderPipelines[renderPipelineName];
  67867. if (!renderPipeline) {
  67868. return;
  67869. }
  67870. renderPipeline._attachCameras(cameras, unique);
  67871. };
  67872. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  67873. var renderPipeline = this._renderPipelines[renderPipelineName];
  67874. if (!renderPipeline) {
  67875. return;
  67876. }
  67877. renderPipeline._detachCameras(cameras);
  67878. };
  67879. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  67880. var renderPipeline = this._renderPipelines[renderPipelineName];
  67881. if (!renderPipeline) {
  67882. return;
  67883. }
  67884. renderPipeline._enableEffect(renderEffectName, cameras);
  67885. };
  67886. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  67887. var renderPipeline = this._renderPipelines[renderPipelineName];
  67888. if (!renderPipeline) {
  67889. return;
  67890. }
  67891. renderPipeline._disableEffect(renderEffectName, cameras);
  67892. };
  67893. PostProcessRenderPipelineManager.prototype.update = function () {
  67894. for (var renderPipelineName in this._renderPipelines) {
  67895. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67896. var pipeline = this._renderPipelines[renderPipelineName];
  67897. if (!pipeline.isSupported) {
  67898. pipeline.dispose();
  67899. delete this._renderPipelines[renderPipelineName];
  67900. }
  67901. else {
  67902. pipeline._update();
  67903. }
  67904. }
  67905. }
  67906. };
  67907. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  67908. for (var renderPipelineName in this._renderPipelines) {
  67909. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67910. var pipeline = this._renderPipelines[renderPipelineName];
  67911. pipeline._rebuild();
  67912. }
  67913. }
  67914. };
  67915. PostProcessRenderPipelineManager.prototype.dispose = function () {
  67916. for (var renderPipelineName in this._renderPipelines) {
  67917. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67918. var pipeline = this._renderPipelines[renderPipelineName];
  67919. pipeline.dispose();
  67920. }
  67921. }
  67922. };
  67923. return PostProcessRenderPipelineManager;
  67924. }());
  67925. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  67926. })(BABYLON || (BABYLON = {}));
  67927. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  67928. "use strict";
  67929. var BABYLON;
  67930. (function (BABYLON) {
  67931. /**
  67932. * This represents a set of one or more post processes in Babylon.
  67933. * A post process can be used to apply a shader to a texture after it is rendered.
  67934. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  67935. */
  67936. var PostProcessRenderEffect = /** @class */ (function () {
  67937. /**
  67938. * Instantiates a post process render effect.
  67939. * A post process can be used to apply a shader to a texture after it is rendered.
  67940. * @param engine The engine the effect is tied to
  67941. * @param name The name of the effect
  67942. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  67943. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  67944. */
  67945. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  67946. this._name = name;
  67947. this._singleInstance = singleInstance || true;
  67948. this._getPostProcesses = getPostProcesses;
  67949. this._cameras = {};
  67950. this._indicesForCamera = {};
  67951. this._postProcesses = {};
  67952. }
  67953. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  67954. /**
  67955. * Checks if all the post processes in the effect are supported.
  67956. */
  67957. get: function () {
  67958. for (var index in this._postProcesses) {
  67959. for (var ppIndex in this._postProcesses[index]) {
  67960. if (!this._postProcesses[index][ppIndex].isSupported) {
  67961. return false;
  67962. }
  67963. }
  67964. }
  67965. return true;
  67966. },
  67967. enumerable: true,
  67968. configurable: true
  67969. });
  67970. /**
  67971. * Updates the current state of the effect
  67972. */
  67973. PostProcessRenderEffect.prototype._update = function () {
  67974. };
  67975. /**
  67976. * Attaches the effect on cameras
  67977. * @param cameras The camera to attach to.
  67978. */
  67979. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  67980. var _this = this;
  67981. var cameraKey;
  67982. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67983. if (!cams) {
  67984. return;
  67985. }
  67986. for (var i = 0; i < cams.length; i++) {
  67987. var camera = cams[i];
  67988. var cameraName = camera.name;
  67989. if (this._singleInstance) {
  67990. cameraKey = 0;
  67991. }
  67992. else {
  67993. cameraKey = cameraName;
  67994. }
  67995. if (!this._postProcesses[cameraKey]) {
  67996. var postProcess = this._getPostProcesses();
  67997. if (postProcess) {
  67998. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  67999. }
  68000. }
  68001. if (!this._indicesForCamera[cameraName]) {
  68002. this._indicesForCamera[cameraName] = [];
  68003. }
  68004. this._postProcesses[cameraKey].forEach(function (postProcess) {
  68005. var index = camera.attachPostProcess(postProcess);
  68006. _this._indicesForCamera[cameraName].push(index);
  68007. });
  68008. if (!this._cameras[cameraName]) {
  68009. this._cameras[cameraName] = camera;
  68010. }
  68011. }
  68012. };
  68013. /**
  68014. * Detatches the effect on cameras
  68015. * @param cameras The camera to detatch from.
  68016. */
  68017. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  68018. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  68019. if (!cams) {
  68020. return;
  68021. }
  68022. for (var i = 0; i < cams.length; i++) {
  68023. var camera = cams[i];
  68024. var cameraName = camera.name;
  68025. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  68026. camera.detachPostProcess(postProcess);
  68027. });
  68028. if (this._cameras[cameraName]) {
  68029. //this._indicesForCamera.splice(index, 1);
  68030. this._cameras[cameraName] = null;
  68031. }
  68032. }
  68033. };
  68034. /**
  68035. * Enables the effect on given cameras
  68036. * @param cameras The camera to enable.
  68037. */
  68038. PostProcessRenderEffect.prototype._enable = function (cameras) {
  68039. var _this = this;
  68040. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  68041. if (!cams) {
  68042. return;
  68043. }
  68044. for (var i = 0; i < cams.length; i++) {
  68045. var camera = cams[i];
  68046. var cameraName = camera.name;
  68047. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  68048. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  68049. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  68050. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  68051. });
  68052. }
  68053. }
  68054. }
  68055. };
  68056. /**
  68057. * Disables the effect on the given cameras
  68058. * @param cameras The camera to disable.
  68059. */
  68060. PostProcessRenderEffect.prototype._disable = function (cameras) {
  68061. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  68062. if (!cams) {
  68063. return;
  68064. }
  68065. for (var i = 0; i < cams.length; i++) {
  68066. var camera = cams[i];
  68067. var cameraName = camera.name;
  68068. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  68069. camera.detachPostProcess(postProcess);
  68070. });
  68071. }
  68072. };
  68073. /**
  68074. * Gets a list of the post processes contained in the effect.
  68075. * @param camera The camera to get the post processes on.
  68076. * @returns The list of the post processes in the effect.
  68077. */
  68078. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  68079. if (this._singleInstance) {
  68080. return this._postProcesses[0];
  68081. }
  68082. else {
  68083. if (!camera) {
  68084. return null;
  68085. }
  68086. return this._postProcesses[camera.name];
  68087. }
  68088. };
  68089. return PostProcessRenderEffect;
  68090. }());
  68091. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  68092. })(BABYLON || (BABYLON = {}));
  68093. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  68094. "use strict";
  68095. var BABYLON;
  68096. (function (BABYLON) {
  68097. var PostProcessRenderPipeline = /** @class */ (function () {
  68098. function PostProcessRenderPipeline(engine, name) {
  68099. this.engine = engine;
  68100. this._name = name;
  68101. this._renderEffects = {};
  68102. this._renderEffectsForIsolatedPass = new Array();
  68103. this._cameras = [];
  68104. }
  68105. PostProcessRenderPipeline.prototype.getClassName = function () {
  68106. return "PostProcessRenderPipeline";
  68107. };
  68108. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  68109. get: function () {
  68110. for (var renderEffectName in this._renderEffects) {
  68111. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  68112. if (!this._renderEffects[renderEffectName].isSupported) {
  68113. return false;
  68114. }
  68115. }
  68116. }
  68117. return true;
  68118. },
  68119. enumerable: true,
  68120. configurable: true
  68121. });
  68122. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  68123. this._renderEffects[renderEffect._name] = renderEffect;
  68124. };
  68125. // private
  68126. PostProcessRenderPipeline.prototype._rebuild = function () {
  68127. };
  68128. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  68129. var renderEffects = this._renderEffects[renderEffectName];
  68130. if (!renderEffects) {
  68131. return;
  68132. }
  68133. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  68134. };
  68135. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  68136. var renderEffects = this._renderEffects[renderEffectName];
  68137. if (!renderEffects) {
  68138. return;
  68139. }
  68140. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  68141. };
  68142. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  68143. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  68144. if (!cams) {
  68145. return;
  68146. }
  68147. var indicesToDelete = [];
  68148. var i;
  68149. for (i = 0; i < cams.length; i++) {
  68150. var camera = cams[i];
  68151. var cameraName = camera.name;
  68152. if (this._cameras.indexOf(camera) === -1) {
  68153. this._cameras[cameraName] = camera;
  68154. }
  68155. else if (unique) {
  68156. indicesToDelete.push(i);
  68157. }
  68158. }
  68159. for (i = 0; i < indicesToDelete.length; i++) {
  68160. cameras.splice(indicesToDelete[i], 1);
  68161. }
  68162. for (var renderEffectName in this._renderEffects) {
  68163. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  68164. this._renderEffects[renderEffectName]._attachCameras(cams);
  68165. }
  68166. }
  68167. };
  68168. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  68169. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  68170. if (!cams) {
  68171. return;
  68172. }
  68173. for (var renderEffectName in this._renderEffects) {
  68174. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  68175. this._renderEffects[renderEffectName]._detachCameras(cams);
  68176. }
  68177. }
  68178. for (var i = 0; i < cams.length; i++) {
  68179. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  68180. }
  68181. };
  68182. PostProcessRenderPipeline.prototype._update = function () {
  68183. for (var renderEffectName in this._renderEffects) {
  68184. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  68185. this._renderEffects[renderEffectName]._update();
  68186. }
  68187. }
  68188. for (var i = 0; i < this._cameras.length; i++) {
  68189. var cameraName = this._cameras[i].name;
  68190. if (this._renderEffectsForIsolatedPass[cameraName]) {
  68191. this._renderEffectsForIsolatedPass[cameraName]._update();
  68192. }
  68193. }
  68194. };
  68195. PostProcessRenderPipeline.prototype._reset = function () {
  68196. this._renderEffects = {};
  68197. this._renderEffectsForIsolatedPass = new Array();
  68198. };
  68199. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  68200. // 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)
  68201. var effectKeys = Object.keys(this._renderEffects);
  68202. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  68203. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  68204. if (postProcesses) {
  68205. postProcesses[0].samples = sampleCount;
  68206. return true;
  68207. }
  68208. }
  68209. return false;
  68210. };
  68211. PostProcessRenderPipeline.prototype.dispose = function () {
  68212. // Must be implemented by children
  68213. };
  68214. __decorate([
  68215. BABYLON.serialize()
  68216. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  68217. return PostProcessRenderPipeline;
  68218. }());
  68219. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  68220. })(BABYLON || (BABYLON = {}));
  68221. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  68222. "use strict";
  68223. var BABYLON;
  68224. (function (BABYLON) {
  68225. /**
  68226. * This represents a depth renderer in Babylon.
  68227. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  68228. */
  68229. var DepthRenderer = /** @class */ (function () {
  68230. /**
  68231. * Instantiates a depth renderer
  68232. * @param scene The scene the renderer belongs to
  68233. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  68234. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  68235. */
  68236. function DepthRenderer(scene, type, camera) {
  68237. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  68238. if (camera === void 0) { camera = null; }
  68239. var _this = this;
  68240. this._scene = scene;
  68241. this._camera = camera;
  68242. var engine = scene.getEngine();
  68243. // Render target
  68244. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  68245. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68246. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68247. this._depthMap.refreshRate = 1;
  68248. this._depthMap.renderParticles = false;
  68249. this._depthMap.renderList = null;
  68250. // Camera to get depth map from to support multiple concurrent cameras
  68251. this._depthMap.activeCamera = this._camera;
  68252. this._depthMap.ignoreCameraViewport = true;
  68253. this._depthMap.useCameraPostProcesses = false;
  68254. // set default depth value to 1.0 (far away)
  68255. this._depthMap.onClearObservable.add(function (engine) {
  68256. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  68257. });
  68258. // Custom render function
  68259. var renderSubMesh = function (subMesh) {
  68260. var mesh = subMesh.getRenderingMesh();
  68261. var scene = _this._scene;
  68262. var engine = scene.getEngine();
  68263. var material = subMesh.getMaterial();
  68264. if (!material) {
  68265. return;
  68266. }
  68267. // Culling and reverse (right handed system)
  68268. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  68269. // Managing instances
  68270. var batch = mesh._getInstancesRenderList(subMesh._id);
  68271. if (batch.mustReturn) {
  68272. return;
  68273. }
  68274. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  68275. var camera = _this._camera || scene.activeCamera;
  68276. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  68277. engine.enableEffect(_this._effect);
  68278. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  68279. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  68280. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  68281. // Alpha test
  68282. if (material && material.needAlphaTesting()) {
  68283. var alphaTexture = material.getAlphaTestTexture();
  68284. if (alphaTexture) {
  68285. _this._effect.setTexture("diffuseSampler", alphaTexture);
  68286. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  68287. }
  68288. }
  68289. // Bones
  68290. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  68291. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  68292. }
  68293. // Draw
  68294. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  68295. }
  68296. };
  68297. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  68298. var index;
  68299. if (depthOnlySubMeshes.length) {
  68300. engine.setColorWrite(false);
  68301. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  68302. renderSubMesh(depthOnlySubMeshes.data[index]);
  68303. }
  68304. engine.setColorWrite(true);
  68305. }
  68306. for (index = 0; index < opaqueSubMeshes.length; index++) {
  68307. renderSubMesh(opaqueSubMeshes.data[index]);
  68308. }
  68309. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  68310. renderSubMesh(alphaTestSubMeshes.data[index]);
  68311. }
  68312. };
  68313. }
  68314. /**
  68315. * Creates the depth rendering effect and checks if the effect is ready.
  68316. * @param subMesh The submesh to be used to render the depth map of
  68317. * @param useInstances If multiple world instances should be used
  68318. * @returns if the depth renderer is ready to render the depth map
  68319. */
  68320. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  68321. var material = subMesh.getMaterial();
  68322. if (material.disableDepthWrite) {
  68323. return false;
  68324. }
  68325. var defines = [];
  68326. var attribs = [BABYLON.VertexBuffer.PositionKind];
  68327. var mesh = subMesh.getMesh();
  68328. // Alpha test
  68329. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  68330. defines.push("#define ALPHATEST");
  68331. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68332. attribs.push(BABYLON.VertexBuffer.UVKind);
  68333. defines.push("#define UV1");
  68334. }
  68335. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  68336. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  68337. defines.push("#define UV2");
  68338. }
  68339. }
  68340. // Bones
  68341. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68342. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  68343. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  68344. if (mesh.numBoneInfluencers > 4) {
  68345. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  68346. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  68347. }
  68348. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68349. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  68350. }
  68351. else {
  68352. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68353. }
  68354. // Instances
  68355. if (useInstances) {
  68356. defines.push("#define INSTANCES");
  68357. attribs.push("world0");
  68358. attribs.push("world1");
  68359. attribs.push("world2");
  68360. attribs.push("world3");
  68361. }
  68362. // Get correct effect
  68363. var join = defines.join("\n");
  68364. if (this._cachedDefines !== join) {
  68365. this._cachedDefines = join;
  68366. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  68367. }
  68368. return this._effect.isReady();
  68369. };
  68370. /**
  68371. * Gets the texture which the depth map will be written to.
  68372. * @returns The depth map texture
  68373. */
  68374. DepthRenderer.prototype.getDepthMap = function () {
  68375. return this._depthMap;
  68376. };
  68377. /**
  68378. * Disposes of the depth renderer.
  68379. */
  68380. DepthRenderer.prototype.dispose = function () {
  68381. this._depthMap.dispose();
  68382. };
  68383. return DepthRenderer;
  68384. }());
  68385. BABYLON.DepthRenderer = DepthRenderer;
  68386. })(BABYLON || (BABYLON = {}));
  68387. //# sourceMappingURL=babylon.depthRenderer.js.map
  68388. "use strict";
  68389. var BABYLON;
  68390. (function (BABYLON) {
  68391. var SSAORenderingPipeline = /** @class */ (function (_super) {
  68392. __extends(SSAORenderingPipeline, _super);
  68393. /**
  68394. * @constructor
  68395. * @param {string} name - The rendering pipeline name
  68396. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68397. * @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 }
  68398. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68399. */
  68400. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  68401. var _this = _super.call(this, scene.getEngine(), name) || this;
  68402. // Members
  68403. /**
  68404. * The PassPostProcess id in the pipeline that contains the original scene color
  68405. */
  68406. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  68407. /**
  68408. * The SSAO PostProcess id in the pipeline
  68409. */
  68410. _this.SSAORenderEffect = "SSAORenderEffect";
  68411. /**
  68412. * The horizontal blur PostProcess id in the pipeline
  68413. */
  68414. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  68415. /**
  68416. * The vertical blur PostProcess id in the pipeline
  68417. */
  68418. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  68419. /**
  68420. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  68421. */
  68422. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  68423. /**
  68424. * The output strength of the SSAO post-process. Default value is 1.0.
  68425. */
  68426. _this.totalStrength = 1.0;
  68427. /**
  68428. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  68429. */
  68430. _this.radius = 0.0001;
  68431. /**
  68432. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  68433. * Must not be equal to fallOff and superior to fallOff.
  68434. * Default value is 0.975
  68435. */
  68436. _this.area = 0.0075;
  68437. /**
  68438. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  68439. * Must not be equal to area and inferior to area.
  68440. * Default value is 0.0
  68441. */
  68442. _this.fallOff = 0.000001;
  68443. /**
  68444. * The base color of the SSAO post-process
  68445. * The final result is "base + ssao" between [0, 1]
  68446. */
  68447. _this.base = 0.5;
  68448. _this._firstUpdate = true;
  68449. _this._scene = scene;
  68450. // Set up assets
  68451. _this._createRandomTexture();
  68452. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  68453. var ssaoRatio = ratio.ssaoRatio || ratio;
  68454. var combineRatio = ratio.combineRatio || ratio;
  68455. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  68456. _this._createSSAOPostProcess(ssaoRatio);
  68457. _this._createBlurPostProcess(ssaoRatio);
  68458. _this._createSSAOCombinePostProcess(combineRatio);
  68459. // Set up pipeline
  68460. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  68461. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  68462. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  68463. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  68464. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  68465. // Finish
  68466. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68467. if (cameras)
  68468. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  68469. return _this;
  68470. }
  68471. // Public Methods
  68472. /**
  68473. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  68474. */
  68475. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  68476. if (disableDepthRender === void 0) { disableDepthRender = false; }
  68477. for (var i = 0; i < this._scene.cameras.length; i++) {
  68478. var camera = this._scene.cameras[i];
  68479. this._originalColorPostProcess.dispose(camera);
  68480. this._ssaoPostProcess.dispose(camera);
  68481. this._blurHPostProcess.dispose(camera);
  68482. this._blurVPostProcess.dispose(camera);
  68483. this._ssaoCombinePostProcess.dispose(camera);
  68484. }
  68485. this._randomTexture.dispose();
  68486. if (disableDepthRender)
  68487. this._scene.disableDepthRenderer();
  68488. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  68489. _super.prototype.dispose.call(this);
  68490. };
  68491. // Private Methods
  68492. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  68493. var _this = this;
  68494. var size = 16;
  68495. 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);
  68496. 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);
  68497. this._blurHPostProcess.onActivateObservable.add(function () {
  68498. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  68499. _this._blurHPostProcess.kernel = size * dw;
  68500. });
  68501. this._blurVPostProcess.onActivateObservable.add(function () {
  68502. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  68503. _this._blurVPostProcess.kernel = size * dw;
  68504. });
  68505. };
  68506. SSAORenderingPipeline.prototype._rebuild = function () {
  68507. this._firstUpdate = true;
  68508. _super.prototype._rebuild.call(this);
  68509. };
  68510. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  68511. var _this = this;
  68512. var numSamples = 16;
  68513. var sampleSphere = [
  68514. 0.5381, 0.1856, -0.4319,
  68515. 0.1379, 0.2486, 0.4430,
  68516. 0.3371, 0.5679, -0.0057,
  68517. -0.6999, -0.0451, -0.0019,
  68518. 0.0689, -0.1598, -0.8547,
  68519. 0.0560, 0.0069, -0.1843,
  68520. -0.0146, 0.1402, 0.0762,
  68521. 0.0100, -0.1924, -0.0344,
  68522. -0.3577, -0.5301, -0.4358,
  68523. -0.3169, 0.1063, 0.0158,
  68524. 0.0103, -0.5869, 0.0046,
  68525. -0.0897, -0.4940, 0.3287,
  68526. 0.7119, -0.0154, -0.0918,
  68527. -0.0533, 0.0596, -0.5411,
  68528. 0.0352, -0.0631, 0.5460,
  68529. -0.4776, 0.2847, -0.0271
  68530. ];
  68531. var samplesFactor = 1.0 / numSamples;
  68532. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  68533. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  68534. "area", "fallOff", "base", "range", "viewport"
  68535. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  68536. this._ssaoPostProcess.onApply = function (effect) {
  68537. if (_this._firstUpdate) {
  68538. effect.setArray3("sampleSphere", sampleSphere);
  68539. effect.setFloat("samplesFactor", samplesFactor);
  68540. effect.setFloat("randTextureTiles", 4.0);
  68541. }
  68542. effect.setFloat("totalStrength", _this.totalStrength);
  68543. effect.setFloat("radius", _this.radius);
  68544. effect.setFloat("area", _this.area);
  68545. effect.setFloat("fallOff", _this.fallOff);
  68546. effect.setFloat("base", _this.base);
  68547. effect.setTexture("textureSampler", _this._depthTexture);
  68548. effect.setTexture("randomSampler", _this._randomTexture);
  68549. };
  68550. };
  68551. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  68552. var _this = this;
  68553. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68554. this._ssaoCombinePostProcess.onApply = function (effect) {
  68555. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  68556. };
  68557. };
  68558. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  68559. var size = 512;
  68560. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  68561. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68562. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68563. var context = this._randomTexture.getContext();
  68564. var rand = function (min, max) {
  68565. return Math.random() * (max - min) + min;
  68566. };
  68567. var randVector = BABYLON.Vector3.Zero();
  68568. for (var x = 0; x < size; x++) {
  68569. for (var y = 0; y < size; y++) {
  68570. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  68571. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  68572. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  68573. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  68574. context.fillRect(x, y, 1, 1);
  68575. }
  68576. }
  68577. this._randomTexture.update(false);
  68578. };
  68579. __decorate([
  68580. BABYLON.serialize()
  68581. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  68582. __decorate([
  68583. BABYLON.serialize()
  68584. ], SSAORenderingPipeline.prototype, "radius", void 0);
  68585. __decorate([
  68586. BABYLON.serialize()
  68587. ], SSAORenderingPipeline.prototype, "area", void 0);
  68588. __decorate([
  68589. BABYLON.serialize()
  68590. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  68591. __decorate([
  68592. BABYLON.serialize()
  68593. ], SSAORenderingPipeline.prototype, "base", void 0);
  68594. return SSAORenderingPipeline;
  68595. }(BABYLON.PostProcessRenderPipeline));
  68596. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  68597. })(BABYLON || (BABYLON = {}));
  68598. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  68599. "use strict";
  68600. var BABYLON;
  68601. (function (BABYLON) {
  68602. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  68603. __extends(SSAO2RenderingPipeline, _super);
  68604. /**
  68605. * @constructor
  68606. * @param {string} name - The rendering pipeline name
  68607. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68608. * @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 }
  68609. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68610. */
  68611. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  68612. var _this = _super.call(this, scene.getEngine(), name) || this;
  68613. // Members
  68614. /**
  68615. * The PassPostProcess id in the pipeline that contains the original scene color
  68616. */
  68617. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  68618. /**
  68619. * The SSAO PostProcess id in the pipeline
  68620. */
  68621. _this.SSAORenderEffect = "SSAORenderEffect";
  68622. /**
  68623. * The horizontal blur PostProcess id in the pipeline
  68624. */
  68625. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  68626. /**
  68627. * The vertical blur PostProcess id in the pipeline
  68628. */
  68629. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  68630. /**
  68631. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  68632. */
  68633. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  68634. /**
  68635. * The output strength of the SSAO post-process. Default value is 1.0.
  68636. */
  68637. _this.totalStrength = 1.0;
  68638. /**
  68639. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  68640. */
  68641. _this.maxZ = 100.0;
  68642. /**
  68643. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  68644. */
  68645. _this.minZAspect = 0.2;
  68646. /**
  68647. * Number of samples used for the SSAO calculations. Default value is 8
  68648. */
  68649. _this._samples = 8;
  68650. /**
  68651. * Are we using bilateral blur ?
  68652. */
  68653. _this._expensiveBlur = true;
  68654. /**
  68655. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  68656. */
  68657. _this.radius = 2.0;
  68658. /**
  68659. * The base color of the SSAO post-process
  68660. * The final result is "base + ssao" between [0, 1]
  68661. */
  68662. _this.base = 0.1;
  68663. _this._firstUpdate = true;
  68664. _this._scene = scene;
  68665. if (!_this.isSupported) {
  68666. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  68667. return _this;
  68668. }
  68669. var ssaoRatio = ratio.ssaoRatio || ratio;
  68670. var blurRatio = ratio.blurRatio || ratio;
  68671. // Set up assets
  68672. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  68673. _this._createRandomTexture();
  68674. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  68675. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  68676. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  68677. _this._createSSAOPostProcess(1.0);
  68678. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  68679. _this._createSSAOCombinePostProcess(blurRatio);
  68680. // Set up pipeline
  68681. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  68682. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  68683. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  68684. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  68685. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  68686. // Finish
  68687. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68688. if (cameras)
  68689. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  68690. return _this;
  68691. }
  68692. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  68693. get: function () {
  68694. return this._samples;
  68695. },
  68696. set: function (n) {
  68697. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  68698. this._samples = n;
  68699. this._sampleSphere = this._generateHemisphere();
  68700. this._firstUpdate = true;
  68701. },
  68702. enumerable: true,
  68703. configurable: true
  68704. });
  68705. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  68706. get: function () {
  68707. return this._expensiveBlur;
  68708. },
  68709. set: function (b) {
  68710. 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"]);
  68711. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  68712. this._expensiveBlur = b;
  68713. this._firstUpdate = true;
  68714. },
  68715. enumerable: true,
  68716. configurable: true
  68717. });
  68718. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  68719. /**
  68720. * Support test.
  68721. */
  68722. get: function () {
  68723. var engine = BABYLON.Engine.LastCreatedEngine;
  68724. if (!engine) {
  68725. return false;
  68726. }
  68727. return engine.getCaps().drawBuffersExtension;
  68728. },
  68729. enumerable: true,
  68730. configurable: true
  68731. });
  68732. // Public Methods
  68733. /**
  68734. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  68735. */
  68736. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  68737. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  68738. for (var i = 0; i < this._scene.cameras.length; i++) {
  68739. var camera = this._scene.cameras[i];
  68740. this._originalColorPostProcess.dispose(camera);
  68741. this._ssaoPostProcess.dispose(camera);
  68742. this._blurHPostProcess.dispose(camera);
  68743. this._blurVPostProcess.dispose(camera);
  68744. this._ssaoCombinePostProcess.dispose(camera);
  68745. }
  68746. this._randomTexture.dispose();
  68747. if (disableGeometryBufferRenderer)
  68748. this._scene.disableGeometryBufferRenderer();
  68749. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  68750. _super.prototype.dispose.call(this);
  68751. };
  68752. // Private Methods
  68753. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  68754. var _this = this;
  68755. this._samplerOffsets = [];
  68756. var expensive = this.expensiveBlur;
  68757. for (var i = -8; i < 8; i++) {
  68758. this._samplerOffsets.push(i * 2 + 0.5);
  68759. }
  68760. 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");
  68761. this._blurHPostProcess.onApply = function (effect) {
  68762. if (!_this._scene.activeCamera) {
  68763. return;
  68764. }
  68765. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  68766. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68767. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68768. effect.setFloat("radius", _this.radius);
  68769. effect.setTexture("depthSampler", _this._depthTexture);
  68770. if (_this._firstUpdate) {
  68771. effect.setArray("samplerOffsets", _this._samplerOffsets);
  68772. }
  68773. };
  68774. 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");
  68775. this._blurVPostProcess.onApply = function (effect) {
  68776. if (!_this._scene.activeCamera) {
  68777. return;
  68778. }
  68779. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  68780. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68781. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68782. effect.setFloat("radius", _this.radius);
  68783. effect.setTexture("depthSampler", _this._depthTexture);
  68784. if (_this._firstUpdate) {
  68785. effect.setArray("samplerOffsets", _this._samplerOffsets);
  68786. _this._firstUpdate = false;
  68787. }
  68788. };
  68789. };
  68790. SSAO2RenderingPipeline.prototype._rebuild = function () {
  68791. this._firstUpdate = true;
  68792. _super.prototype._rebuild.call(this);
  68793. };
  68794. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  68795. var numSamples = this.samples;
  68796. var result = [];
  68797. var vector, scale;
  68798. var rand = function (min, max) {
  68799. return Math.random() * (max - min) + min;
  68800. };
  68801. var i = 0;
  68802. while (i < numSamples) {
  68803. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  68804. vector.normalize();
  68805. scale = i / numSamples;
  68806. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  68807. vector.scaleInPlace(scale);
  68808. result.push(vector.x, vector.y, vector.z);
  68809. i++;
  68810. }
  68811. return result;
  68812. };
  68813. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  68814. var _this = this;
  68815. var numSamples = this.samples;
  68816. this._sampleSphere = this._generateHemisphere();
  68817. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  68818. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  68819. "base", "range", "projection", "near", "far", "texelSize",
  68820. "xViewport", "yViewport", "maxZ", "minZAspect"
  68821. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  68822. this._ssaoPostProcess.onApply = function (effect) {
  68823. if (_this._firstUpdate) {
  68824. effect.setArray3("sampleSphere", _this._sampleSphere);
  68825. effect.setFloat("randTextureTiles", 4.0);
  68826. }
  68827. if (!_this._scene.activeCamera) {
  68828. return;
  68829. }
  68830. effect.setFloat("samplesFactor", 1 / _this.samples);
  68831. effect.setFloat("totalStrength", _this.totalStrength);
  68832. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  68833. effect.setFloat("radius", _this.radius);
  68834. effect.setFloat("maxZ", _this.maxZ);
  68835. effect.setFloat("minZAspect", _this.minZAspect);
  68836. effect.setFloat("base", _this.base);
  68837. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68838. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68839. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  68840. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  68841. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  68842. effect.setTexture("textureSampler", _this._depthTexture);
  68843. effect.setTexture("normalSampler", _this._normalTexture);
  68844. effect.setTexture("randomSampler", _this._randomTexture);
  68845. };
  68846. };
  68847. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  68848. var _this = this;
  68849. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68850. this._ssaoCombinePostProcess.onApply = function (effect) {
  68851. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  68852. };
  68853. };
  68854. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  68855. var size = 512;
  68856. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  68857. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68858. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68859. var context = this._randomTexture.getContext();
  68860. var rand = function (min, max) {
  68861. return Math.random() * (max - min) + min;
  68862. };
  68863. var randVector = BABYLON.Vector3.Zero();
  68864. for (var x = 0; x < size; x++) {
  68865. for (var y = 0; y < size; y++) {
  68866. randVector.x = rand(0.0, 1.0);
  68867. randVector.y = rand(0.0, 1.0);
  68868. randVector.z = 0.0;
  68869. randVector.normalize();
  68870. randVector.scaleInPlace(255);
  68871. randVector.x = Math.floor(randVector.x);
  68872. randVector.y = Math.floor(randVector.y);
  68873. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  68874. context.fillRect(x, y, 1, 1);
  68875. }
  68876. }
  68877. this._randomTexture.update(false);
  68878. };
  68879. __decorate([
  68880. BABYLON.serialize()
  68881. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  68882. __decorate([
  68883. BABYLON.serialize()
  68884. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  68885. __decorate([
  68886. BABYLON.serialize()
  68887. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  68888. __decorate([
  68889. BABYLON.serialize("samples")
  68890. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  68891. __decorate([
  68892. BABYLON.serialize("expensiveBlur")
  68893. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  68894. __decorate([
  68895. BABYLON.serialize()
  68896. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  68897. __decorate([
  68898. BABYLON.serialize()
  68899. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  68900. return SSAO2RenderingPipeline;
  68901. }(BABYLON.PostProcessRenderPipeline));
  68902. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  68903. })(BABYLON || (BABYLON = {}));
  68904. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  68905. "use strict";
  68906. // BABYLON.JS Chromatic Aberration GLSL Shader
  68907. // Author: Olivier Guyot
  68908. // Separates very slightly R, G and B colors on the edges of the screen
  68909. // Inspired by Francois Tarlier & Martins Upitis
  68910. var BABYLON;
  68911. (function (BABYLON) {
  68912. var LensRenderingPipeline = /** @class */ (function (_super) {
  68913. __extends(LensRenderingPipeline, _super);
  68914. /**
  68915. * @constructor
  68916. *
  68917. * Effect parameters are as follow:
  68918. * {
  68919. * chromatic_aberration: number; // from 0 to x (1 for realism)
  68920. * edge_blur: number; // from 0 to x (1 for realism)
  68921. * distortion: number; // from 0 to x (1 for realism)
  68922. * grain_amount: number; // from 0 to 1
  68923. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  68924. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  68925. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  68926. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  68927. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  68928. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  68929. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  68930. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  68931. * }
  68932. * Note: if an effect parameter is unset, effect is disabled
  68933. *
  68934. * @param {string} name - The rendering pipeline name
  68935. * @param {object} parameters - An object containing all parameters (see above)
  68936. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68937. * @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)
  68938. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68939. */
  68940. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  68941. if (ratio === void 0) { ratio = 1.0; }
  68942. var _this = _super.call(this, scene.getEngine(), name) || this;
  68943. // Lens effects can be of the following:
  68944. // - chromatic aberration (slight shift of RGB colors)
  68945. // - blur on the edge of the lens
  68946. // - lens distortion
  68947. // - depth-of-field blur & highlights enhancing
  68948. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  68949. // - grain effect (noise or custom texture)
  68950. // Two additional texture samplers are needed:
  68951. // - depth map (for depth-of-field)
  68952. // - grain texture
  68953. /**
  68954. * The chromatic aberration PostProcess id in the pipeline
  68955. */
  68956. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  68957. /**
  68958. * The highlights enhancing PostProcess id in the pipeline
  68959. */
  68960. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  68961. /**
  68962. * The depth-of-field PostProcess id in the pipeline
  68963. */
  68964. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  68965. _this._scene = scene;
  68966. // Fetch texture samplers
  68967. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  68968. if (parameters.grain_texture) {
  68969. _this._grainTexture = parameters.grain_texture;
  68970. }
  68971. else {
  68972. _this._createGrainTexture();
  68973. }
  68974. // save parameters
  68975. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  68976. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  68977. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  68978. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  68979. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  68980. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  68981. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  68982. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  68983. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  68984. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  68985. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  68986. // Create effects
  68987. _this._createChromaticAberrationPostProcess(ratio);
  68988. _this._createHighlightsPostProcess(ratio);
  68989. _this._createDepthOfFieldPostProcess(ratio / 4);
  68990. // Set up pipeline
  68991. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  68992. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  68993. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  68994. if (_this._highlightsGain === -1) {
  68995. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  68996. }
  68997. // Finish
  68998. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68999. if (cameras) {
  69000. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  69001. }
  69002. return _this;
  69003. }
  69004. // public methods (self explanatory)
  69005. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  69006. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  69007. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  69008. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  69009. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  69010. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  69011. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  69012. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  69013. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  69014. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  69015. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  69016. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  69017. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  69018. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  69019. };
  69020. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  69021. this._highlightsPostProcess.updateEffect();
  69022. };
  69023. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  69024. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  69025. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  69026. this._highlightsGain = amount;
  69027. };
  69028. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  69029. if (this._highlightsGain === -1) {
  69030. this._highlightsGain = 1.0;
  69031. }
  69032. this._highlightsThreshold = amount;
  69033. };
  69034. LensRenderingPipeline.prototype.disableHighlights = function () {
  69035. this._highlightsGain = -1;
  69036. };
  69037. /**
  69038. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  69039. */
  69040. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  69041. if (disableDepthRender === void 0) { disableDepthRender = false; }
  69042. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  69043. this._chromaticAberrationPostProcess = null;
  69044. this._highlightsPostProcess = null;
  69045. this._depthOfFieldPostProcess = null;
  69046. this._grainTexture.dispose();
  69047. if (disableDepthRender)
  69048. this._scene.disableDepthRenderer();
  69049. };
  69050. // colors shifting and distortion
  69051. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  69052. var _this = this;
  69053. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  69054. [], // samplers
  69055. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  69056. this._chromaticAberrationPostProcess.onApply = function (effect) {
  69057. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  69058. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  69059. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  69060. effect.setFloat('radialIntensity', 1);
  69061. effect.setFloat2('direction', 17, 17);
  69062. effect.setFloat2('centerPosition', 0.5, 0.5);
  69063. };
  69064. };
  69065. // highlights enhancing
  69066. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  69067. var _this = this;
  69068. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  69069. [], // samplers
  69070. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  69071. this._highlightsPostProcess.onApply = function (effect) {
  69072. effect.setFloat('gain', _this._highlightsGain);
  69073. effect.setFloat('threshold', _this._highlightsThreshold);
  69074. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  69075. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  69076. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  69077. };
  69078. };
  69079. // colors shifting and distortion
  69080. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  69081. var _this = this;
  69082. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  69083. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  69084. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  69085. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  69086. this._depthOfFieldPostProcess.onApply = function (effect) {
  69087. effect.setTexture("depthSampler", _this._depthTexture);
  69088. effect.setTexture("grainSampler", _this._grainTexture);
  69089. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  69090. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  69091. effect.setFloat('grain_amount', _this._grainAmount);
  69092. effect.setBool('blur_noise', _this._blurNoise);
  69093. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  69094. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  69095. effect.setFloat('distortion', _this._distortion);
  69096. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  69097. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  69098. effect.setFloat('aperture', _this._dofAperture);
  69099. effect.setFloat('darken', _this._dofDarken);
  69100. effect.setFloat('edge_blur', _this._edgeBlur);
  69101. effect.setBool('highlights', (_this._highlightsGain !== -1));
  69102. if (_this._scene.activeCamera) {
  69103. effect.setFloat('near', _this._scene.activeCamera.minZ);
  69104. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  69105. }
  69106. };
  69107. };
  69108. // creates a black and white random noise texture, 512x512
  69109. LensRenderingPipeline.prototype._createGrainTexture = function () {
  69110. var size = 512;
  69111. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  69112. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  69113. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  69114. var context = this._grainTexture.getContext();
  69115. var rand = function (min, max) {
  69116. return Math.random() * (max - min) + min;
  69117. };
  69118. var value;
  69119. for (var x = 0; x < size; x++) {
  69120. for (var y = 0; y < size; y++) {
  69121. value = Math.floor(rand(0.42, 0.58) * 255);
  69122. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  69123. context.fillRect(x, y, 1, 1);
  69124. }
  69125. }
  69126. this._grainTexture.update(false);
  69127. };
  69128. return LensRenderingPipeline;
  69129. }(BABYLON.PostProcessRenderPipeline));
  69130. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  69131. })(BABYLON || (BABYLON = {}));
  69132. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  69133. "use strict";
  69134. var BABYLON;
  69135. (function (BABYLON) {
  69136. var StandardRenderingPipeline = /** @class */ (function (_super) {
  69137. __extends(StandardRenderingPipeline, _super);
  69138. /**
  69139. * @constructor
  69140. * @param {string} name - The rendering pipeline name
  69141. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  69142. * @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)
  69143. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  69144. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  69145. */
  69146. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  69147. if (originalPostProcess === void 0) { originalPostProcess = null; }
  69148. var _this = _super.call(this, scene.getEngine(), name) || this;
  69149. _this.downSampleX4PostProcess = null;
  69150. _this.brightPassPostProcess = null;
  69151. _this.blurHPostProcesses = [];
  69152. _this.blurVPostProcesses = [];
  69153. _this.textureAdderPostProcess = null;
  69154. _this.volumetricLightPostProcess = null;
  69155. _this.volumetricLightSmoothXPostProcess = null;
  69156. _this.volumetricLightSmoothYPostProcess = null;
  69157. _this.volumetricLightMergePostProces = null;
  69158. _this.volumetricLightFinalPostProcess = null;
  69159. _this.luminancePostProcess = null;
  69160. _this.luminanceDownSamplePostProcesses = [];
  69161. _this.hdrPostProcess = null;
  69162. _this.textureAdderFinalPostProcess = null;
  69163. _this.lensFlareFinalPostProcess = null;
  69164. _this.hdrFinalPostProcess = null;
  69165. _this.lensFlarePostProcess = null;
  69166. _this.lensFlareComposePostProcess = null;
  69167. _this.motionBlurPostProcess = null;
  69168. _this.depthOfFieldPostProcess = null;
  69169. // Values
  69170. _this.brightThreshold = 1.0;
  69171. _this.blurWidth = 512.0;
  69172. _this.horizontalBlur = false;
  69173. _this.exposure = 1.0;
  69174. _this.lensTexture = null;
  69175. _this.volumetricLightCoefficient = 0.2;
  69176. _this.volumetricLightPower = 4.0;
  69177. _this.volumetricLightBlurScale = 64.0;
  69178. _this.sourceLight = null;
  69179. _this.hdrMinimumLuminance = 1.0;
  69180. _this.hdrDecreaseRate = 0.5;
  69181. _this.hdrIncreaseRate = 0.5;
  69182. _this.lensColorTexture = null;
  69183. _this.lensFlareStrength = 20.0;
  69184. _this.lensFlareGhostDispersal = 1.4;
  69185. _this.lensFlareHaloWidth = 0.7;
  69186. _this.lensFlareDistortionStrength = 16.0;
  69187. _this.lensStarTexture = null;
  69188. _this.lensFlareDirtTexture = null;
  69189. _this.depthOfFieldDistance = 10.0;
  69190. _this.depthOfFieldBlurWidth = 64.0;
  69191. _this.motionStrength = 1.0;
  69192. // IAnimatable
  69193. _this.animations = [];
  69194. _this._currentDepthOfFieldSource = null;
  69195. _this._hdrCurrentLuminance = 1.0;
  69196. // Getters and setters
  69197. _this._bloomEnabled = true;
  69198. _this._depthOfFieldEnabled = false;
  69199. _this._vlsEnabled = false;
  69200. _this._lensFlareEnabled = false;
  69201. _this._hdrEnabled = false;
  69202. _this._motionBlurEnabled = false;
  69203. _this._motionBlurSamples = 64.0;
  69204. _this._volumetricLightStepsCount = 50.0;
  69205. _this._cameras = cameras || [];
  69206. // Initialize
  69207. _this._scene = scene;
  69208. _this._basePostProcess = originalPostProcess;
  69209. _this._ratio = ratio;
  69210. // Misc
  69211. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  69212. // Finish
  69213. scene.postProcessRenderPipelineManager.addPipeline(_this);
  69214. _this._buildPipeline();
  69215. return _this;
  69216. }
  69217. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  69218. get: function () {
  69219. return this._bloomEnabled;
  69220. },
  69221. set: function (enabled) {
  69222. if (this._bloomEnabled === enabled) {
  69223. return;
  69224. }
  69225. this._bloomEnabled = enabled;
  69226. this._buildPipeline();
  69227. },
  69228. enumerable: true,
  69229. configurable: true
  69230. });
  69231. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  69232. get: function () {
  69233. return this._depthOfFieldEnabled;
  69234. },
  69235. set: function (enabled) {
  69236. if (this._depthOfFieldEnabled === enabled) {
  69237. return;
  69238. }
  69239. this._depthOfFieldEnabled = enabled;
  69240. this._buildPipeline();
  69241. },
  69242. enumerable: true,
  69243. configurable: true
  69244. });
  69245. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  69246. get: function () {
  69247. return this._lensFlareEnabled;
  69248. },
  69249. set: function (enabled) {
  69250. if (this._lensFlareEnabled === enabled) {
  69251. return;
  69252. }
  69253. this._lensFlareEnabled = enabled;
  69254. this._buildPipeline();
  69255. },
  69256. enumerable: true,
  69257. configurable: true
  69258. });
  69259. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  69260. get: function () {
  69261. return this._hdrEnabled;
  69262. },
  69263. set: function (enabled) {
  69264. if (this._hdrEnabled === enabled) {
  69265. return;
  69266. }
  69267. this._hdrEnabled = enabled;
  69268. this._buildPipeline();
  69269. },
  69270. enumerable: true,
  69271. configurable: true
  69272. });
  69273. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  69274. get: function () {
  69275. return this._vlsEnabled;
  69276. },
  69277. set: function (enabled) {
  69278. if (this._vlsEnabled === enabled) {
  69279. return;
  69280. }
  69281. if (enabled) {
  69282. var geometry = this._scene.enableGeometryBufferRenderer();
  69283. if (!geometry) {
  69284. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  69285. return;
  69286. }
  69287. }
  69288. this._vlsEnabled = enabled;
  69289. this._buildPipeline();
  69290. },
  69291. enumerable: true,
  69292. configurable: true
  69293. });
  69294. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  69295. get: function () {
  69296. return this._motionBlurEnabled;
  69297. },
  69298. set: function (enabled) {
  69299. if (this._motionBlurEnabled === enabled) {
  69300. return;
  69301. }
  69302. this._motionBlurEnabled = enabled;
  69303. this._buildPipeline();
  69304. },
  69305. enumerable: true,
  69306. configurable: true
  69307. });
  69308. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  69309. get: function () {
  69310. return this._volumetricLightStepsCount;
  69311. },
  69312. set: function (count) {
  69313. if (this.volumetricLightPostProcess) {
  69314. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  69315. }
  69316. this._volumetricLightStepsCount = count;
  69317. },
  69318. enumerable: true,
  69319. configurable: true
  69320. });
  69321. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  69322. get: function () {
  69323. return this._motionBlurSamples;
  69324. },
  69325. set: function (samples) {
  69326. if (this.motionBlurPostProcess) {
  69327. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  69328. }
  69329. this._motionBlurSamples = samples;
  69330. },
  69331. enumerable: true,
  69332. configurable: true
  69333. });
  69334. StandardRenderingPipeline.prototype._buildPipeline = function () {
  69335. var _this = this;
  69336. var ratio = this._ratio;
  69337. var scene = this._scene;
  69338. this._disposePostProcesses();
  69339. this._reset();
  69340. // Create pass post-process
  69341. if (!this._basePostProcess) {
  69342. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  69343. this.originalPostProcess.onApply = function (effect) {
  69344. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  69345. };
  69346. }
  69347. else {
  69348. this.originalPostProcess = this._basePostProcess;
  69349. }
  69350. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  69351. this._currentDepthOfFieldSource = this.originalPostProcess;
  69352. if (this._vlsEnabled) {
  69353. // Create volumetric light
  69354. this._createVolumetricLightPostProcess(scene, ratio);
  69355. // Create volumetric light final post-process
  69356. 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);
  69357. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  69358. }
  69359. if (this._bloomEnabled) {
  69360. // Create down sample X4 post-process
  69361. this._createDownSampleX4PostProcess(scene, ratio / 2);
  69362. // Create bright pass post-process
  69363. this._createBrightPassPostProcess(scene, ratio / 2);
  69364. // Create gaussian blur post-processes (down sampling blurs)
  69365. this._createBlurPostProcesses(scene, ratio / 4, 1);
  69366. // Create texture adder post-process
  69367. this._createTextureAdderPostProcess(scene, ratio);
  69368. // Create depth-of-field source post-process
  69369. 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);
  69370. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  69371. }
  69372. if (this._lensFlareEnabled) {
  69373. // Create lens flare post-process
  69374. this._createLensFlarePostProcess(scene, ratio);
  69375. // Create depth-of-field source post-process post lens-flare and disable it now
  69376. 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);
  69377. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  69378. }
  69379. if (this._hdrEnabled) {
  69380. // Create luminance
  69381. this._createLuminancePostProcesses(scene, this._floatTextureType);
  69382. // Create HDR
  69383. this._createHdrPostProcess(scene, ratio);
  69384. // Create depth-of-field source post-process post hdr and disable it now
  69385. 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);
  69386. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  69387. }
  69388. if (this._depthOfFieldEnabled) {
  69389. // Create gaussian blur used by depth-of-field
  69390. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  69391. // Create depth-of-field post-process
  69392. this._createDepthOfFieldPostProcess(scene, ratio);
  69393. }
  69394. if (this._motionBlurEnabled) {
  69395. // Create motion blur post-process
  69396. this._createMotionBlurPostProcess(scene, ratio);
  69397. }
  69398. if (this._cameras !== null) {
  69399. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  69400. }
  69401. };
  69402. // Down Sample X4 Post-Processs
  69403. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  69404. var _this = this;
  69405. var downSampleX4Offsets = new Array(32);
  69406. 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);
  69407. this.downSampleX4PostProcess.onApply = function (effect) {
  69408. var id = 0;
  69409. var width = _this.downSampleX4PostProcess.width;
  69410. var height = _this.downSampleX4PostProcess.height;
  69411. for (var i = -2; i < 2; i++) {
  69412. for (var j = -2; j < 2; j++) {
  69413. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  69414. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  69415. id += 2;
  69416. }
  69417. }
  69418. effect.setArray2("dsOffsets", downSampleX4Offsets);
  69419. };
  69420. // Add to pipeline
  69421. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  69422. };
  69423. // Brightpass Post-Process
  69424. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  69425. var _this = this;
  69426. var brightOffsets = new Array(8);
  69427. 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);
  69428. this.brightPassPostProcess.onApply = function (effect) {
  69429. var sU = (1.0 / _this.brightPassPostProcess.width);
  69430. var sV = (1.0 / _this.brightPassPostProcess.height);
  69431. brightOffsets[0] = -0.5 * sU;
  69432. brightOffsets[1] = 0.5 * sV;
  69433. brightOffsets[2] = 0.5 * sU;
  69434. brightOffsets[3] = 0.5 * sV;
  69435. brightOffsets[4] = -0.5 * sU;
  69436. brightOffsets[5] = -0.5 * sV;
  69437. brightOffsets[6] = 0.5 * sU;
  69438. brightOffsets[7] = -0.5 * sV;
  69439. effect.setArray2("dsOffsets", brightOffsets);
  69440. effect.setFloat("brightThreshold", _this.brightThreshold);
  69441. };
  69442. // Add to pipeline
  69443. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  69444. };
  69445. // Create blur H&V post-processes
  69446. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  69447. var _this = this;
  69448. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  69449. var engine = scene.getEngine();
  69450. 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);
  69451. 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);
  69452. blurX.onActivateObservable.add(function () {
  69453. var dw = blurX.width / engine.getRenderWidth();
  69454. blurX.kernel = _this[blurWidthKey] * dw;
  69455. });
  69456. blurY.onActivateObservable.add(function () {
  69457. var dw = blurY.height / engine.getRenderHeight();
  69458. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  69459. });
  69460. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  69461. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  69462. this.blurHPostProcesses.push(blurX);
  69463. this.blurVPostProcesses.push(blurY);
  69464. };
  69465. // Create texture adder post-process
  69466. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  69467. var _this = this;
  69468. 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);
  69469. this.textureAdderPostProcess.onApply = function (effect) {
  69470. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  69471. effect.setTexture("lensSampler", _this.lensTexture);
  69472. effect.setFloat("exposure", _this.exposure);
  69473. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  69474. };
  69475. // Add to pipeline
  69476. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  69477. };
  69478. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  69479. var _this = this;
  69480. var geometryRenderer = scene.enableGeometryBufferRenderer();
  69481. geometryRenderer.enablePosition = true;
  69482. var geometry = geometryRenderer.getGBuffer();
  69483. // Base post-process
  69484. 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));
  69485. var depthValues = BABYLON.Vector2.Zero();
  69486. this.volumetricLightPostProcess.onApply = function (effect) {
  69487. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  69488. var generator = _this.sourceLight.getShadowGenerator();
  69489. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  69490. effect.setTexture("positionSampler", geometry.textures[2]);
  69491. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  69492. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  69493. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  69494. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  69495. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  69496. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  69497. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  69498. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  69499. effect.setVector2("depthValues", depthValues);
  69500. }
  69501. };
  69502. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  69503. // Smooth
  69504. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  69505. // Merge
  69506. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  69507. this.volumetricLightMergePostProces.onApply = function (effect) {
  69508. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  69509. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  69510. };
  69511. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  69512. };
  69513. // Create luminance
  69514. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  69515. var _this = this;
  69516. // Create luminance
  69517. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  69518. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  69519. var offsets = [];
  69520. this.luminancePostProcess.onApply = function (effect) {
  69521. var sU = (1.0 / _this.luminancePostProcess.width);
  69522. var sV = (1.0 / _this.luminancePostProcess.height);
  69523. offsets[0] = -0.5 * sU;
  69524. offsets[1] = 0.5 * sV;
  69525. offsets[2] = 0.5 * sU;
  69526. offsets[3] = 0.5 * sV;
  69527. offsets[4] = -0.5 * sU;
  69528. offsets[5] = -0.5 * sV;
  69529. offsets[6] = 0.5 * sU;
  69530. offsets[7] = -0.5 * sV;
  69531. effect.setArray2("lumOffsets", offsets);
  69532. };
  69533. // Add to pipeline
  69534. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  69535. // Create down sample luminance
  69536. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  69537. var size = Math.pow(3, i);
  69538. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  69539. if (i === 0) {
  69540. defines += "#define FINAL_DOWN_SAMPLER";
  69541. }
  69542. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  69543. this.luminanceDownSamplePostProcesses.push(postProcess);
  69544. }
  69545. // Create callbacks and add effects
  69546. var lastLuminance = this.luminancePostProcess;
  69547. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  69548. var downSampleOffsets = new Array(18);
  69549. pp.onApply = function (effect) {
  69550. if (!lastLuminance) {
  69551. return;
  69552. }
  69553. var id = 0;
  69554. for (var x = -1; x < 2; x++) {
  69555. for (var y = -1; y < 2; y++) {
  69556. downSampleOffsets[id] = x / lastLuminance.width;
  69557. downSampleOffsets[id + 1] = y / lastLuminance.height;
  69558. id += 2;
  69559. }
  69560. }
  69561. effect.setArray2("dsOffsets", downSampleOffsets);
  69562. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  69563. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  69564. lastLuminance = _this.luminancePostProcess;
  69565. }
  69566. else {
  69567. lastLuminance = pp;
  69568. }
  69569. };
  69570. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  69571. pp.onAfterRender = function (effect) {
  69572. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  69573. 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);
  69574. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  69575. };
  69576. }
  69577. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  69578. });
  69579. };
  69580. // Create HDR post-process
  69581. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  69582. var _this = this;
  69583. 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);
  69584. var outputLiminance = 1;
  69585. var time = 0;
  69586. var lastTime = 0;
  69587. this.hdrPostProcess.onApply = function (effect) {
  69588. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  69589. time += scene.getEngine().getDeltaTime();
  69590. if (outputLiminance < 0) {
  69591. outputLiminance = _this._hdrCurrentLuminance;
  69592. }
  69593. else {
  69594. var dt = (lastTime - time) / 1000.0;
  69595. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  69596. outputLiminance += _this.hdrDecreaseRate * dt;
  69597. }
  69598. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  69599. outputLiminance -= _this.hdrIncreaseRate * dt;
  69600. }
  69601. else {
  69602. outputLiminance = _this._hdrCurrentLuminance;
  69603. }
  69604. }
  69605. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  69606. effect.setFloat("averageLuminance", outputLiminance);
  69607. lastTime = time;
  69608. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  69609. };
  69610. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  69611. };
  69612. // Create lens flare post-process
  69613. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  69614. var _this = this;
  69615. 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);
  69616. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  69617. this._createBlurPostProcesses(scene, ratio / 4, 2);
  69618. 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);
  69619. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  69620. var resolution = new BABYLON.Vector2(0, 0);
  69621. // Lens flare
  69622. this.lensFlarePostProcess.onApply = function (effect) {
  69623. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  69624. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  69625. effect.setFloat("strength", _this.lensFlareStrength);
  69626. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  69627. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  69628. // Shift
  69629. resolution.x = _this.lensFlarePostProcess.width;
  69630. resolution.y = _this.lensFlarePostProcess.height;
  69631. effect.setVector2("resolution", resolution);
  69632. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  69633. };
  69634. // Compose
  69635. 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);
  69636. 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);
  69637. this.lensFlareComposePostProcess.onApply = function (effect) {
  69638. if (!_this._scene.activeCamera) {
  69639. return;
  69640. }
  69641. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  69642. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  69643. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  69644. // Lens start rotation matrix
  69645. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  69646. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  69647. 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));
  69648. camRot *= 4.0;
  69649. 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);
  69650. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  69651. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  69652. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  69653. };
  69654. };
  69655. // Create depth-of-field post-process
  69656. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  69657. var _this = this;
  69658. 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);
  69659. this.depthOfFieldPostProcess.onApply = function (effect) {
  69660. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  69661. effect.setTexture("depthSampler", _this._getDepthTexture());
  69662. effect.setFloat("distance", _this.depthOfFieldDistance);
  69663. };
  69664. // Add to pipeline
  69665. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  69666. };
  69667. // Create motion blur post-process
  69668. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  69669. var _this = this;
  69670. 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);
  69671. var motionScale = 0;
  69672. var prevViewProjection = BABYLON.Matrix.Identity();
  69673. var invViewProjection = BABYLON.Matrix.Identity();
  69674. var viewProjection = BABYLON.Matrix.Identity();
  69675. var screenSize = BABYLON.Vector2.Zero();
  69676. this.motionBlurPostProcess.onApply = function (effect) {
  69677. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  69678. viewProjection.invertToRef(invViewProjection);
  69679. effect.setMatrix("inverseViewProjection", invViewProjection);
  69680. effect.setMatrix("prevViewProjection", prevViewProjection);
  69681. prevViewProjection = viewProjection;
  69682. screenSize.x = _this.motionBlurPostProcess.width;
  69683. screenSize.y = _this.motionBlurPostProcess.height;
  69684. effect.setVector2("screenSize", screenSize);
  69685. motionScale = scene.getEngine().getFps() / 60.0;
  69686. effect.setFloat("motionScale", motionScale);
  69687. effect.setFloat("motionStrength", _this.motionStrength);
  69688. effect.setTexture("depthSampler", _this._getDepthTexture());
  69689. };
  69690. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  69691. };
  69692. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  69693. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  69694. var renderer = this._scene.enableGeometryBufferRenderer();
  69695. return renderer.getGBuffer().textures[0];
  69696. }
  69697. return this._scene.enableDepthRenderer().getDepthMap();
  69698. };
  69699. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  69700. for (var i = 0; i < this._cameras.length; i++) {
  69701. var camera = this._cameras[i];
  69702. if (this.originalPostProcess) {
  69703. this.originalPostProcess.dispose(camera);
  69704. }
  69705. if (this.downSampleX4PostProcess) {
  69706. this.downSampleX4PostProcess.dispose(camera);
  69707. }
  69708. if (this.brightPassPostProcess) {
  69709. this.brightPassPostProcess.dispose(camera);
  69710. }
  69711. if (this.textureAdderPostProcess) {
  69712. this.textureAdderPostProcess.dispose(camera);
  69713. }
  69714. if (this.textureAdderFinalPostProcess) {
  69715. this.textureAdderFinalPostProcess.dispose(camera);
  69716. }
  69717. if (this.volumetricLightPostProcess) {
  69718. this.volumetricLightPostProcess.dispose(camera);
  69719. }
  69720. if (this.volumetricLightSmoothXPostProcess) {
  69721. this.volumetricLightSmoothXPostProcess.dispose(camera);
  69722. }
  69723. if (this.volumetricLightSmoothYPostProcess) {
  69724. this.volumetricLightSmoothYPostProcess.dispose(camera);
  69725. }
  69726. if (this.volumetricLightMergePostProces) {
  69727. this.volumetricLightMergePostProces.dispose(camera);
  69728. }
  69729. if (this.volumetricLightFinalPostProcess) {
  69730. this.volumetricLightFinalPostProcess.dispose(camera);
  69731. }
  69732. if (this.lensFlarePostProcess) {
  69733. this.lensFlarePostProcess.dispose(camera);
  69734. }
  69735. if (this.lensFlareComposePostProcess) {
  69736. this.lensFlareComposePostProcess.dispose(camera);
  69737. }
  69738. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  69739. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  69740. }
  69741. if (this.luminancePostProcess) {
  69742. this.luminancePostProcess.dispose(camera);
  69743. }
  69744. if (this.hdrPostProcess) {
  69745. this.hdrPostProcess.dispose(camera);
  69746. }
  69747. if (this.hdrFinalPostProcess) {
  69748. this.hdrFinalPostProcess.dispose(camera);
  69749. }
  69750. if (this.depthOfFieldPostProcess) {
  69751. this.depthOfFieldPostProcess.dispose(camera);
  69752. }
  69753. if (this.motionBlurPostProcess) {
  69754. this.motionBlurPostProcess.dispose(camera);
  69755. }
  69756. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  69757. this.blurHPostProcesses[j].dispose(camera);
  69758. }
  69759. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  69760. this.blurVPostProcesses[j].dispose(camera);
  69761. }
  69762. }
  69763. this.originalPostProcess = null;
  69764. this.downSampleX4PostProcess = null;
  69765. this.brightPassPostProcess = null;
  69766. this.textureAdderPostProcess = null;
  69767. this.textureAdderFinalPostProcess = null;
  69768. this.volumetricLightPostProcess = null;
  69769. this.volumetricLightSmoothXPostProcess = null;
  69770. this.volumetricLightSmoothYPostProcess = null;
  69771. this.volumetricLightMergePostProces = null;
  69772. this.volumetricLightFinalPostProcess = null;
  69773. this.lensFlarePostProcess = null;
  69774. this.lensFlareComposePostProcess = null;
  69775. this.luminancePostProcess = null;
  69776. this.hdrPostProcess = null;
  69777. this.hdrFinalPostProcess = null;
  69778. this.depthOfFieldPostProcess = null;
  69779. this.motionBlurPostProcess = null;
  69780. this.luminanceDownSamplePostProcesses = [];
  69781. this.blurHPostProcesses = [];
  69782. this.blurVPostProcesses = [];
  69783. };
  69784. // Dispose
  69785. StandardRenderingPipeline.prototype.dispose = function () {
  69786. this._disposePostProcesses();
  69787. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  69788. _super.prototype.dispose.call(this);
  69789. };
  69790. // Serialize rendering pipeline
  69791. StandardRenderingPipeline.prototype.serialize = function () {
  69792. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  69793. serializationObject.customType = "StandardRenderingPipeline";
  69794. return serializationObject;
  69795. };
  69796. /**
  69797. * Static members
  69798. */
  69799. // Parse serialized pipeline
  69800. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  69801. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  69802. };
  69803. // Luminance steps
  69804. StandardRenderingPipeline.LuminanceSteps = 6;
  69805. __decorate([
  69806. BABYLON.serialize()
  69807. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  69808. __decorate([
  69809. BABYLON.serialize()
  69810. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  69811. __decorate([
  69812. BABYLON.serialize()
  69813. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  69814. __decorate([
  69815. BABYLON.serialize()
  69816. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  69817. __decorate([
  69818. BABYLON.serializeAsTexture("lensTexture")
  69819. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  69820. __decorate([
  69821. BABYLON.serialize()
  69822. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  69823. __decorate([
  69824. BABYLON.serialize()
  69825. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  69826. __decorate([
  69827. BABYLON.serialize()
  69828. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  69829. __decorate([
  69830. BABYLON.serialize()
  69831. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  69832. __decorate([
  69833. BABYLON.serialize()
  69834. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  69835. __decorate([
  69836. BABYLON.serialize()
  69837. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  69838. __decorate([
  69839. BABYLON.serializeAsTexture("lensColorTexture")
  69840. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  69841. __decorate([
  69842. BABYLON.serialize()
  69843. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  69844. __decorate([
  69845. BABYLON.serialize()
  69846. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  69847. __decorate([
  69848. BABYLON.serialize()
  69849. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  69850. __decorate([
  69851. BABYLON.serialize()
  69852. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  69853. __decorate([
  69854. BABYLON.serializeAsTexture("lensStarTexture")
  69855. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  69856. __decorate([
  69857. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  69858. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  69859. __decorate([
  69860. BABYLON.serialize()
  69861. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  69862. __decorate([
  69863. BABYLON.serialize()
  69864. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  69865. __decorate([
  69866. BABYLON.serialize()
  69867. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  69868. __decorate([
  69869. BABYLON.serialize()
  69870. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  69871. __decorate([
  69872. BABYLON.serialize()
  69873. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  69874. __decorate([
  69875. BABYLON.serialize()
  69876. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  69877. __decorate([
  69878. BABYLON.serialize()
  69879. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  69880. __decorate([
  69881. BABYLON.serialize()
  69882. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  69883. __decorate([
  69884. BABYLON.serialize()
  69885. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  69886. __decorate([
  69887. BABYLON.serialize()
  69888. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  69889. __decorate([
  69890. BABYLON.serialize()
  69891. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  69892. __decorate([
  69893. BABYLON.serialize()
  69894. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  69895. return StandardRenderingPipeline;
  69896. }(BABYLON.PostProcessRenderPipeline));
  69897. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  69898. })(BABYLON || (BABYLON = {}));
  69899. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  69900. "use strict";
  69901. var BABYLON;
  69902. (function (BABYLON) {
  69903. var FxaaPostProcess = /** @class */ (function (_super) {
  69904. __extends(FxaaPostProcess, _super);
  69905. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  69906. if (camera === void 0) { camera = null; }
  69907. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69908. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  69909. _this.onApplyObservable.add(function (effect) {
  69910. var texelSize = _this.texelSize;
  69911. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  69912. });
  69913. return _this;
  69914. }
  69915. return FxaaPostProcess;
  69916. }(BABYLON.PostProcess));
  69917. BABYLON.FxaaPostProcess = FxaaPostProcess;
  69918. })(BABYLON || (BABYLON = {}));
  69919. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  69920. "use strict";
  69921. var BABYLON;
  69922. (function (BABYLON) {
  69923. /**
  69924. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  69925. */
  69926. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  69927. __extends(ChromaticAberrationPostProcess, _super);
  69928. /**
  69929. * Creates a new instance ChromaticAberrationPostProcess
  69930. * @param name The name of the effect.
  69931. * @param screenWidth The width of the screen to apply the effect on.
  69932. * @param screenHeight The height of the screen to apply the effect on.
  69933. * @param options The required width/height ratio to downsize to before computing the render pass.
  69934. * @param camera The camera to apply the render pass to.
  69935. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69936. * @param engine The engine which the post process will be applied. (default: current engine)
  69937. * @param reusable If the post process can be reused on the same frame. (default: false)
  69938. * @param textureType Type of textures used when performing the post process. (default: 0)
  69939. * @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)
  69940. */
  69941. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69942. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69943. if (blockCompilation === void 0) { blockCompilation = false; }
  69944. 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;
  69945. /**
  69946. * The amount of seperation of rgb channels (default: 30)
  69947. */
  69948. _this.aberrationAmount = 30;
  69949. /**
  69950. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  69951. */
  69952. _this.radialIntensity = 0;
  69953. /**
  69954. * 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))
  69955. */
  69956. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  69957. /**
  69958. * 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))
  69959. */
  69960. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  69961. _this.onApplyObservable.add(function (effect) {
  69962. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  69963. effect.setFloat('screen_width', screenWidth);
  69964. effect.setFloat('screen_height', screenHeight);
  69965. effect.setFloat('radialIntensity', _this.radialIntensity);
  69966. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  69967. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  69968. });
  69969. return _this;
  69970. }
  69971. return ChromaticAberrationPostProcess;
  69972. }(BABYLON.PostProcess));
  69973. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  69974. })(BABYLON || (BABYLON = {}));
  69975. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  69976. "use strict";
  69977. var BABYLON;
  69978. (function (BABYLON) {
  69979. /**
  69980. * The GrainPostProcess adds noise to the image at mid luminance levels
  69981. */
  69982. var GrainPostProcess = /** @class */ (function (_super) {
  69983. __extends(GrainPostProcess, _super);
  69984. /**
  69985. * Creates a new instance of @see GrainPostProcess
  69986. * @param name The name of the effect.
  69987. * @param options The required width/height ratio to downsize to before computing the render pass.
  69988. * @param camera The camera to apply the render pass to.
  69989. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69990. * @param engine The engine which the post process will be applied. (default: current engine)
  69991. * @param reusable If the post process can be reused on the same frame. (default: false)
  69992. * @param textureType Type of textures used when performing the post process. (default: 0)
  69993. * @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)
  69994. */
  69995. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69996. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69997. if (blockCompilation === void 0) { blockCompilation = false; }
  69998. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  69999. /**
  70000. * The intensity of the grain added (default: 30)
  70001. */
  70002. _this.intensity = 30;
  70003. /**
  70004. * If the grain should be randomized on every frame
  70005. */
  70006. _this.animated = false;
  70007. _this.onApplyObservable.add(function (effect) {
  70008. effect.setFloat('intensity', _this.intensity);
  70009. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  70010. });
  70011. return _this;
  70012. }
  70013. return GrainPostProcess;
  70014. }(BABYLON.PostProcess));
  70015. BABYLON.GrainPostProcess = GrainPostProcess;
  70016. })(BABYLON || (BABYLON = {}));
  70017. //# sourceMappingURL=babylon.grainPostProcess.js.map
  70018. "use strict";
  70019. var BABYLON;
  70020. (function (BABYLON) {
  70021. /**
  70022. * The SharpenPostProcess applies a sharpen kernel to every pixel
  70023. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  70024. */
  70025. var SharpenPostProcess = /** @class */ (function (_super) {
  70026. __extends(SharpenPostProcess, _super);
  70027. /**
  70028. * Creates a new instance ConvolutionPostProcess
  70029. * @param name The name of the effect.
  70030. * @param options The required width/height ratio to downsize to before computing the render pass.
  70031. * @param camera The camera to apply the render pass to.
  70032. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70033. * @param engine The engine which the post process will be applied. (default: current engine)
  70034. * @param reusable If the post process can be reused on the same frame. (default: false)
  70035. * @param textureType Type of textures used when performing the post process. (default: 0)
  70036. * @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)
  70037. */
  70038. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70039. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70040. if (blockCompilation === void 0) { blockCompilation = false; }
  70041. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  70042. /**
  70043. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  70044. */
  70045. _this.colorAmount = 1.0;
  70046. /**
  70047. * How much sharpness should be applied (default: 0.3)
  70048. */
  70049. _this.edgeAmount = 0.3;
  70050. _this.onApply = function (effect) {
  70051. effect.setFloat2("screenSize", _this.width, _this.height);
  70052. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  70053. };
  70054. return _this;
  70055. }
  70056. return SharpenPostProcess;
  70057. }(BABYLON.PostProcess));
  70058. BABYLON.SharpenPostProcess = SharpenPostProcess;
  70059. })(BABYLON || (BABYLON = {}));
  70060. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  70061. "use strict";
  70062. var BABYLON;
  70063. (function (BABYLON) {
  70064. /**
  70065. * The Blur Post Process which blurs an image based on a kernel and direction.
  70066. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  70067. */
  70068. var BlurPostProcess = /** @class */ (function (_super) {
  70069. __extends(BlurPostProcess, _super);
  70070. /**
  70071. * Creates a new instance BlurPostProcess
  70072. * @param name The name of the effect.
  70073. * @param direction The direction in which to blur the image.
  70074. * @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.
  70075. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  70076. * @param camera The camera to apply the render pass to.
  70077. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70078. * @param engine The engine which the post process will be applied. (default: current engine)
  70079. * @param reusable If the post process can be reused on the same frame. (default: false)
  70080. * @param textureType Type of textures used when performing the post process. (default: 0)
  70081. * @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)
  70082. */
  70083. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  70084. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70085. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70086. if (defines === void 0) { defines = ""; }
  70087. if (blockCompilation === void 0) { blockCompilation = false; }
  70088. 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;
  70089. _this.direction = direction;
  70090. _this.blockCompilation = blockCompilation;
  70091. _this._packedFloat = false;
  70092. _this._staticDefines = "";
  70093. _this._staticDefines = defines;
  70094. _this.onApplyObservable.add(function (effect) {
  70095. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  70096. });
  70097. _this.kernel = kernel;
  70098. return _this;
  70099. }
  70100. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  70101. /**
  70102. * Gets the length in pixels of the blur sample region
  70103. */
  70104. get: function () {
  70105. return this._idealKernel;
  70106. },
  70107. /**
  70108. * Sets the length in pixels of the blur sample region
  70109. */
  70110. set: function (v) {
  70111. if (this._idealKernel === v) {
  70112. return;
  70113. }
  70114. v = Math.max(v, 1);
  70115. this._idealKernel = v;
  70116. this._kernel = this._nearestBestKernel(v);
  70117. if (!this.blockCompilation) {
  70118. this._updateParameters();
  70119. }
  70120. },
  70121. enumerable: true,
  70122. configurable: true
  70123. });
  70124. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  70125. /**
  70126. * Gets wether or not the blur is unpacking/repacking floats
  70127. */
  70128. get: function () {
  70129. return this._packedFloat;
  70130. },
  70131. /**
  70132. * Sets wether or not the blur needs to unpack/repack floats
  70133. */
  70134. set: function (v) {
  70135. if (this._packedFloat === v) {
  70136. return;
  70137. }
  70138. this._packedFloat = v;
  70139. if (!this.blockCompilation) {
  70140. this._updateParameters();
  70141. }
  70142. },
  70143. enumerable: true,
  70144. configurable: true
  70145. });
  70146. /**
  70147. * Updates the effect with the current post process compile time values and recompiles the shader.
  70148. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  70149. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  70150. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  70151. * @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
  70152. * @param onCompiled Called when the shader has been compiled.
  70153. * @param onError Called if there is an error when compiling a shader.
  70154. */
  70155. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  70156. if (defines === void 0) { defines = null; }
  70157. if (uniforms === void 0) { uniforms = null; }
  70158. if (samplers === void 0) { samplers = null; }
  70159. this._updateParameters(onCompiled, onError);
  70160. };
  70161. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  70162. // Generate sampling offsets and weights
  70163. var N = this._kernel;
  70164. var centerIndex = (N - 1) / 2;
  70165. // Generate Gaussian sampling weights over kernel
  70166. var offsets = [];
  70167. var weights = [];
  70168. var totalWeight = 0;
  70169. for (var i = 0; i < N; i++) {
  70170. var u = i / (N - 1);
  70171. var w = this._gaussianWeight(u * 2.0 - 1);
  70172. offsets[i] = (i - centerIndex);
  70173. weights[i] = w;
  70174. totalWeight += w;
  70175. }
  70176. // Normalize weights
  70177. for (var i = 0; i < weights.length; i++) {
  70178. weights[i] /= totalWeight;
  70179. }
  70180. // Optimize: combine samples to take advantage of hardware linear sampling
  70181. // Walk from left to center, combining pairs (symmetrically)
  70182. var linearSamplingWeights = [];
  70183. var linearSamplingOffsets = [];
  70184. var linearSamplingMap = [];
  70185. for (var i = 0; i <= centerIndex; i += 2) {
  70186. var j = Math.min(i + 1, Math.floor(centerIndex));
  70187. var singleCenterSample = i === j;
  70188. if (singleCenterSample) {
  70189. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  70190. }
  70191. else {
  70192. var sharedCell = j === centerIndex;
  70193. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  70194. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  70195. if (offsetLinear === 0) {
  70196. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  70197. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  70198. }
  70199. else {
  70200. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  70201. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  70202. }
  70203. }
  70204. }
  70205. for (var i = 0; i < linearSamplingMap.length; i++) {
  70206. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  70207. linearSamplingWeights[i] = linearSamplingMap[i].w;
  70208. }
  70209. // Replace with optimized
  70210. offsets = linearSamplingOffsets;
  70211. weights = linearSamplingWeights;
  70212. // Generate shaders
  70213. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  70214. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  70215. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  70216. var defines = "";
  70217. defines += this._staticDefines;
  70218. for (var i = 0; i < varyingCount; i++) {
  70219. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  70220. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  70221. }
  70222. var depCount = 0;
  70223. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  70224. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  70225. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  70226. depCount++;
  70227. }
  70228. if (this.packedFloat) {
  70229. defines += "#define PACKEDFLOAT 1";
  70230. }
  70231. this.blockCompilation = false;
  70232. _super.prototype.updateEffect.call(this, defines, null, null, {
  70233. varyingCount: varyingCount,
  70234. depCount: depCount
  70235. }, onCompiled, onError);
  70236. };
  70237. /**
  70238. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  70239. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  70240. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  70241. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  70242. * The gaps between physical kernels are compensated for in the weighting of the samples
  70243. * @param idealKernel Ideal blur kernel.
  70244. * @return Nearest best kernel.
  70245. */
  70246. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  70247. var v = Math.round(idealKernel);
  70248. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  70249. var k = _a[_i];
  70250. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  70251. return Math.max(k, 3);
  70252. }
  70253. }
  70254. return Math.max(v, 3);
  70255. };
  70256. /**
  70257. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  70258. * @param x The point on the Gaussian distribution to sample.
  70259. * @return the value of the Gaussian function at x.
  70260. */
  70261. BlurPostProcess.prototype._gaussianWeight = function (x) {
  70262. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  70263. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  70264. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  70265. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  70266. // truncated at around 1.3% of peak strength.
  70267. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  70268. var sigma = (1 / 3);
  70269. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  70270. var exponent = -((x * x) / (2.0 * sigma * sigma));
  70271. var weight = (1.0 / denominator) * Math.exp(exponent);
  70272. return weight;
  70273. };
  70274. /**
  70275. * Generates a string that can be used as a floating point number in GLSL.
  70276. * @param x Value to print.
  70277. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  70278. * @return GLSL float string.
  70279. */
  70280. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  70281. if (decimalFigures === void 0) { decimalFigures = 8; }
  70282. return x.toFixed(decimalFigures).replace(/0+$/, '');
  70283. };
  70284. return BlurPostProcess;
  70285. }(BABYLON.PostProcess));
  70286. BABYLON.BlurPostProcess = BlurPostProcess;
  70287. })(BABYLON || (BABYLON = {}));
  70288. //# sourceMappingURL=babylon.blurPostProcess.js.map
  70289. "use strict";
  70290. var BABYLON;
  70291. (function (BABYLON) {
  70292. /**
  70293. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  70294. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  70295. * based on samples that have a large difference in distance than the center pixel.
  70296. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  70297. */
  70298. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  70299. __extends(DepthOfFieldBlurPostProcess, _super);
  70300. /**
  70301. * Creates a new instance CircleOfConfusionPostProcess
  70302. * @param name The name of the effect.
  70303. * @param scene The scene the effect belongs to.
  70304. * @param direction The direction the blur should be applied.
  70305. * @param kernel The size of the kernel used to blur.
  70306. * @param options The required width/height ratio to downsize to before computing the render pass.
  70307. * @param camera The camera to apply the render pass to.
  70308. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  70309. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  70310. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70311. * @param engine The engine which the post process will be applied. (default: current engine)
  70312. * @param reusable If the post process can be reused on the same frame. (default: false)
  70313. * @param textureType Type of textures used when performing the post process. (default: 0)
  70314. * @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)
  70315. */
  70316. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  70317. if (imageToBlur === void 0) { imageToBlur = null; }
  70318. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70319. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70320. if (blockCompilation === void 0) { blockCompilation = false; }
  70321. 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;
  70322. _this.direction = direction;
  70323. _this.onApplyObservable.add(function (effect) {
  70324. if (imageToBlur != null) {
  70325. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  70326. }
  70327. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  70328. if (scene.activeCamera) {
  70329. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  70330. }
  70331. });
  70332. return _this;
  70333. }
  70334. return DepthOfFieldBlurPostProcess;
  70335. }(BABYLON.BlurPostProcess));
  70336. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  70337. })(BABYLON || (BABYLON = {}));
  70338. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  70339. "use strict";
  70340. var BABYLON;
  70341. (function (BABYLON) {
  70342. /**
  70343. * Options to be set when merging outputs from the default pipeline.
  70344. */
  70345. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  70346. function DepthOfFieldMergePostProcessOptions() {
  70347. }
  70348. return DepthOfFieldMergePostProcessOptions;
  70349. }());
  70350. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  70351. /**
  70352. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  70353. */
  70354. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  70355. __extends(DepthOfFieldMergePostProcess, _super);
  70356. /**
  70357. * Creates a new instance of DepthOfFieldMergePostProcess
  70358. * @param name The name of the effect.
  70359. * @param originalFromInput Post process which's input will be used for the merge.
  70360. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  70361. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  70362. * @param options The required width/height ratio to downsize to before computing the render pass.
  70363. * @param camera The camera to apply the render pass to.
  70364. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70365. * @param engine The engine which the post process will be applied. (default: current engine)
  70366. * @param reusable If the post process can be reused on the same frame. (default: false)
  70367. * @param textureType Type of textures used when performing the post process. (default: 0)
  70368. * @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)
  70369. */
  70370. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70371. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70372. if (blockCompilation === void 0) { blockCompilation = false; }
  70373. var _this = _super.call(this, name, "depthOfFieldMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  70374. _this.blurSteps = blurSteps;
  70375. _this.onApplyObservable.add(function (effect) {
  70376. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  70377. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  70378. blurSteps.forEach(function (step, index) {
  70379. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  70380. });
  70381. });
  70382. if (!blockCompilation) {
  70383. _this.updateEffect();
  70384. }
  70385. return _this;
  70386. }
  70387. /**
  70388. * Updates the effect with the current post process compile time values and recompiles the shader.
  70389. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  70390. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  70391. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  70392. * @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
  70393. * @param onCompiled Called when the shader has been compiled.
  70394. * @param onError Called if there is an error when compiling a shader.
  70395. */
  70396. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  70397. if (defines === void 0) { defines = null; }
  70398. if (uniforms === void 0) { uniforms = null; }
  70399. if (samplers === void 0) { samplers = null; }
  70400. if (!defines) {
  70401. defines = "";
  70402. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  70403. }
  70404. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  70405. };
  70406. return DepthOfFieldMergePostProcess;
  70407. }(BABYLON.PostProcess));
  70408. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  70409. })(BABYLON || (BABYLON = {}));
  70410. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  70411. "use strict";
  70412. var BABYLON;
  70413. (function (BABYLON) {
  70414. /**
  70415. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  70416. */
  70417. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  70418. __extends(CircleOfConfusionPostProcess, _super);
  70419. /**
  70420. * Creates a new instance CircleOfConfusionPostProcess
  70421. * @param name The name of the effect.
  70422. * @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.
  70423. * @param options The required width/height ratio to downsize to before computing the render pass.
  70424. * @param camera The camera to apply the render pass to.
  70425. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70426. * @param engine The engine which the post process will be applied. (default: current engine)
  70427. * @param reusable If the post process can be reused on the same frame. (default: false)
  70428. * @param textureType Type of textures used when performing the post process. (default: 0)
  70429. * @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)
  70430. */
  70431. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70432. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70433. if (blockCompilation === void 0) { blockCompilation = false; }
  70434. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  70435. /**
  70436. * 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.
  70437. */
  70438. _this.lensSize = 50;
  70439. /**
  70440. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  70441. */
  70442. _this.fStop = 1.4;
  70443. /**
  70444. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  70445. */
  70446. _this.focusDistance = 2000;
  70447. /**
  70448. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  70449. */
  70450. _this.focalLength = 50;
  70451. _this._depthTexture = null;
  70452. _this._depthTexture = depthTexture;
  70453. _this.onApplyObservable.add(function (effect) {
  70454. if (!_this._depthTexture) {
  70455. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  70456. return;
  70457. }
  70458. effect.setTexture("depthSampler", _this._depthTexture);
  70459. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  70460. var aperture = _this.lensSize / _this.fStop;
  70461. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  70462. effect.setFloat('focusDistance', _this.focusDistance);
  70463. effect.setFloat('cocPrecalculation', cocPrecalculation);
  70464. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  70465. });
  70466. return _this;
  70467. }
  70468. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  70469. /**
  70470. * 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.
  70471. */
  70472. set: function (value) {
  70473. this._depthTexture = value;
  70474. },
  70475. enumerable: true,
  70476. configurable: true
  70477. });
  70478. return CircleOfConfusionPostProcess;
  70479. }(BABYLON.PostProcess));
  70480. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  70481. })(BABYLON || (BABYLON = {}));
  70482. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  70483. "use strict";
  70484. var BABYLON;
  70485. (function (BABYLON) {
  70486. /**
  70487. * Specifies the level of max blur that should be applied when using the depth of field effect
  70488. */
  70489. var DepthOfFieldEffectBlurLevel;
  70490. (function (DepthOfFieldEffectBlurLevel) {
  70491. /**
  70492. * Subtle blur
  70493. */
  70494. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  70495. /**
  70496. * Medium blur
  70497. */
  70498. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  70499. /**
  70500. * Large blur
  70501. */
  70502. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  70503. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  70504. ;
  70505. /**
  70506. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  70507. */
  70508. var DepthOfFieldEffect = /** @class */ (function (_super) {
  70509. __extends(DepthOfFieldEffect, _super);
  70510. /**
  70511. * Creates a new instance DepthOfFieldEffect
  70512. * @param scene The scene the effect belongs to.
  70513. * @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.
  70514. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  70515. * @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)
  70516. */
  70517. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  70518. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  70519. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  70520. if (blockCompilation === void 0) { blockCompilation = false; }
  70521. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  70522. return _this._effects;
  70523. }, true) || this;
  70524. /**
  70525. * Internal post processes in depth of field effect
  70526. */
  70527. _this._effects = [];
  70528. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  70529. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70530. // 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)
  70531. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  70532. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  70533. _this._depthOfFieldBlurY = [];
  70534. _this._depthOfFieldBlurX = [];
  70535. var blurCount = 1;
  70536. var kernelSize = 15;
  70537. switch (blurLevel) {
  70538. case DepthOfFieldEffectBlurLevel.High: {
  70539. blurCount = 3;
  70540. kernelSize = 51;
  70541. break;
  70542. }
  70543. case DepthOfFieldEffectBlurLevel.Medium: {
  70544. blurCount = 2;
  70545. kernelSize = 31;
  70546. break;
  70547. }
  70548. default: {
  70549. kernelSize = 15;
  70550. blurCount = 1;
  70551. break;
  70552. }
  70553. }
  70554. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  70555. for (var i = 0; i < blurCount; i++) {
  70556. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._circleOfConfusion, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70557. blurY.autoClear = false;
  70558. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._circleOfConfusion, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70559. blurX.autoClear = false;
  70560. _this._depthOfFieldBlurY.push(blurY);
  70561. _this._depthOfFieldBlurX.push(blurX);
  70562. }
  70563. // Set all post processes on the effect.
  70564. _this._effects = [_this._circleOfConfusion];
  70565. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  70566. _this._effects.push(_this._depthOfFieldBlurY[i]);
  70567. _this._effects.push(_this._depthOfFieldBlurX[i]);
  70568. }
  70569. // Merge blurred images with original image based on circleOfConfusion
  70570. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70571. _this._dofMerge.autoClear = false;
  70572. _this._effects.push(_this._dofMerge);
  70573. return _this;
  70574. }
  70575. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  70576. get: function () {
  70577. return this._circleOfConfusion.focalLength;
  70578. },
  70579. /**
  70580. * The focal the length of the camera used in the effect
  70581. */
  70582. set: function (value) {
  70583. this._circleOfConfusion.focalLength = value;
  70584. },
  70585. enumerable: true,
  70586. configurable: true
  70587. });
  70588. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  70589. get: function () {
  70590. return this._circleOfConfusion.fStop;
  70591. },
  70592. /**
  70593. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  70594. */
  70595. set: function (value) {
  70596. this._circleOfConfusion.fStop = value;
  70597. },
  70598. enumerable: true,
  70599. configurable: true
  70600. });
  70601. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  70602. get: function () {
  70603. return this._circleOfConfusion.focusDistance;
  70604. },
  70605. /**
  70606. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  70607. */
  70608. set: function (value) {
  70609. this._circleOfConfusion.focusDistance = value;
  70610. },
  70611. enumerable: true,
  70612. configurable: true
  70613. });
  70614. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  70615. get: function () {
  70616. return this._circleOfConfusion.lensSize;
  70617. },
  70618. /**
  70619. * 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.
  70620. */
  70621. set: function (value) {
  70622. this._circleOfConfusion.lensSize = value;
  70623. },
  70624. enumerable: true,
  70625. configurable: true
  70626. });
  70627. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  70628. /**
  70629. * 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.
  70630. */
  70631. set: function (value) {
  70632. this._circleOfConfusion.depthTexture = value;
  70633. },
  70634. enumerable: true,
  70635. configurable: true
  70636. });
  70637. /**
  70638. * Disposes each of the internal effects for a given camera.
  70639. * @param camera The camera to dispose the effect on.
  70640. */
  70641. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  70642. for (var effect in this._effects) {
  70643. this._effects[effect].dispose(camera);
  70644. }
  70645. };
  70646. /**
  70647. * Internal
  70648. */
  70649. DepthOfFieldEffect.prototype._updateEffects = function () {
  70650. for (var effect in this._effects) {
  70651. this._effects[effect].updateEffect();
  70652. }
  70653. };
  70654. /**
  70655. * Internal
  70656. * @returns if all the contained post processes are ready.
  70657. */
  70658. DepthOfFieldEffect.prototype._isReady = function () {
  70659. for (var effect in this._effects) {
  70660. if (!this._effects[effect].isReady()) {
  70661. return false;
  70662. }
  70663. }
  70664. return true;
  70665. };
  70666. return DepthOfFieldEffect;
  70667. }(BABYLON.PostProcessRenderEffect));
  70668. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  70669. })(BABYLON || (BABYLON = {}));
  70670. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  70671. "use strict";
  70672. var BABYLON;
  70673. (function (BABYLON) {
  70674. /**
  70675. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  70676. */
  70677. var BloomMergePostProcess = /** @class */ (function (_super) {
  70678. __extends(BloomMergePostProcess, _super);
  70679. /**
  70680. * Creates a new instance of @see BloomMergePostProcess
  70681. * @param name The name of the effect.
  70682. * @param originalFromInput Post process which's input will be used for the merge.
  70683. * @param blurred Blurred highlights post process which's output will be used.
  70684. * @param weight Weight of the bloom to be added to the original input.
  70685. * @param options The required width/height ratio to downsize to before computing the render pass.
  70686. * @param camera The camera to apply the render pass to.
  70687. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70688. * @param engine The engine which the post process will be applied. (default: current engine)
  70689. * @param reusable If the post process can be reused on the same frame. (default: false)
  70690. * @param textureType Type of textures used when performing the post process. (default: 0)
  70691. * @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)
  70692. */
  70693. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70694. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70695. if (blockCompilation === void 0) { blockCompilation = false; }
  70696. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  70697. _this.weight = weight;
  70698. _this.onApplyObservable.add(function (effect) {
  70699. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  70700. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  70701. effect.setFloat("bloomWeight", _this.weight);
  70702. });
  70703. if (!blockCompilation) {
  70704. _this.updateEffect();
  70705. }
  70706. return _this;
  70707. }
  70708. return BloomMergePostProcess;
  70709. }(BABYLON.PostProcess));
  70710. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  70711. })(BABYLON || (BABYLON = {}));
  70712. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  70713. "use strict";
  70714. var BABYLON;
  70715. (function (BABYLON) {
  70716. /**
  70717. * 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.
  70718. */
  70719. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  70720. __extends(ExtractHighlightsPostProcess, _super);
  70721. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70722. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70723. if (blockCompilation === void 0) { blockCompilation = false; }
  70724. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  70725. /**
  70726. * The luminance threshold, pixels below this value will be set to black.
  70727. */
  70728. _this.threshold = 0.9;
  70729. /**
  70730. * Internal
  70731. */
  70732. _this._exposure = 1;
  70733. /**
  70734. * Post process which has the input texture to be used when performing highlight extraction
  70735. */
  70736. _this._inputPostProcess = null;
  70737. _this.onApplyObservable.add(function (effect) {
  70738. if (_this._inputPostProcess) {
  70739. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  70740. }
  70741. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  70742. effect.setFloat('exposure', _this._exposure);
  70743. });
  70744. return _this;
  70745. }
  70746. return ExtractHighlightsPostProcess;
  70747. }(BABYLON.PostProcess));
  70748. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  70749. })(BABYLON || (BABYLON = {}));
  70750. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  70751. "use strict";
  70752. var BABYLON;
  70753. (function (BABYLON) {
  70754. /**
  70755. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  70756. */
  70757. var BloomEffect = /** @class */ (function (_super) {
  70758. __extends(BloomEffect, _super);
  70759. /**
  70760. * Creates a new instance of @see BloomEffect
  70761. * @param scene The scene the effect belongs to.
  70762. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  70763. * @param bloomKernel The size of the kernel to be used when applying the blur.
  70764. * @param bloomWeight The the strength of bloom.
  70765. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  70766. * @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)
  70767. */
  70768. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  70769. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  70770. if (blockCompilation === void 0) { blockCompilation = false; }
  70771. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  70772. return _this._effects;
  70773. }, true) || this;
  70774. _this.bloomScale = bloomScale;
  70775. /**
  70776. * Internal
  70777. */
  70778. _this._effects = [];
  70779. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70780. _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);
  70781. _this._blurX.alwaysForcePOT = true;
  70782. _this._blurX.autoClear = false;
  70783. _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);
  70784. _this._blurY.alwaysForcePOT = true;
  70785. _this._blurY.autoClear = false;
  70786. _this.kernel = bloomKernel;
  70787. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  70788. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70789. _this._merge.autoClear = false;
  70790. _this._effects.push(_this._merge);
  70791. return _this;
  70792. }
  70793. Object.defineProperty(BloomEffect.prototype, "threshold", {
  70794. /**
  70795. * The luminance threshold to find bright areas of the image to bloom.
  70796. */
  70797. get: function () {
  70798. return this._downscale.threshold;
  70799. },
  70800. set: function (value) {
  70801. this._downscale.threshold = value;
  70802. },
  70803. enumerable: true,
  70804. configurable: true
  70805. });
  70806. Object.defineProperty(BloomEffect.prototype, "weight", {
  70807. /**
  70808. * The strength of the bloom.
  70809. */
  70810. get: function () {
  70811. return this._merge.weight;
  70812. },
  70813. set: function (value) {
  70814. this._merge.weight = value;
  70815. },
  70816. enumerable: true,
  70817. configurable: true
  70818. });
  70819. Object.defineProperty(BloomEffect.prototype, "kernel", {
  70820. /**
  70821. * Specifies the size of the bloom blur kernel, relative to the final output size
  70822. */
  70823. get: function () {
  70824. return this._blurX.kernel / this.bloomScale;
  70825. },
  70826. set: function (value) {
  70827. this._blurX.kernel = value * this.bloomScale;
  70828. this._blurY.kernel = value * this.bloomScale;
  70829. },
  70830. enumerable: true,
  70831. configurable: true
  70832. });
  70833. /**
  70834. * Disposes each of the internal effects for a given camera.
  70835. * @param camera The camera to dispose the effect on.
  70836. */
  70837. BloomEffect.prototype.disposeEffects = function (camera) {
  70838. for (var effect in this._effects) {
  70839. this._effects[effect].dispose(camera);
  70840. }
  70841. };
  70842. /**
  70843. * Internal
  70844. */
  70845. BloomEffect.prototype._updateEffects = function () {
  70846. for (var effect in this._effects) {
  70847. this._effects[effect].updateEffect();
  70848. }
  70849. };
  70850. /**
  70851. * Internal
  70852. * @returns if all the contained post processes are ready.
  70853. */
  70854. BloomEffect.prototype._isReady = function () {
  70855. for (var effect in this._effects) {
  70856. if (!this._effects[effect].isReady()) {
  70857. return false;
  70858. }
  70859. }
  70860. return true;
  70861. };
  70862. return BloomEffect;
  70863. }(BABYLON.PostProcessRenderEffect));
  70864. BABYLON.BloomEffect = BloomEffect;
  70865. })(BABYLON || (BABYLON = {}));
  70866. //# sourceMappingURL=babylon.bloomEffect.js.map
  70867. "use strict";
  70868. var BABYLON;
  70869. (function (BABYLON) {
  70870. /**
  70871. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  70872. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  70873. */
  70874. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  70875. __extends(DefaultRenderingPipeline, _super);
  70876. /**
  70877. * @constructor
  70878. * @param {string} name - The rendering pipeline name
  70879. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  70880. * @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)
  70881. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  70882. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  70883. */
  70884. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  70885. if (automaticBuild === void 0) { automaticBuild = true; }
  70886. var _this = _super.call(this, scene.getEngine(), name) || this;
  70887. _this._originalCameras = [];
  70888. /**
  70889. * ID of the sharpen post process,
  70890. */
  70891. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  70892. /**
  70893. * ID of the image processing post process;
  70894. */
  70895. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  70896. /**
  70897. * ID of the Fast Approximate Anti-Aliasing post process;
  70898. */
  70899. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  70900. /**
  70901. * ID of the chromatic aberration post process,
  70902. */
  70903. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  70904. /**
  70905. * ID of the grain post process
  70906. */
  70907. _this.GrainPostProcessId = "GrainPostProcessEffect";
  70908. /**
  70909. * Animations which can be used to tweak settings over a period of time
  70910. */
  70911. _this.animations = [];
  70912. _this._imageProcessingConfigurationObserver = null;
  70913. // Values
  70914. _this._sharpenEnabled = false;
  70915. _this._bloomEnabled = false;
  70916. _this._depthOfFieldEnabled = false;
  70917. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  70918. _this._fxaaEnabled = false;
  70919. _this._imageProcessingEnabled = true;
  70920. _this._bloomScale = 0.5;
  70921. _this._chromaticAberrationEnabled = false;
  70922. _this._grainEnabled = false;
  70923. _this._buildAllowed = true;
  70924. _this._resizeObserver = null;
  70925. _this._hardwareScaleLevel = 1.0;
  70926. _this._bloomKernel = 64;
  70927. /**
  70928. * Specifies the weight of the bloom in the final rendering
  70929. */
  70930. _this._bloomWeight = 0.15;
  70931. /**
  70932. * Specifies the luma threshold for the area that will be blurred by the bloom
  70933. */
  70934. _this._bloomThreshold = 0.9;
  70935. _this._samples = 1;
  70936. _this._hasCleared = false;
  70937. _this._prevPostProcess = null;
  70938. _this._prevPrevPostProcess = null;
  70939. _this._cameras = cameras || [];
  70940. _this._originalCameras = _this._cameras.slice();
  70941. _this._buildAllowed = automaticBuild;
  70942. // Initialize
  70943. _this._scene = scene;
  70944. var caps = _this._scene.getEngine().getCaps();
  70945. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  70946. // Misc
  70947. if (_this._hdr) {
  70948. if (caps.textureHalfFloatRender) {
  70949. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70950. }
  70951. else if (caps.textureFloatRender) {
  70952. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70953. }
  70954. }
  70955. else {
  70956. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70957. }
  70958. // Attach
  70959. scene.postProcessRenderPipelineManager.addPipeline(_this);
  70960. var engine = _this._scene.getEngine();
  70961. // Create post processes before hand so they can be modified before enabled.
  70962. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  70963. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  70964. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  70965. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  70966. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  70967. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  70968. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  70969. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  70970. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  70971. _this._resizeObserver = engine.onResizeObservable.add(function () {
  70972. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  70973. _this.bloomKernel = _this.bloomKernel;
  70974. });
  70975. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  70976. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  70977. });
  70978. _this._buildPipeline();
  70979. return _this;
  70980. }
  70981. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  70982. get: function () {
  70983. return this._sharpenEnabled;
  70984. },
  70985. /**
  70986. * Enable or disable the sharpen process from the pipeline
  70987. */
  70988. set: function (enabled) {
  70989. if (this._sharpenEnabled === enabled) {
  70990. return;
  70991. }
  70992. this._sharpenEnabled = enabled;
  70993. this._buildPipeline();
  70994. },
  70995. enumerable: true,
  70996. configurable: true
  70997. });
  70998. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  70999. /**
  71000. * Specifies the size of the bloom blur kernel, relative to the final output size
  71001. */
  71002. get: function () {
  71003. return this._bloomKernel;
  71004. },
  71005. set: function (value) {
  71006. this._bloomKernel = value;
  71007. this.bloom.kernel = value / this._hardwareScaleLevel;
  71008. },
  71009. enumerable: true,
  71010. configurable: true
  71011. });
  71012. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  71013. get: function () {
  71014. return this._bloomWeight;
  71015. },
  71016. /**
  71017. * The strength of the bloom.
  71018. */
  71019. set: function (value) {
  71020. if (this._bloomWeight === value) {
  71021. return;
  71022. }
  71023. this.bloom.weight = value;
  71024. this._bloomWeight = value;
  71025. },
  71026. enumerable: true,
  71027. configurable: true
  71028. });
  71029. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  71030. get: function () {
  71031. return this._bloomThreshold;
  71032. },
  71033. /**
  71034. * The strength of the bloom.
  71035. */
  71036. set: function (value) {
  71037. if (this._bloomThreshold === value) {
  71038. return;
  71039. }
  71040. this.bloom.threshold = value;
  71041. this._bloomThreshold = value;
  71042. },
  71043. enumerable: true,
  71044. configurable: true
  71045. });
  71046. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  71047. get: function () {
  71048. return this._bloomScale;
  71049. },
  71050. /**
  71051. * The scale of the bloom, lower value will provide better performance.
  71052. */
  71053. set: function (value) {
  71054. if (this._bloomScale === value) {
  71055. return;
  71056. }
  71057. this._bloomScale = value;
  71058. // recreate bloom and dispose old as this setting is not dynamic
  71059. this._rebuildBloom();
  71060. this._buildPipeline();
  71061. },
  71062. enumerable: true,
  71063. configurable: true
  71064. });
  71065. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  71066. get: function () {
  71067. return this._bloomEnabled;
  71068. },
  71069. /**
  71070. * Enable or disable the bloom from the pipeline
  71071. */
  71072. set: function (enabled) {
  71073. if (this._bloomEnabled === enabled) {
  71074. return;
  71075. }
  71076. this._bloomEnabled = enabled;
  71077. this._buildPipeline();
  71078. },
  71079. enumerable: true,
  71080. configurable: true
  71081. });
  71082. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  71083. // recreate bloom and dispose old as this setting is not dynamic
  71084. var oldBloom = this.bloom;
  71085. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  71086. this.bloom.threshold = oldBloom.threshold;
  71087. for (var i = 0; i < this._cameras.length; i++) {
  71088. oldBloom.disposeEffects(this._cameras[i]);
  71089. }
  71090. };
  71091. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  71092. /**
  71093. * If the depth of field is enabled.
  71094. */
  71095. get: function () {
  71096. return this._depthOfFieldEnabled;
  71097. },
  71098. set: function (enabled) {
  71099. if (this._depthOfFieldEnabled === enabled) {
  71100. return;
  71101. }
  71102. this._depthOfFieldEnabled = enabled;
  71103. this._buildPipeline();
  71104. },
  71105. enumerable: true,
  71106. configurable: true
  71107. });
  71108. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  71109. /**
  71110. * Blur level of the depth of field effect. (Higher blur will effect performance)
  71111. */
  71112. get: function () {
  71113. return this._depthOfFieldBlurLevel;
  71114. },
  71115. set: function (value) {
  71116. if (this._depthOfFieldBlurLevel === value) {
  71117. return;
  71118. }
  71119. this._depthOfFieldBlurLevel = value;
  71120. // recreate dof and dispose old as this setting is not dynamic
  71121. var oldDof = this.depthOfField;
  71122. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  71123. this.depthOfField.focalLength = oldDof.focalLength;
  71124. this.depthOfField.focusDistance = oldDof.focusDistance;
  71125. this.depthOfField.fStop = oldDof.fStop;
  71126. this.depthOfField.lensSize = oldDof.lensSize;
  71127. for (var i = 0; i < this._cameras.length; i++) {
  71128. oldDof.disposeEffects(this._cameras[i]);
  71129. }
  71130. this._buildPipeline();
  71131. },
  71132. enumerable: true,
  71133. configurable: true
  71134. });
  71135. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  71136. get: function () {
  71137. return this._fxaaEnabled;
  71138. },
  71139. /**
  71140. * If the anti aliasing is enabled.
  71141. */
  71142. set: function (enabled) {
  71143. if (this._fxaaEnabled === enabled) {
  71144. return;
  71145. }
  71146. this._fxaaEnabled = enabled;
  71147. this._buildPipeline();
  71148. },
  71149. enumerable: true,
  71150. configurable: true
  71151. });
  71152. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  71153. get: function () {
  71154. return this._samples;
  71155. },
  71156. /**
  71157. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  71158. */
  71159. set: function (sampleCount) {
  71160. if (this._samples === sampleCount) {
  71161. return;
  71162. }
  71163. this._samples = sampleCount;
  71164. this._buildPipeline();
  71165. },
  71166. enumerable: true,
  71167. configurable: true
  71168. });
  71169. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  71170. get: function () {
  71171. return this._imageProcessingEnabled;
  71172. },
  71173. /**
  71174. * If image processing is enabled.
  71175. */
  71176. set: function (enabled) {
  71177. if (this._imageProcessingEnabled === enabled) {
  71178. return;
  71179. }
  71180. this._imageProcessingEnabled = enabled;
  71181. this._buildPipeline();
  71182. },
  71183. enumerable: true,
  71184. configurable: true
  71185. });
  71186. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  71187. get: function () {
  71188. return this._chromaticAberrationEnabled;
  71189. },
  71190. /**
  71191. * Enable or disable the chromaticAberration process from the pipeline
  71192. */
  71193. set: function (enabled) {
  71194. if (this._chromaticAberrationEnabled === enabled) {
  71195. return;
  71196. }
  71197. this._chromaticAberrationEnabled = enabled;
  71198. this._buildPipeline();
  71199. },
  71200. enumerable: true,
  71201. configurable: true
  71202. });
  71203. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  71204. get: function () {
  71205. return this._grainEnabled;
  71206. },
  71207. /**
  71208. * Enable or disable the grain process from the pipeline
  71209. */
  71210. set: function (enabled) {
  71211. if (this._grainEnabled === enabled) {
  71212. return;
  71213. }
  71214. this._grainEnabled = enabled;
  71215. this._buildPipeline();
  71216. },
  71217. enumerable: true,
  71218. configurable: true
  71219. });
  71220. /**
  71221. * Force the compilation of the entire pipeline.
  71222. */
  71223. DefaultRenderingPipeline.prototype.prepare = function () {
  71224. var previousState = this._buildAllowed;
  71225. this._buildAllowed = true;
  71226. this._buildPipeline();
  71227. this._buildAllowed = previousState;
  71228. };
  71229. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  71230. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  71231. if (this._hasCleared) {
  71232. postProcess.autoClear = false;
  71233. }
  71234. else {
  71235. postProcess.autoClear = true;
  71236. this._scene.autoClear = false;
  71237. this._hasCleared = true;
  71238. }
  71239. if (!skipTextureSharing) {
  71240. if (this._prevPrevPostProcess) {
  71241. postProcess.shareOutputWith(this._prevPrevPostProcess);
  71242. }
  71243. else {
  71244. postProcess.useOwnOutput();
  71245. }
  71246. if (this._prevPostProcess) {
  71247. this._prevPrevPostProcess = this._prevPostProcess;
  71248. }
  71249. this._prevPostProcess = postProcess;
  71250. }
  71251. };
  71252. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  71253. var _this = this;
  71254. if (!this._buildAllowed) {
  71255. return;
  71256. }
  71257. this._scene.autoClear = true;
  71258. var engine = this._scene.getEngine();
  71259. this._disposePostProcesses();
  71260. if (this._cameras !== null) {
  71261. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  71262. // get back cameras to be used to reattach pipeline
  71263. this._cameras = this._originalCameras.slice();
  71264. }
  71265. this._reset();
  71266. this._prevPostProcess = null;
  71267. this._prevPrevPostProcess = null;
  71268. this._hasCleared = false;
  71269. if (this.depthOfFieldEnabled) {
  71270. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  71271. this.depthOfField.depthTexture = depthTexture;
  71272. if (!this.depthOfField._isReady()) {
  71273. this.depthOfField._updateEffects();
  71274. }
  71275. this.addEffect(this.depthOfField);
  71276. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  71277. }
  71278. if (this.bloomEnabled) {
  71279. if (!this.bloom._isReady()) {
  71280. this.bloom._updateEffects();
  71281. }
  71282. this.addEffect(this.bloom);
  71283. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  71284. }
  71285. if (this._imageProcessingEnabled) {
  71286. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  71287. if (this._hdr) {
  71288. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  71289. this._setAutoClearAndTextureSharing(this.imageProcessing);
  71290. }
  71291. else {
  71292. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  71293. }
  71294. }
  71295. if (this.sharpenEnabled) {
  71296. if (!this.sharpen.isReady()) {
  71297. this.sharpen.updateEffect();
  71298. }
  71299. this.addEffect(this._sharpenEffect);
  71300. this._setAutoClearAndTextureSharing(this.sharpen);
  71301. }
  71302. if (this.grainEnabled) {
  71303. if (!this.grain.isReady()) {
  71304. this.grain.updateEffect();
  71305. }
  71306. this.addEffect(this._grainEffect);
  71307. this._setAutoClearAndTextureSharing(this.grain);
  71308. }
  71309. if (this.chromaticAberrationEnabled) {
  71310. if (!this.chromaticAberration.isReady()) {
  71311. this.chromaticAberration.updateEffect();
  71312. }
  71313. this.addEffect(this._chromaticAberrationEffect);
  71314. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  71315. }
  71316. if (this.fxaaEnabled) {
  71317. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  71318. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  71319. this._setAutoClearAndTextureSharing(this.fxaa, true);
  71320. }
  71321. if (this._cameras !== null) {
  71322. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  71323. }
  71324. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  71325. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  71326. }
  71327. };
  71328. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  71329. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  71330. for (var i = 0; i < this._cameras.length; i++) {
  71331. var camera = this._cameras[i];
  71332. if (this.imageProcessing) {
  71333. this.imageProcessing.dispose(camera);
  71334. }
  71335. if (this.fxaa) {
  71336. this.fxaa.dispose(camera);
  71337. }
  71338. // These are created in the constructor and should not be disposed on every pipeline change
  71339. if (disposeNonRecreated) {
  71340. if (this.sharpen) {
  71341. this.sharpen.dispose(camera);
  71342. }
  71343. if (this.depthOfField) {
  71344. this.depthOfField.disposeEffects(camera);
  71345. }
  71346. if (this.bloom) {
  71347. this.bloom.disposeEffects(camera);
  71348. }
  71349. if (this.chromaticAberration) {
  71350. this.chromaticAberration.dispose(camera);
  71351. }
  71352. if (this.grain) {
  71353. this.grain.dispose(camera);
  71354. }
  71355. }
  71356. }
  71357. this.imageProcessing = null;
  71358. this.fxaa = null;
  71359. if (disposeNonRecreated) {
  71360. this.sharpen = null;
  71361. this._sharpenEffect = null;
  71362. this.depthOfField = null;
  71363. this.bloom = null;
  71364. this.chromaticAberration = null;
  71365. this._chromaticAberrationEffect = null;
  71366. this.grain = null;
  71367. this._grainEffect = null;
  71368. }
  71369. };
  71370. /**
  71371. * Dispose of the pipeline and stop all post processes
  71372. */
  71373. DefaultRenderingPipeline.prototype.dispose = function () {
  71374. this._disposePostProcesses(true);
  71375. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  71376. this._scene.autoClear = true;
  71377. if (this._resizeObserver) {
  71378. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  71379. this._resizeObserver = null;
  71380. }
  71381. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  71382. _super.prototype.dispose.call(this);
  71383. };
  71384. /**
  71385. * Serialize the rendering pipeline (Used when exporting)
  71386. * @returns the serialized object
  71387. */
  71388. DefaultRenderingPipeline.prototype.serialize = function () {
  71389. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  71390. serializationObject.customType = "DefaultRenderingPipeline";
  71391. return serializationObject;
  71392. };
  71393. /**
  71394. * Parse the serialized pipeline
  71395. * @param source Source pipeline.
  71396. * @param scene The scene to load the pipeline to.
  71397. * @param rootUrl The URL of the serialized pipeline.
  71398. * @returns An instantiated pipeline from the serialized object.
  71399. */
  71400. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  71401. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  71402. };
  71403. __decorate([
  71404. BABYLON.serialize()
  71405. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  71406. __decorate([
  71407. BABYLON.serialize()
  71408. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  71409. __decorate([
  71410. BABYLON.serialize()
  71411. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  71412. __decorate([
  71413. BABYLON.serialize()
  71414. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  71415. __decorate([
  71416. BABYLON.serialize()
  71417. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  71418. __decorate([
  71419. BABYLON.serialize()
  71420. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  71421. __decorate([
  71422. BABYLON.serialize()
  71423. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  71424. __decorate([
  71425. BABYLON.serialize()
  71426. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  71427. __decorate([
  71428. BABYLON.serialize()
  71429. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  71430. __decorate([
  71431. BABYLON.serialize()
  71432. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  71433. __decorate([
  71434. BABYLON.serialize()
  71435. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  71436. __decorate([
  71437. BABYLON.serialize()
  71438. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  71439. __decorate([
  71440. BABYLON.serialize()
  71441. ], DefaultRenderingPipeline.prototype, "samples", null);
  71442. __decorate([
  71443. BABYLON.serialize()
  71444. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  71445. __decorate([
  71446. BABYLON.serialize()
  71447. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  71448. __decorate([
  71449. BABYLON.serialize()
  71450. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  71451. return DefaultRenderingPipeline;
  71452. }(BABYLON.PostProcessRenderPipeline));
  71453. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  71454. })(BABYLON || (BABYLON = {}));
  71455. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  71456. "use strict";
  71457. var BABYLON;
  71458. (function (BABYLON) {
  71459. /**
  71460. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  71461. */
  71462. var GeometryBufferRenderer = /** @class */ (function () {
  71463. /**
  71464. * Creates a new G Buffer for the scene
  71465. * @param scene The scene the buffer belongs to
  71466. * @param ratio How big is the buffer related to the main canvas.
  71467. */
  71468. function GeometryBufferRenderer(scene, ratio) {
  71469. if (ratio === void 0) { ratio = 1; }
  71470. this._enablePosition = false;
  71471. this._scene = scene;
  71472. this._ratio = ratio;
  71473. // Render target
  71474. this._createRenderTargets();
  71475. }
  71476. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  71477. /**
  71478. * Set the render list (meshes to be rendered) used in the G buffer.
  71479. */
  71480. set: function (meshes) {
  71481. this._multiRenderTarget.renderList = meshes;
  71482. },
  71483. enumerable: true,
  71484. configurable: true
  71485. });
  71486. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  71487. /**
  71488. * Gets wether or not G buffer are supported by the running hardware.
  71489. * This requires draw buffer supports
  71490. */
  71491. get: function () {
  71492. return this._multiRenderTarget.isSupported;
  71493. },
  71494. enumerable: true,
  71495. configurable: true
  71496. });
  71497. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  71498. /**
  71499. * Gets wether or not position are enabled for the G buffer.
  71500. */
  71501. get: function () {
  71502. return this._enablePosition;
  71503. },
  71504. /**
  71505. * Sets wether or not position are enabled for the G buffer.
  71506. */
  71507. set: function (enable) {
  71508. this._enablePosition = enable;
  71509. this.dispose();
  71510. this._createRenderTargets();
  71511. },
  71512. enumerable: true,
  71513. configurable: true
  71514. });
  71515. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  71516. /**
  71517. * Gets the scene associated with the buffer.
  71518. */
  71519. get: function () {
  71520. return this._scene;
  71521. },
  71522. enumerable: true,
  71523. configurable: true
  71524. });
  71525. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  71526. /**
  71527. * Gets the ratio used by the buffer during its creation.
  71528. * How big is the buffer related to the main canvas.
  71529. */
  71530. get: function () {
  71531. return this._ratio;
  71532. },
  71533. enumerable: true,
  71534. configurable: true
  71535. });
  71536. /**
  71537. * Checks wether everything is ready to render a submesh to the G buffer.
  71538. * @param subMesh the submesh to check readiness for
  71539. * @param useInstances is the mesh drawn using instance or not
  71540. * @returns true if ready otherwise false
  71541. */
  71542. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  71543. var material = subMesh.getMaterial();
  71544. if (material && material.disableDepthWrite) {
  71545. return false;
  71546. }
  71547. var defines = [];
  71548. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  71549. var mesh = subMesh.getMesh();
  71550. // Alpha test
  71551. if (material && material.needAlphaTesting()) {
  71552. defines.push("#define ALPHATEST");
  71553. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71554. attribs.push(BABYLON.VertexBuffer.UVKind);
  71555. defines.push("#define UV1");
  71556. }
  71557. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  71558. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71559. defines.push("#define UV2");
  71560. }
  71561. }
  71562. // Buffers
  71563. if (this._enablePosition) {
  71564. defines.push("#define POSITION");
  71565. }
  71566. // Bones
  71567. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71568. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71569. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71570. if (mesh.numBoneInfluencers > 4) {
  71571. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  71572. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  71573. }
  71574. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71575. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  71576. }
  71577. else {
  71578. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71579. }
  71580. // Instances
  71581. if (useInstances) {
  71582. defines.push("#define INSTANCES");
  71583. attribs.push("world0");
  71584. attribs.push("world1");
  71585. attribs.push("world2");
  71586. attribs.push("world3");
  71587. }
  71588. // Get correct effect
  71589. var join = defines.join("\n");
  71590. if (this._cachedDefines !== join) {
  71591. this._cachedDefines = join;
  71592. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  71593. }
  71594. return this._effect.isReady();
  71595. };
  71596. /**
  71597. * Gets the current underlying G Buffer.
  71598. * @returns the buffer
  71599. */
  71600. GeometryBufferRenderer.prototype.getGBuffer = function () {
  71601. return this._multiRenderTarget;
  71602. };
  71603. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  71604. /**
  71605. * Gets the number of samples used to render the buffer (anti aliasing).
  71606. */
  71607. get: function () {
  71608. return this._multiRenderTarget.samples;
  71609. },
  71610. /**
  71611. * Sets the number of samples used to render the buffer (anti aliasing).
  71612. */
  71613. set: function (value) {
  71614. this._multiRenderTarget.samples = value;
  71615. },
  71616. enumerable: true,
  71617. configurable: true
  71618. });
  71619. /**
  71620. * Disposes the renderer and frees up associated resources.
  71621. */
  71622. GeometryBufferRenderer.prototype.dispose = function () {
  71623. this.getGBuffer().dispose();
  71624. };
  71625. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  71626. var _this = this;
  71627. var engine = this._scene.getEngine();
  71628. var count = this._enablePosition ? 3 : 2;
  71629. 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 });
  71630. if (!this.isSupported) {
  71631. return;
  71632. }
  71633. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71634. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71635. this._multiRenderTarget.refreshRate = 1;
  71636. this._multiRenderTarget.renderParticles = false;
  71637. this._multiRenderTarget.renderList = null;
  71638. // set default depth value to 1.0 (far away)
  71639. this._multiRenderTarget.onClearObservable.add(function (engine) {
  71640. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  71641. });
  71642. // Custom render function
  71643. var renderSubMesh = function (subMesh) {
  71644. var mesh = subMesh.getRenderingMesh();
  71645. var scene = _this._scene;
  71646. var engine = scene.getEngine();
  71647. var material = subMesh.getMaterial();
  71648. if (!material) {
  71649. return;
  71650. }
  71651. // Culling
  71652. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  71653. // Managing instances
  71654. var batch = mesh._getInstancesRenderList(subMesh._id);
  71655. if (batch.mustReturn) {
  71656. return;
  71657. }
  71658. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  71659. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  71660. engine.enableEffect(_this._effect);
  71661. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  71662. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  71663. _this._effect.setMatrix("view", scene.getViewMatrix());
  71664. // Alpha test
  71665. if (material && material.needAlphaTesting()) {
  71666. var alphaTexture = material.getAlphaTestTexture();
  71667. if (alphaTexture) {
  71668. _this._effect.setTexture("diffuseSampler", alphaTexture);
  71669. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  71670. }
  71671. }
  71672. // Bones
  71673. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71674. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71675. }
  71676. // Draw
  71677. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  71678. }
  71679. };
  71680. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  71681. var index;
  71682. if (depthOnlySubMeshes.length) {
  71683. engine.setColorWrite(false);
  71684. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  71685. renderSubMesh(depthOnlySubMeshes.data[index]);
  71686. }
  71687. engine.setColorWrite(true);
  71688. }
  71689. for (index = 0; index < opaqueSubMeshes.length; index++) {
  71690. renderSubMesh(opaqueSubMeshes.data[index]);
  71691. }
  71692. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  71693. renderSubMesh(alphaTestSubMeshes.data[index]);
  71694. }
  71695. };
  71696. };
  71697. return GeometryBufferRenderer;
  71698. }());
  71699. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  71700. })(BABYLON || (BABYLON = {}));
  71701. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  71702. "use strict";
  71703. var BABYLON;
  71704. (function (BABYLON) {
  71705. var RefractionPostProcess = /** @class */ (function (_super) {
  71706. __extends(RefractionPostProcess, _super);
  71707. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  71708. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  71709. _this.color = color;
  71710. _this.depth = depth;
  71711. _this.colorLevel = colorLevel;
  71712. _this._ownRefractionTexture = true;
  71713. _this.onActivateObservable.add(function (cam) {
  71714. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  71715. });
  71716. _this.onApplyObservable.add(function (effect) {
  71717. effect.setColor3("baseColor", _this.color);
  71718. effect.setFloat("depth", _this.depth);
  71719. effect.setFloat("colorLevel", _this.colorLevel);
  71720. effect.setTexture("refractionSampler", _this._refTexture);
  71721. });
  71722. return _this;
  71723. }
  71724. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  71725. /**
  71726. * Gets or sets the refraction texture
  71727. * Please note that you are responsible for disposing the texture if you set it manually
  71728. */
  71729. get: function () {
  71730. return this._refTexture;
  71731. },
  71732. set: function (value) {
  71733. if (this._refTexture && this._ownRefractionTexture) {
  71734. this._refTexture.dispose();
  71735. }
  71736. this._refTexture = value;
  71737. this._ownRefractionTexture = false;
  71738. },
  71739. enumerable: true,
  71740. configurable: true
  71741. });
  71742. // Methods
  71743. RefractionPostProcess.prototype.dispose = function (camera) {
  71744. if (this._refTexture && this._ownRefractionTexture) {
  71745. this._refTexture.dispose();
  71746. this._refTexture = null;
  71747. }
  71748. _super.prototype.dispose.call(this, camera);
  71749. };
  71750. return RefractionPostProcess;
  71751. }(BABYLON.PostProcess));
  71752. BABYLON.RefractionPostProcess = RefractionPostProcess;
  71753. })(BABYLON || (BABYLON = {}));
  71754. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  71755. "use strict";
  71756. var BABYLON;
  71757. (function (BABYLON) {
  71758. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  71759. __extends(BlackAndWhitePostProcess, _super);
  71760. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  71761. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  71762. _this.degree = 1;
  71763. _this.onApplyObservable.add(function (effect) {
  71764. effect.setFloat("degree", _this.degree);
  71765. });
  71766. return _this;
  71767. }
  71768. return BlackAndWhitePostProcess;
  71769. }(BABYLON.PostProcess));
  71770. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  71771. })(BABYLON || (BABYLON = {}));
  71772. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  71773. "use strict";
  71774. var BABYLON;
  71775. (function (BABYLON) {
  71776. /**
  71777. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  71778. * input texture to perform effects such as edge detection or sharpening
  71779. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  71780. */
  71781. var ConvolutionPostProcess = /** @class */ (function (_super) {
  71782. __extends(ConvolutionPostProcess, _super);
  71783. /**
  71784. * Creates a new instance ConvolutionPostProcess
  71785. * @param name The name of the effect.
  71786. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  71787. * @param options The required width/height ratio to downsize to before computing the render pass.
  71788. * @param camera The camera to apply the render pass to.
  71789. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  71790. * @param engine The engine which the post process will be applied. (default: current engine)
  71791. * @param reusable If the post process can be reused on the same frame. (default: false)
  71792. * @param textureType Type of textures used when performing the post process. (default: 0)
  71793. */
  71794. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  71795. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71796. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  71797. _this.kernel = kernel;
  71798. _this.onApply = function (effect) {
  71799. effect.setFloat2("screenSize", _this.width, _this.height);
  71800. effect.setArray("kernel", _this.kernel);
  71801. };
  71802. return _this;
  71803. }
  71804. // Statics
  71805. /**
  71806. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71807. */
  71808. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  71809. /**
  71810. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71811. */
  71812. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  71813. /**
  71814. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71815. */
  71816. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  71817. /**
  71818. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71819. */
  71820. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  71821. /**
  71822. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71823. */
  71824. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  71825. /**
  71826. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71827. */
  71828. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  71829. return ConvolutionPostProcess;
  71830. }(BABYLON.PostProcess));
  71831. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  71832. })(BABYLON || (BABYLON = {}));
  71833. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  71834. "use strict";
  71835. var BABYLON;
  71836. (function (BABYLON) {
  71837. var FilterPostProcess = /** @class */ (function (_super) {
  71838. __extends(FilterPostProcess, _super);
  71839. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  71840. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  71841. _this.kernelMatrix = kernelMatrix;
  71842. _this.onApply = function (effect) {
  71843. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  71844. };
  71845. return _this;
  71846. }
  71847. return FilterPostProcess;
  71848. }(BABYLON.PostProcess));
  71849. BABYLON.FilterPostProcess = FilterPostProcess;
  71850. })(BABYLON || (BABYLON = {}));
  71851. //# sourceMappingURL=babylon.filterPostProcess.js.map
  71852. "use strict";
  71853. var BABYLON;
  71854. (function (BABYLON) {
  71855. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  71856. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  71857. __extends(VolumetricLightScatteringPostProcess, _super);
  71858. /**
  71859. * @constructor
  71860. * @param {string} name - The post-process name
  71861. * @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)
  71862. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  71863. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  71864. * @param {number} samples - The post-process quality, default 100
  71865. * @param {number} samplingMode - The post-process filtering mode
  71866. * @param {BABYLON.Engine} engine - The babylon engine
  71867. * @param {boolean} reusable - If the post-process is reusable
  71868. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  71869. */
  71870. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  71871. if (samples === void 0) { samples = 100; }
  71872. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  71873. 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;
  71874. _this._screenCoordinates = BABYLON.Vector2.Zero();
  71875. /**
  71876. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  71877. */
  71878. _this.customMeshPosition = BABYLON.Vector3.Zero();
  71879. /**
  71880. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  71881. */
  71882. _this.useCustomMeshPosition = false;
  71883. /**
  71884. * If the post-process should inverse the light scattering direction
  71885. */
  71886. _this.invert = true;
  71887. /**
  71888. * Array containing the excluded meshes not rendered in the internal pass
  71889. */
  71890. _this.excludedMeshes = new Array();
  71891. /**
  71892. * Controls the overall intensity of the post-process
  71893. */
  71894. _this.exposure = 0.3;
  71895. /**
  71896. * Dissipates each sample's contribution in range [0, 1]
  71897. */
  71898. _this.decay = 0.96815;
  71899. /**
  71900. * Controls the overall intensity of each sample
  71901. */
  71902. _this.weight = 0.58767;
  71903. /**
  71904. * Controls the density of each sample
  71905. */
  71906. _this.density = 0.926;
  71907. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  71908. engine = scene.getEngine();
  71909. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  71910. // Configure mesh
  71911. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  71912. // Configure
  71913. _this._createPass(scene, ratio.passRatio || ratio);
  71914. _this.onActivate = function (camera) {
  71915. if (!_this.isSupported) {
  71916. _this.dispose(camera);
  71917. }
  71918. _this.onActivate = null;
  71919. };
  71920. _this.onApplyObservable.add(function (effect) {
  71921. _this._updateMeshScreenCoordinates(scene);
  71922. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  71923. effect.setFloat("exposure", _this.exposure);
  71924. effect.setFloat("decay", _this.decay);
  71925. effect.setFloat("weight", _this.weight);
  71926. effect.setFloat("density", _this.density);
  71927. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  71928. });
  71929. return _this;
  71930. }
  71931. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  71932. get: function () {
  71933. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  71934. return false;
  71935. },
  71936. set: function (useDiffuseColor) {
  71937. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  71938. },
  71939. enumerable: true,
  71940. configurable: true
  71941. });
  71942. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  71943. return "VolumetricLightScatteringPostProcess";
  71944. };
  71945. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  71946. var mesh = subMesh.getMesh();
  71947. // Render this.mesh as default
  71948. if (mesh === this.mesh && mesh.material) {
  71949. return mesh.material.isReady(mesh);
  71950. }
  71951. var defines = [];
  71952. var attribs = [BABYLON.VertexBuffer.PositionKind];
  71953. var material = subMesh.getMaterial();
  71954. // Alpha test
  71955. if (material) {
  71956. if (material.needAlphaTesting()) {
  71957. defines.push("#define ALPHATEST");
  71958. }
  71959. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71960. attribs.push(BABYLON.VertexBuffer.UVKind);
  71961. defines.push("#define UV1");
  71962. }
  71963. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  71964. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71965. defines.push("#define UV2");
  71966. }
  71967. }
  71968. // Bones
  71969. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71970. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71971. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71972. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71973. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  71974. }
  71975. else {
  71976. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71977. }
  71978. // Instances
  71979. if (useInstances) {
  71980. defines.push("#define INSTANCES");
  71981. attribs.push("world0");
  71982. attribs.push("world1");
  71983. attribs.push("world2");
  71984. attribs.push("world3");
  71985. }
  71986. // Get correct effect
  71987. var join = defines.join("\n");
  71988. if (this._cachedDefines !== join) {
  71989. this._cachedDefines = join;
  71990. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  71991. }
  71992. return this._volumetricLightScatteringPass.isReady();
  71993. };
  71994. /**
  71995. * Sets the new light position for light scattering effect
  71996. * @param {BABYLON.Vector3} The new custom light position
  71997. */
  71998. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  71999. this.customMeshPosition = position;
  72000. };
  72001. /**
  72002. * Returns the light position for light scattering effect
  72003. * @return {BABYLON.Vector3} The custom light position
  72004. */
  72005. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  72006. return this.customMeshPosition;
  72007. };
  72008. /**
  72009. * Disposes the internal assets and detaches the post-process from the camera
  72010. */
  72011. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  72012. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  72013. if (rttIndex !== -1) {
  72014. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  72015. }
  72016. this._volumetricLightScatteringRTT.dispose();
  72017. _super.prototype.dispose.call(this, camera);
  72018. };
  72019. /**
  72020. * Returns the render target texture used by the post-process
  72021. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  72022. */
  72023. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  72024. return this._volumetricLightScatteringRTT;
  72025. };
  72026. // Private methods
  72027. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  72028. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  72029. return true;
  72030. }
  72031. return false;
  72032. };
  72033. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  72034. var _this = this;
  72035. var engine = scene.getEngine();
  72036. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  72037. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72038. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72039. this._volumetricLightScatteringRTT.renderList = null;
  72040. this._volumetricLightScatteringRTT.renderParticles = false;
  72041. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  72042. var camera = this.getCamera();
  72043. if (camera) {
  72044. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  72045. }
  72046. else {
  72047. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  72048. }
  72049. // Custom render function for submeshes
  72050. var renderSubMesh = function (subMesh) {
  72051. var mesh = subMesh.getRenderingMesh();
  72052. if (_this._meshExcluded(mesh)) {
  72053. return;
  72054. }
  72055. var material = subMesh.getMaterial();
  72056. if (!material) {
  72057. return;
  72058. }
  72059. var scene = mesh.getScene();
  72060. var engine = scene.getEngine();
  72061. // Culling
  72062. engine.setState(material.backFaceCulling);
  72063. // Managing instances
  72064. var batch = mesh._getInstancesRenderList(subMesh._id);
  72065. if (batch.mustReturn) {
  72066. return;
  72067. }
  72068. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  72069. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  72070. var effect = _this._volumetricLightScatteringPass;
  72071. if (mesh === _this.mesh) {
  72072. if (subMesh.effect) {
  72073. effect = subMesh.effect;
  72074. }
  72075. else {
  72076. effect = material.getEffect();
  72077. }
  72078. }
  72079. engine.enableEffect(effect);
  72080. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  72081. if (mesh === _this.mesh) {
  72082. material.bind(mesh.getWorldMatrix(), mesh);
  72083. }
  72084. else {
  72085. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  72086. // Alpha test
  72087. if (material && material.needAlphaTesting()) {
  72088. var alphaTexture = material.getAlphaTestTexture();
  72089. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  72090. if (alphaTexture) {
  72091. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  72092. }
  72093. }
  72094. // Bones
  72095. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  72096. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  72097. }
  72098. }
  72099. // Draw
  72100. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  72101. }
  72102. };
  72103. // Render target texture callbacks
  72104. var savedSceneClearColor;
  72105. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  72106. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  72107. savedSceneClearColor = scene.clearColor;
  72108. scene.clearColor = sceneClearColor;
  72109. });
  72110. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  72111. scene.clearColor = savedSceneClearColor;
  72112. });
  72113. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72114. var engine = scene.getEngine();
  72115. var index;
  72116. if (depthOnlySubMeshes.length) {
  72117. engine.setColorWrite(false);
  72118. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72119. renderSubMesh(depthOnlySubMeshes.data[index]);
  72120. }
  72121. engine.setColorWrite(true);
  72122. }
  72123. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72124. renderSubMesh(opaqueSubMeshes.data[index]);
  72125. }
  72126. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72127. renderSubMesh(alphaTestSubMeshes.data[index]);
  72128. }
  72129. if (transparentSubMeshes.length) {
  72130. // Sort sub meshes
  72131. for (index = 0; index < transparentSubMeshes.length; index++) {
  72132. var submesh = transparentSubMeshes.data[index];
  72133. var boundingInfo = submesh.getBoundingInfo();
  72134. if (boundingInfo && scene.activeCamera) {
  72135. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  72136. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  72137. }
  72138. }
  72139. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  72140. sortedArray.sort(function (a, b) {
  72141. // Alpha index first
  72142. if (a._alphaIndex > b._alphaIndex) {
  72143. return 1;
  72144. }
  72145. if (a._alphaIndex < b._alphaIndex) {
  72146. return -1;
  72147. }
  72148. // Then distance to camera
  72149. if (a._distanceToCamera < b._distanceToCamera) {
  72150. return 1;
  72151. }
  72152. if (a._distanceToCamera > b._distanceToCamera) {
  72153. return -1;
  72154. }
  72155. return 0;
  72156. });
  72157. // Render sub meshes
  72158. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  72159. for (index = 0; index < sortedArray.length; index++) {
  72160. renderSubMesh(sortedArray[index]);
  72161. }
  72162. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  72163. }
  72164. };
  72165. };
  72166. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  72167. var transform = scene.getTransformMatrix();
  72168. var meshPosition;
  72169. if (this.useCustomMeshPosition) {
  72170. meshPosition = this.customMeshPosition;
  72171. }
  72172. else if (this.attachedNode) {
  72173. meshPosition = this.attachedNode.position;
  72174. }
  72175. else {
  72176. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  72177. }
  72178. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  72179. this._screenCoordinates.x = pos.x / this._viewPort.width;
  72180. this._screenCoordinates.y = pos.y / this._viewPort.height;
  72181. if (this.invert)
  72182. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  72183. };
  72184. // Static methods
  72185. /**
  72186. * Creates a default mesh for the Volumeric Light Scattering post-process
  72187. * @param {string} The mesh name
  72188. * @param {BABYLON.Scene} The scene where to create the mesh
  72189. * @return {BABYLON.Mesh} the default mesh
  72190. */
  72191. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  72192. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  72193. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  72194. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  72195. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  72196. mesh.material = material;
  72197. return mesh;
  72198. };
  72199. __decorate([
  72200. BABYLON.serializeAsVector3()
  72201. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  72202. __decorate([
  72203. BABYLON.serialize()
  72204. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  72205. __decorate([
  72206. BABYLON.serialize()
  72207. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  72208. __decorate([
  72209. BABYLON.serializeAsMeshReference()
  72210. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  72211. __decorate([
  72212. BABYLON.serialize()
  72213. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  72214. __decorate([
  72215. BABYLON.serialize()
  72216. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  72217. __decorate([
  72218. BABYLON.serialize()
  72219. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  72220. __decorate([
  72221. BABYLON.serialize()
  72222. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  72223. __decorate([
  72224. BABYLON.serialize()
  72225. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  72226. return VolumetricLightScatteringPostProcess;
  72227. }(BABYLON.PostProcess));
  72228. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  72229. })(BABYLON || (BABYLON = {}));
  72230. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  72231. "use strict";
  72232. //
  72233. // This post-process allows the modification of rendered colors by using
  72234. // a 'look-up table' (LUT). This effect is also called Color Grading.
  72235. //
  72236. // The object needs to be provided an url to a texture containing the color
  72237. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  72238. // Use an image editing software to tweak the LUT to match your needs.
  72239. //
  72240. // For an example of a color LUT, see here:
  72241. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  72242. // For explanations on color grading, see here:
  72243. // http://udn.epicgames.com/Three/ColorGrading.html
  72244. //
  72245. var BABYLON;
  72246. (function (BABYLON) {
  72247. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  72248. __extends(ColorCorrectionPostProcess, _super);
  72249. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  72250. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  72251. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  72252. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  72253. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72254. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72255. _this.onApply = function (effect) {
  72256. effect.setTexture("colorTable", _this._colorTableTexture);
  72257. };
  72258. return _this;
  72259. }
  72260. return ColorCorrectionPostProcess;
  72261. }(BABYLON.PostProcess));
  72262. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  72263. })(BABYLON || (BABYLON = {}));
  72264. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  72265. "use strict";
  72266. var BABYLON;
  72267. (function (BABYLON) {
  72268. var TonemappingOperator;
  72269. (function (TonemappingOperator) {
  72270. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  72271. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  72272. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  72273. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  72274. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  72275. ;
  72276. var TonemapPostProcess = /** @class */ (function (_super) {
  72277. __extends(TonemapPostProcess, _super);
  72278. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  72279. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  72280. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72281. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  72282. _this._operator = _operator;
  72283. _this.exposureAdjustment = exposureAdjustment;
  72284. var defines = "#define ";
  72285. if (_this._operator === TonemappingOperator.Hable)
  72286. defines += "HABLE_TONEMAPPING";
  72287. else if (_this._operator === TonemappingOperator.Reinhard)
  72288. defines += "REINHARD_TONEMAPPING";
  72289. else if (_this._operator === TonemappingOperator.HejiDawson)
  72290. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  72291. else if (_this._operator === TonemappingOperator.Photographic)
  72292. defines += "PHOTOGRAPHIC_TONEMAPPING";
  72293. //sadly a second call to create the effect.
  72294. _this.updateEffect(defines);
  72295. _this.onApply = function (effect) {
  72296. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  72297. };
  72298. return _this;
  72299. }
  72300. return TonemapPostProcess;
  72301. }(BABYLON.PostProcess));
  72302. BABYLON.TonemapPostProcess = TonemapPostProcess;
  72303. })(BABYLON || (BABYLON = {}));
  72304. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  72305. "use strict";
  72306. var BABYLON;
  72307. (function (BABYLON) {
  72308. var DisplayPassPostProcess = /** @class */ (function (_super) {
  72309. __extends(DisplayPassPostProcess, _super);
  72310. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  72311. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  72312. }
  72313. return DisplayPassPostProcess;
  72314. }(BABYLON.PostProcess));
  72315. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  72316. })(BABYLON || (BABYLON = {}));
  72317. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  72318. "use strict";
  72319. var BABYLON;
  72320. (function (BABYLON) {
  72321. var HighlightsPostProcess = /** @class */ (function (_super) {
  72322. __extends(HighlightsPostProcess, _super);
  72323. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  72324. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72325. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  72326. }
  72327. return HighlightsPostProcess;
  72328. }(BABYLON.PostProcess));
  72329. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  72330. })(BABYLON || (BABYLON = {}));
  72331. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  72332. "use strict";
  72333. var BABYLON;
  72334. (function (BABYLON) {
  72335. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  72336. __extends(ImageProcessingPostProcess, _super);
  72337. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  72338. if (camera === void 0) { camera = null; }
  72339. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72340. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  72341. _this._fromLinearSpace = true;
  72342. /**
  72343. * Defines cache preventing GC.
  72344. */
  72345. _this._defines = {
  72346. IMAGEPROCESSING: false,
  72347. VIGNETTE: false,
  72348. VIGNETTEBLENDMODEMULTIPLY: false,
  72349. VIGNETTEBLENDMODEOPAQUE: false,
  72350. TONEMAPPING: false,
  72351. CONTRAST: false,
  72352. COLORCURVES: false,
  72353. COLORGRADING: false,
  72354. COLORGRADING3D: false,
  72355. FROMLINEARSPACE: false,
  72356. SAMPLER3DGREENDEPTH: false,
  72357. SAMPLER3DBGRMAP: false,
  72358. IMAGEPROCESSINGPOSTPROCESS: false,
  72359. EXPOSURE: false,
  72360. };
  72361. // Setup the configuration as forced by the constructor. This would then not force the
  72362. // scene materials output in linear space and let untouched the default forward pass.
  72363. if (imageProcessingConfiguration) {
  72364. imageProcessingConfiguration.applyByPostProcess = true;
  72365. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  72366. // This will cause the shader to be compiled
  72367. _this.fromLinearSpace = false;
  72368. }
  72369. else {
  72370. _this._attachImageProcessingConfiguration(null, true);
  72371. _this.imageProcessingConfiguration.applyByPostProcess = true;
  72372. }
  72373. _this.onApply = function (effect) {
  72374. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  72375. };
  72376. return _this;
  72377. }
  72378. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  72379. /**
  72380. * Gets the image processing configuration used either in this material.
  72381. */
  72382. get: function () {
  72383. return this._imageProcessingConfiguration;
  72384. },
  72385. /**
  72386. * Sets the Default image processing configuration used either in the this material.
  72387. *
  72388. * If sets to null, the scene one is in use.
  72389. */
  72390. set: function (value) {
  72391. this._attachImageProcessingConfiguration(value);
  72392. },
  72393. enumerable: true,
  72394. configurable: true
  72395. });
  72396. /**
  72397. * Attaches a new image processing configuration to the PBR Material.
  72398. * @param configuration
  72399. */
  72400. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  72401. var _this = this;
  72402. if (doNotBuild === void 0) { doNotBuild = false; }
  72403. if (configuration === this._imageProcessingConfiguration) {
  72404. return;
  72405. }
  72406. // Detaches observer.
  72407. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  72408. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  72409. }
  72410. // Pick the scene configuration if needed.
  72411. if (!configuration) {
  72412. var scene = null;
  72413. var engine = this.getEngine();
  72414. var camera = this.getCamera();
  72415. if (camera) {
  72416. scene = camera.getScene();
  72417. }
  72418. else if (engine && engine.scenes) {
  72419. var scenes = engine.scenes;
  72420. scene = scenes[scenes.length - 1];
  72421. }
  72422. else {
  72423. scene = BABYLON.Engine.LastCreatedScene;
  72424. }
  72425. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  72426. }
  72427. else {
  72428. this._imageProcessingConfiguration = configuration;
  72429. }
  72430. // Attaches observer.
  72431. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  72432. _this._updateParameters();
  72433. });
  72434. // Ensure the effect will be rebuilt.
  72435. if (!doNotBuild) {
  72436. this._updateParameters();
  72437. }
  72438. };
  72439. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  72440. /**
  72441. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  72442. */
  72443. get: function () {
  72444. return this.imageProcessingConfiguration.colorCurves;
  72445. },
  72446. /**
  72447. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  72448. */
  72449. set: function (value) {
  72450. this.imageProcessingConfiguration.colorCurves = value;
  72451. },
  72452. enumerable: true,
  72453. configurable: true
  72454. });
  72455. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  72456. /**
  72457. * Gets wether the color curves effect is enabled.
  72458. */
  72459. get: function () {
  72460. return this.imageProcessingConfiguration.colorCurvesEnabled;
  72461. },
  72462. /**
  72463. * Sets wether the color curves effect is enabled.
  72464. */
  72465. set: function (value) {
  72466. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  72467. },
  72468. enumerable: true,
  72469. configurable: true
  72470. });
  72471. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  72472. /**
  72473. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  72474. */
  72475. get: function () {
  72476. return this.imageProcessingConfiguration.colorGradingTexture;
  72477. },
  72478. /**
  72479. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  72480. */
  72481. set: function (value) {
  72482. this.imageProcessingConfiguration.colorGradingTexture = value;
  72483. },
  72484. enumerable: true,
  72485. configurable: true
  72486. });
  72487. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  72488. /**
  72489. * Gets wether the color grading effect is enabled.
  72490. */
  72491. get: function () {
  72492. return this.imageProcessingConfiguration.colorGradingEnabled;
  72493. },
  72494. /**
  72495. * Gets wether the color grading effect is enabled.
  72496. */
  72497. set: function (value) {
  72498. this.imageProcessingConfiguration.colorGradingEnabled = value;
  72499. },
  72500. enumerable: true,
  72501. configurable: true
  72502. });
  72503. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  72504. /**
  72505. * Gets exposure used in the effect.
  72506. */
  72507. get: function () {
  72508. return this.imageProcessingConfiguration.exposure;
  72509. },
  72510. /**
  72511. * Sets exposure used in the effect.
  72512. */
  72513. set: function (value) {
  72514. this.imageProcessingConfiguration.exposure = value;
  72515. },
  72516. enumerable: true,
  72517. configurable: true
  72518. });
  72519. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  72520. /**
  72521. * Gets wether tonemapping is enabled or not.
  72522. */
  72523. get: function () {
  72524. return this._imageProcessingConfiguration.toneMappingEnabled;
  72525. },
  72526. /**
  72527. * Sets wether tonemapping is enabled or not
  72528. */
  72529. set: function (value) {
  72530. this._imageProcessingConfiguration.toneMappingEnabled = value;
  72531. },
  72532. enumerable: true,
  72533. configurable: true
  72534. });
  72535. ;
  72536. ;
  72537. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  72538. /**
  72539. * Gets contrast used in the effect.
  72540. */
  72541. get: function () {
  72542. return this.imageProcessingConfiguration.contrast;
  72543. },
  72544. /**
  72545. * Sets contrast used in the effect.
  72546. */
  72547. set: function (value) {
  72548. this.imageProcessingConfiguration.contrast = value;
  72549. },
  72550. enumerable: true,
  72551. configurable: true
  72552. });
  72553. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  72554. /**
  72555. * Gets Vignette stretch size.
  72556. */
  72557. get: function () {
  72558. return this.imageProcessingConfiguration.vignetteStretch;
  72559. },
  72560. /**
  72561. * Sets Vignette stretch size.
  72562. */
  72563. set: function (value) {
  72564. this.imageProcessingConfiguration.vignetteStretch = value;
  72565. },
  72566. enumerable: true,
  72567. configurable: true
  72568. });
  72569. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  72570. /**
  72571. * Gets Vignette centre X Offset.
  72572. */
  72573. get: function () {
  72574. return this.imageProcessingConfiguration.vignetteCentreX;
  72575. },
  72576. /**
  72577. * Sets Vignette centre X Offset.
  72578. */
  72579. set: function (value) {
  72580. this.imageProcessingConfiguration.vignetteCentreX = value;
  72581. },
  72582. enumerable: true,
  72583. configurable: true
  72584. });
  72585. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  72586. /**
  72587. * Gets Vignette centre Y Offset.
  72588. */
  72589. get: function () {
  72590. return this.imageProcessingConfiguration.vignetteCentreY;
  72591. },
  72592. /**
  72593. * Sets Vignette centre Y Offset.
  72594. */
  72595. set: function (value) {
  72596. this.imageProcessingConfiguration.vignetteCentreY = value;
  72597. },
  72598. enumerable: true,
  72599. configurable: true
  72600. });
  72601. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  72602. /**
  72603. * Gets Vignette weight or intensity of the vignette effect.
  72604. */
  72605. get: function () {
  72606. return this.imageProcessingConfiguration.vignetteWeight;
  72607. },
  72608. /**
  72609. * Sets Vignette weight or intensity of the vignette effect.
  72610. */
  72611. set: function (value) {
  72612. this.imageProcessingConfiguration.vignetteWeight = value;
  72613. },
  72614. enumerable: true,
  72615. configurable: true
  72616. });
  72617. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  72618. /**
  72619. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  72620. * if vignetteEnabled is set to true.
  72621. */
  72622. get: function () {
  72623. return this.imageProcessingConfiguration.vignetteColor;
  72624. },
  72625. /**
  72626. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  72627. * if vignetteEnabled is set to true.
  72628. */
  72629. set: function (value) {
  72630. this.imageProcessingConfiguration.vignetteColor = value;
  72631. },
  72632. enumerable: true,
  72633. configurable: true
  72634. });
  72635. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  72636. /**
  72637. * Gets Camera field of view used by the Vignette effect.
  72638. */
  72639. get: function () {
  72640. return this.imageProcessingConfiguration.vignetteCameraFov;
  72641. },
  72642. /**
  72643. * Sets Camera field of view used by the Vignette effect.
  72644. */
  72645. set: function (value) {
  72646. this.imageProcessingConfiguration.vignetteCameraFov = value;
  72647. },
  72648. enumerable: true,
  72649. configurable: true
  72650. });
  72651. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  72652. /**
  72653. * Gets the vignette blend mode allowing different kind of effect.
  72654. */
  72655. get: function () {
  72656. return this.imageProcessingConfiguration.vignetteBlendMode;
  72657. },
  72658. /**
  72659. * Sets the vignette blend mode allowing different kind of effect.
  72660. */
  72661. set: function (value) {
  72662. this.imageProcessingConfiguration.vignetteBlendMode = value;
  72663. },
  72664. enumerable: true,
  72665. configurable: true
  72666. });
  72667. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  72668. /**
  72669. * Gets wether the vignette effect is enabled.
  72670. */
  72671. get: function () {
  72672. return this.imageProcessingConfiguration.vignetteEnabled;
  72673. },
  72674. /**
  72675. * Sets wether the vignette effect is enabled.
  72676. */
  72677. set: function (value) {
  72678. this.imageProcessingConfiguration.vignetteEnabled = value;
  72679. },
  72680. enumerable: true,
  72681. configurable: true
  72682. });
  72683. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  72684. /**
  72685. * Gets wether the input of the processing is in Gamma or Linear Space.
  72686. */
  72687. get: function () {
  72688. return this._fromLinearSpace;
  72689. },
  72690. /**
  72691. * Sets wether the input of the processing is in Gamma or Linear Space.
  72692. */
  72693. set: function (value) {
  72694. if (this._fromLinearSpace === value) {
  72695. return;
  72696. }
  72697. this._fromLinearSpace = value;
  72698. this._updateParameters();
  72699. },
  72700. enumerable: true,
  72701. configurable: true
  72702. });
  72703. ImageProcessingPostProcess.prototype.getClassName = function () {
  72704. return "ImageProcessingPostProcess";
  72705. };
  72706. ImageProcessingPostProcess.prototype._updateParameters = function () {
  72707. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  72708. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  72709. var defines = "";
  72710. for (var define in this._defines) {
  72711. if (this._defines[define]) {
  72712. defines += "#define " + define + ";\r\n";
  72713. }
  72714. }
  72715. var samplers = ["textureSampler"];
  72716. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  72717. var uniforms = ["scale"];
  72718. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  72719. this.updateEffect(defines, uniforms, samplers);
  72720. };
  72721. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  72722. _super.prototype.dispose.call(this, camera);
  72723. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  72724. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  72725. }
  72726. this.imageProcessingConfiguration.applyByPostProcess = false;
  72727. };
  72728. __decorate([
  72729. BABYLON.serialize()
  72730. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  72731. return ImageProcessingPostProcess;
  72732. }(BABYLON.PostProcess));
  72733. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  72734. })(BABYLON || (BABYLON = {}));
  72735. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  72736. "use strict";
  72737. var BABYLON;
  72738. (function (BABYLON) {
  72739. var Bone = /** @class */ (function (_super) {
  72740. __extends(Bone, _super);
  72741. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  72742. if (parentBone === void 0) { parentBone = null; }
  72743. if (localMatrix === void 0) { localMatrix = null; }
  72744. if (restPose === void 0) { restPose = null; }
  72745. if (baseMatrix === void 0) { baseMatrix = null; }
  72746. if (index === void 0) { index = null; }
  72747. var _this = _super.call(this, name, skeleton.getScene()) || this;
  72748. _this.name = name;
  72749. _this.children = new Array();
  72750. _this.animations = new Array();
  72751. // Set this value to map this bone to a different index in the transform matrices.
  72752. // Set this value to -1 to exclude the bone from the transform matrices.
  72753. _this._index = null;
  72754. _this._worldTransform = new BABYLON.Matrix();
  72755. _this._absoluteTransform = new BABYLON.Matrix();
  72756. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  72757. _this._scaleMatrix = BABYLON.Matrix.Identity();
  72758. _this._scaleVector = BABYLON.Vector3.One();
  72759. _this._negateScaleChildren = BABYLON.Vector3.One();
  72760. _this._scalingDeterminant = 1;
  72761. _this._skeleton = skeleton;
  72762. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  72763. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  72764. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  72765. _this._index = index;
  72766. skeleton.bones.push(_this);
  72767. _this.setParent(parentBone, false);
  72768. _this._updateDifferenceMatrix();
  72769. return _this;
  72770. }
  72771. Object.defineProperty(Bone.prototype, "_matrix", {
  72772. get: function () {
  72773. return this._localMatrix;
  72774. },
  72775. set: function (val) {
  72776. if (this._localMatrix) {
  72777. this._localMatrix.copyFrom(val);
  72778. }
  72779. else {
  72780. this._localMatrix = val;
  72781. }
  72782. },
  72783. enumerable: true,
  72784. configurable: true
  72785. });
  72786. // Members
  72787. Bone.prototype.getSkeleton = function () {
  72788. return this._skeleton;
  72789. };
  72790. Bone.prototype.getParent = function () {
  72791. return this._parent;
  72792. };
  72793. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  72794. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  72795. if (this._parent === parent) {
  72796. return;
  72797. }
  72798. if (this._parent) {
  72799. var index = this._parent.children.indexOf(this);
  72800. if (index !== -1) {
  72801. this._parent.children.splice(index, 1);
  72802. }
  72803. }
  72804. this._parent = parent;
  72805. if (this._parent) {
  72806. this._parent.children.push(this);
  72807. }
  72808. if (updateDifferenceMatrix) {
  72809. this._updateDifferenceMatrix();
  72810. }
  72811. };
  72812. Bone.prototype.getLocalMatrix = function () {
  72813. return this._localMatrix;
  72814. };
  72815. Bone.prototype.getBaseMatrix = function () {
  72816. return this._baseMatrix;
  72817. };
  72818. Bone.prototype.getRestPose = function () {
  72819. return this._restPose;
  72820. };
  72821. Bone.prototype.returnToRest = function () {
  72822. this.updateMatrix(this._restPose.clone());
  72823. };
  72824. Bone.prototype.getWorldMatrix = function () {
  72825. return this._worldTransform;
  72826. };
  72827. Bone.prototype.getInvertedAbsoluteTransform = function () {
  72828. return this._invertedAbsoluteTransform;
  72829. };
  72830. Bone.prototype.getAbsoluteTransform = function () {
  72831. return this._absoluteTransform;
  72832. };
  72833. Object.defineProperty(Bone.prototype, "position", {
  72834. // Properties (matches AbstractMesh properties)
  72835. get: function () {
  72836. return this.getPosition();
  72837. },
  72838. set: function (newPosition) {
  72839. this.setPosition(newPosition);
  72840. },
  72841. enumerable: true,
  72842. configurable: true
  72843. });
  72844. Object.defineProperty(Bone.prototype, "rotation", {
  72845. get: function () {
  72846. return this.getRotation();
  72847. },
  72848. set: function (newRotation) {
  72849. this.setRotation(newRotation);
  72850. },
  72851. enumerable: true,
  72852. configurable: true
  72853. });
  72854. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  72855. get: function () {
  72856. return this.getRotationQuaternion();
  72857. },
  72858. set: function (newRotation) {
  72859. this.setRotationQuaternion(newRotation);
  72860. },
  72861. enumerable: true,
  72862. configurable: true
  72863. });
  72864. Object.defineProperty(Bone.prototype, "scaling", {
  72865. get: function () {
  72866. return this.getScale();
  72867. },
  72868. set: function (newScaling) {
  72869. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  72870. },
  72871. enumerable: true,
  72872. configurable: true
  72873. });
  72874. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  72875. /**
  72876. * Gets the animation properties override
  72877. */
  72878. get: function () {
  72879. return this._skeleton.animationPropertiesOverride;
  72880. },
  72881. enumerable: true,
  72882. configurable: true
  72883. });
  72884. // Methods
  72885. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  72886. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  72887. this._baseMatrix = matrix.clone();
  72888. this._localMatrix = matrix.clone();
  72889. this._skeleton._markAsDirty();
  72890. if (updateDifferenceMatrix) {
  72891. this._updateDifferenceMatrix();
  72892. }
  72893. };
  72894. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  72895. if (!rootMatrix) {
  72896. rootMatrix = this._baseMatrix;
  72897. }
  72898. if (this._parent) {
  72899. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  72900. }
  72901. else {
  72902. this._absoluteTransform.copyFrom(rootMatrix);
  72903. }
  72904. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  72905. for (var index = 0; index < this.children.length; index++) {
  72906. this.children[index]._updateDifferenceMatrix();
  72907. }
  72908. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  72909. };
  72910. Bone.prototype.markAsDirty = function () {
  72911. this._currentRenderId++;
  72912. this._childRenderId++;
  72913. this._skeleton._markAsDirty();
  72914. };
  72915. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  72916. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  72917. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  72918. // all animation may be coming from a library skeleton, so may need to create animation
  72919. if (this.animations.length === 0) {
  72920. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  72921. this.animations[0].setKeys([]);
  72922. }
  72923. // get animation info / verify there is such a range from the source bone
  72924. var sourceRange = source.animations[0].getRange(rangeName);
  72925. if (!sourceRange) {
  72926. return false;
  72927. }
  72928. var from = sourceRange.from;
  72929. var to = sourceRange.to;
  72930. var sourceKeys = source.animations[0].getKeys();
  72931. // rescaling prep
  72932. var sourceBoneLength = source.length;
  72933. var sourceParent = source.getParent();
  72934. var parent = this.getParent();
  72935. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  72936. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  72937. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  72938. var destKeys = this.animations[0].getKeys();
  72939. // loop vars declaration
  72940. var orig;
  72941. var origTranslation;
  72942. var mat;
  72943. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  72944. orig = sourceKeys[key];
  72945. if (orig.frame >= from && orig.frame <= to) {
  72946. if (rescaleAsRequired) {
  72947. mat = orig.value.clone();
  72948. // scale based on parent ratio, when bone has parent
  72949. if (parentScalingReqd) {
  72950. origTranslation = mat.getTranslation();
  72951. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  72952. // scale based on skeleton dimension ratio when root bone, and value is passed
  72953. }
  72954. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  72955. origTranslation = mat.getTranslation();
  72956. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  72957. // use original when root bone, and no data for skelDimensionsRatio
  72958. }
  72959. else {
  72960. mat = orig.value;
  72961. }
  72962. }
  72963. else {
  72964. mat = orig.value;
  72965. }
  72966. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  72967. }
  72968. }
  72969. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  72970. return true;
  72971. };
  72972. /**
  72973. * Translate the bone in local or world space.
  72974. * @param vec The amount to translate the bone.
  72975. * @param space The space that the translation is in.
  72976. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72977. */
  72978. Bone.prototype.translate = function (vec, space, mesh) {
  72979. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72980. var lm = this.getLocalMatrix();
  72981. if (space == BABYLON.Space.LOCAL) {
  72982. lm.m[12] += vec.x;
  72983. lm.m[13] += vec.y;
  72984. lm.m[14] += vec.z;
  72985. }
  72986. else {
  72987. var wm = null;
  72988. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72989. if (mesh) {
  72990. wm = mesh.getWorldMatrix();
  72991. }
  72992. this._skeleton.computeAbsoluteTransforms();
  72993. var tmat = Bone._tmpMats[0];
  72994. var tvec = Bone._tmpVecs[0];
  72995. if (this._parent) {
  72996. if (mesh && wm) {
  72997. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72998. tmat.multiplyToRef(wm, tmat);
  72999. }
  73000. else {
  73001. tmat.copyFrom(this._parent.getAbsoluteTransform());
  73002. }
  73003. }
  73004. tmat.m[12] = 0;
  73005. tmat.m[13] = 0;
  73006. tmat.m[14] = 0;
  73007. tmat.invert();
  73008. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  73009. lm.m[12] += tvec.x;
  73010. lm.m[13] += tvec.y;
  73011. lm.m[14] += tvec.z;
  73012. }
  73013. this.markAsDirty();
  73014. };
  73015. /**
  73016. * Set the postion of the bone in local or world space.
  73017. * @param position The position to set the bone.
  73018. * @param space The space that the position is in.
  73019. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73020. */
  73021. Bone.prototype.setPosition = function (position, space, mesh) {
  73022. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73023. var lm = this.getLocalMatrix();
  73024. if (space == BABYLON.Space.LOCAL) {
  73025. lm.m[12] = position.x;
  73026. lm.m[13] = position.y;
  73027. lm.m[14] = position.z;
  73028. }
  73029. else {
  73030. var wm = null;
  73031. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73032. if (mesh) {
  73033. wm = mesh.getWorldMatrix();
  73034. }
  73035. this._skeleton.computeAbsoluteTransforms();
  73036. var tmat = Bone._tmpMats[0];
  73037. var vec = Bone._tmpVecs[0];
  73038. if (this._parent) {
  73039. if (mesh && wm) {
  73040. tmat.copyFrom(this._parent.getAbsoluteTransform());
  73041. tmat.multiplyToRef(wm, tmat);
  73042. }
  73043. else {
  73044. tmat.copyFrom(this._parent.getAbsoluteTransform());
  73045. }
  73046. }
  73047. tmat.invert();
  73048. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  73049. lm.m[12] = vec.x;
  73050. lm.m[13] = vec.y;
  73051. lm.m[14] = vec.z;
  73052. }
  73053. this.markAsDirty();
  73054. };
  73055. /**
  73056. * Set the absolute postion of the bone (world space).
  73057. * @param position The position to set the bone.
  73058. * @param mesh The mesh that this bone is attached to.
  73059. */
  73060. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  73061. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  73062. };
  73063. /**
  73064. * Set the scale of the bone on the x, y and z axes.
  73065. * @param x The scale of the bone on the x axis.
  73066. * @param x The scale of the bone on the y axis.
  73067. * @param z The scale of the bone on the z axis.
  73068. * @param scaleChildren Set this to true if children of the bone should be scaled.
  73069. */
  73070. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  73071. if (scaleChildren === void 0) { scaleChildren = false; }
  73072. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  73073. if (!scaleChildren) {
  73074. this._negateScaleChildren.x = 1 / x;
  73075. this._negateScaleChildren.y = 1 / y;
  73076. this._negateScaleChildren.z = 1 / z;
  73077. }
  73078. this._syncScaleVector();
  73079. }
  73080. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  73081. };
  73082. /**
  73083. * Scale the bone on the x, y and z axes.
  73084. * @param x The amount to scale the bone on the x axis.
  73085. * @param x The amount to scale the bone on the y axis.
  73086. * @param z The amount to scale the bone on the z axis.
  73087. * @param scaleChildren Set this to true if children of the bone should be scaled.
  73088. */
  73089. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  73090. if (scaleChildren === void 0) { scaleChildren = false; }
  73091. var locMat = this.getLocalMatrix();
  73092. var origLocMat = Bone._tmpMats[0];
  73093. origLocMat.copyFrom(locMat);
  73094. var origLocMatInv = Bone._tmpMats[1];
  73095. origLocMatInv.copyFrom(origLocMat);
  73096. origLocMatInv.invert();
  73097. var scaleMat = Bone._tmpMats[2];
  73098. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  73099. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  73100. this._scaleVector.x *= x;
  73101. this._scaleVector.y *= y;
  73102. this._scaleVector.z *= z;
  73103. locMat.multiplyToRef(origLocMatInv, locMat);
  73104. locMat.multiplyToRef(scaleMat, locMat);
  73105. locMat.multiplyToRef(origLocMat, locMat);
  73106. var parent = this.getParent();
  73107. if (parent) {
  73108. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  73109. }
  73110. else {
  73111. this.getAbsoluteTransform().copyFrom(locMat);
  73112. }
  73113. var len = this.children.length;
  73114. scaleMat.invert();
  73115. for (var i = 0; i < len; i++) {
  73116. var child = this.children[i];
  73117. var cm = child.getLocalMatrix();
  73118. cm.multiplyToRef(scaleMat, cm);
  73119. var lm = child.getLocalMatrix();
  73120. lm.m[12] *= x;
  73121. lm.m[13] *= y;
  73122. lm.m[14] *= z;
  73123. }
  73124. this.computeAbsoluteTransforms();
  73125. if (scaleChildren) {
  73126. for (var i = 0; i < len; i++) {
  73127. this.children[i].scale(x, y, z, scaleChildren);
  73128. }
  73129. }
  73130. this.markAsDirty();
  73131. };
  73132. /**
  73133. * Set the yaw, pitch, and roll of the bone in local or world space.
  73134. * @param yaw The rotation of the bone on the y axis.
  73135. * @param pitch The rotation of the bone on the x axis.
  73136. * @param roll The rotation of the bone on the z axis.
  73137. * @param space The space that the axes of rotation are in.
  73138. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73139. */
  73140. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  73141. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73142. var rotMat = Bone._tmpMats[0];
  73143. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  73144. var rotMatInv = Bone._tmpMats[1];
  73145. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  73146. rotMatInv.multiplyToRef(rotMat, rotMat);
  73147. this._rotateWithMatrix(rotMat, space, mesh);
  73148. };
  73149. /**
  73150. * Rotate the bone on an axis in local or world space.
  73151. * @param axis The axis to rotate the bone on.
  73152. * @param amount The amount to rotate the bone.
  73153. * @param space The space that the axis is in.
  73154. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73155. */
  73156. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  73157. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73158. var rmat = Bone._tmpMats[0];
  73159. rmat.m[12] = 0;
  73160. rmat.m[13] = 0;
  73161. rmat.m[14] = 0;
  73162. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  73163. this._rotateWithMatrix(rmat, space, mesh);
  73164. };
  73165. /**
  73166. * Set the rotation of the bone to a particular axis angle in local or world space.
  73167. * @param axis The axis to rotate the bone on.
  73168. * @param angle The angle that the bone should be rotated to.
  73169. * @param space The space that the axis is in.
  73170. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73171. */
  73172. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  73173. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73174. var rotMat = Bone._tmpMats[0];
  73175. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  73176. var rotMatInv = Bone._tmpMats[1];
  73177. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  73178. rotMatInv.multiplyToRef(rotMat, rotMat);
  73179. this._rotateWithMatrix(rotMat, space, mesh);
  73180. };
  73181. /**
  73182. * Set the euler rotation of the bone in local of world space.
  73183. * @param rotation The euler rotation that the bone should be set to.
  73184. * @param space The space that the rotation is in.
  73185. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73186. */
  73187. Bone.prototype.setRotation = function (rotation, space, mesh) {
  73188. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73189. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  73190. };
  73191. /**
  73192. * Set the quaternion rotation of the bone in local of world space.
  73193. * @param quat The quaternion rotation that the bone should be set to.
  73194. * @param space The space that the rotation is in.
  73195. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73196. */
  73197. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  73198. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73199. var rotMatInv = Bone._tmpMats[0];
  73200. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  73201. var rotMat = Bone._tmpMats[1];
  73202. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  73203. rotMatInv.multiplyToRef(rotMat, rotMat);
  73204. this._rotateWithMatrix(rotMat, space, mesh);
  73205. };
  73206. /**
  73207. * Set the rotation matrix of the bone in local of world space.
  73208. * @param rotMat The rotation matrix that the bone should be set to.
  73209. * @param space The space that the rotation is in.
  73210. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73211. */
  73212. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  73213. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73214. var rotMatInv = Bone._tmpMats[0];
  73215. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  73216. var rotMat2 = Bone._tmpMats[1];
  73217. rotMat2.copyFrom(rotMat);
  73218. rotMatInv.multiplyToRef(rotMat, rotMat2);
  73219. this._rotateWithMatrix(rotMat2, space, mesh);
  73220. };
  73221. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  73222. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73223. var lmat = this.getLocalMatrix();
  73224. var lx = lmat.m[12];
  73225. var ly = lmat.m[13];
  73226. var lz = lmat.m[14];
  73227. var parent = this.getParent();
  73228. var parentScale = Bone._tmpMats[3];
  73229. var parentScaleInv = Bone._tmpMats[4];
  73230. if (parent) {
  73231. if (space == BABYLON.Space.WORLD) {
  73232. if (mesh) {
  73233. parentScale.copyFrom(mesh.getWorldMatrix());
  73234. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  73235. }
  73236. else {
  73237. parentScale.copyFrom(parent.getAbsoluteTransform());
  73238. }
  73239. }
  73240. else {
  73241. parentScale = parent._scaleMatrix;
  73242. }
  73243. parentScaleInv.copyFrom(parentScale);
  73244. parentScaleInv.invert();
  73245. lmat.multiplyToRef(parentScale, lmat);
  73246. lmat.multiplyToRef(rmat, lmat);
  73247. lmat.multiplyToRef(parentScaleInv, lmat);
  73248. }
  73249. else {
  73250. if (space == BABYLON.Space.WORLD && mesh) {
  73251. parentScale.copyFrom(mesh.getWorldMatrix());
  73252. parentScaleInv.copyFrom(parentScale);
  73253. parentScaleInv.invert();
  73254. lmat.multiplyToRef(parentScale, lmat);
  73255. lmat.multiplyToRef(rmat, lmat);
  73256. lmat.multiplyToRef(parentScaleInv, lmat);
  73257. }
  73258. else {
  73259. lmat.multiplyToRef(rmat, lmat);
  73260. }
  73261. }
  73262. lmat.m[12] = lx;
  73263. lmat.m[13] = ly;
  73264. lmat.m[14] = lz;
  73265. this.computeAbsoluteTransforms();
  73266. this.markAsDirty();
  73267. };
  73268. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  73269. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73270. if (space == BABYLON.Space.WORLD) {
  73271. var scaleMatrix = Bone._tmpMats[2];
  73272. scaleMatrix.copyFrom(this._scaleMatrix);
  73273. rotMatInv.copyFrom(this.getAbsoluteTransform());
  73274. if (mesh) {
  73275. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  73276. var meshScale = Bone._tmpMats[3];
  73277. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  73278. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  73279. }
  73280. rotMatInv.invert();
  73281. scaleMatrix.m[0] *= this._scalingDeterminant;
  73282. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  73283. }
  73284. else {
  73285. rotMatInv.copyFrom(this.getLocalMatrix());
  73286. rotMatInv.invert();
  73287. var scaleMatrix = Bone._tmpMats[2];
  73288. scaleMatrix.copyFrom(this._scaleMatrix);
  73289. if (this._parent) {
  73290. var pscaleMatrix = Bone._tmpMats[3];
  73291. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  73292. pscaleMatrix.invert();
  73293. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  73294. }
  73295. else {
  73296. scaleMatrix.m[0] *= this._scalingDeterminant;
  73297. }
  73298. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  73299. }
  73300. };
  73301. /**
  73302. * Get the scale of the bone
  73303. * @returns the scale of the bone
  73304. */
  73305. Bone.prototype.getScale = function () {
  73306. return this._scaleVector.clone();
  73307. };
  73308. /**
  73309. * Copy the scale of the bone to a vector3.
  73310. * @param result The vector3 to copy the scale to
  73311. */
  73312. Bone.prototype.getScaleToRef = function (result) {
  73313. result.copyFrom(this._scaleVector);
  73314. };
  73315. /**
  73316. * Get the position of the bone in local or world space.
  73317. * @param space The space that the returned position is in.
  73318. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73319. * @returns The position of the bone
  73320. */
  73321. Bone.prototype.getPosition = function (space, mesh) {
  73322. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73323. if (mesh === void 0) { mesh = null; }
  73324. var pos = BABYLON.Vector3.Zero();
  73325. this.getPositionToRef(space, mesh, pos);
  73326. return pos;
  73327. };
  73328. /**
  73329. * Copy the position of the bone to a vector3 in local or world space.
  73330. * @param space The space that the returned position is in.
  73331. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73332. * @param result The vector3 to copy the position to.
  73333. */
  73334. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  73335. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73336. if (space == BABYLON.Space.LOCAL) {
  73337. var lm = this.getLocalMatrix();
  73338. result.x = lm.m[12];
  73339. result.y = lm.m[13];
  73340. result.z = lm.m[14];
  73341. }
  73342. else {
  73343. var wm = null;
  73344. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73345. if (mesh) {
  73346. wm = mesh.getWorldMatrix();
  73347. }
  73348. this._skeleton.computeAbsoluteTransforms();
  73349. var tmat = Bone._tmpMats[0];
  73350. if (mesh && wm) {
  73351. tmat.copyFrom(this.getAbsoluteTransform());
  73352. tmat.multiplyToRef(wm, tmat);
  73353. }
  73354. else {
  73355. tmat = this.getAbsoluteTransform();
  73356. }
  73357. result.x = tmat.m[12];
  73358. result.y = tmat.m[13];
  73359. result.z = tmat.m[14];
  73360. }
  73361. };
  73362. /**
  73363. * Get the absolute position of the bone (world space).
  73364. * @param mesh The mesh that this bone is attached to.
  73365. * @returns The absolute position of the bone
  73366. */
  73367. Bone.prototype.getAbsolutePosition = function (mesh) {
  73368. if (mesh === void 0) { mesh = null; }
  73369. var pos = BABYLON.Vector3.Zero();
  73370. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  73371. return pos;
  73372. };
  73373. /**
  73374. * Copy the absolute position of the bone (world space) to the result param.
  73375. * @param mesh The mesh that this bone is attached to.
  73376. * @param result The vector3 to copy the absolute position to.
  73377. */
  73378. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  73379. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  73380. };
  73381. /**
  73382. * Compute the absolute transforms of this bone and its children.
  73383. */
  73384. Bone.prototype.computeAbsoluteTransforms = function () {
  73385. if (this._parent) {
  73386. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  73387. }
  73388. else {
  73389. this._absoluteTransform.copyFrom(this._localMatrix);
  73390. var poseMatrix = this._skeleton.getPoseMatrix();
  73391. if (poseMatrix) {
  73392. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  73393. }
  73394. }
  73395. var children = this.children;
  73396. var len = children.length;
  73397. for (var i = 0; i < len; i++) {
  73398. children[i].computeAbsoluteTransforms();
  73399. }
  73400. };
  73401. Bone.prototype._syncScaleVector = function () {
  73402. var lm = this.getLocalMatrix();
  73403. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  73404. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  73405. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  73406. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  73407. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  73408. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  73409. this._scaleVector.x = xs * Math.sqrt(xsq);
  73410. this._scaleVector.y = ys * Math.sqrt(ysq);
  73411. this._scaleVector.z = zs * Math.sqrt(zsq);
  73412. if (this._parent) {
  73413. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  73414. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  73415. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  73416. }
  73417. BABYLON.Matrix.FromValuesToRef(this._scaleVector.x, 0, 0, 0, 0, this._scaleVector.y, 0, 0, 0, 0, this._scaleVector.z, 0, 0, 0, 0, 1, this._scaleMatrix);
  73418. };
  73419. /**
  73420. * Get the world direction from an axis that is in the local space of the bone.
  73421. * @param localAxis The local direction that is used to compute the world direction.
  73422. * @param mesh The mesh that this bone is attached to.
  73423. * @returns The world direction
  73424. */
  73425. Bone.prototype.getDirection = function (localAxis, mesh) {
  73426. if (mesh === void 0) { mesh = null; }
  73427. var result = BABYLON.Vector3.Zero();
  73428. this.getDirectionToRef(localAxis, mesh, result);
  73429. return result;
  73430. };
  73431. /**
  73432. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  73433. * @param localAxis The local direction that is used to compute the world direction.
  73434. * @param mesh The mesh that this bone is attached to.
  73435. * @param result The vector3 that the world direction will be copied to.
  73436. */
  73437. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  73438. if (mesh === void 0) { mesh = null; }
  73439. var wm = null;
  73440. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73441. if (mesh) {
  73442. wm = mesh.getWorldMatrix();
  73443. }
  73444. this._skeleton.computeAbsoluteTransforms();
  73445. var mat = Bone._tmpMats[0];
  73446. mat.copyFrom(this.getAbsoluteTransform());
  73447. if (mesh && wm) {
  73448. mat.multiplyToRef(wm, mat);
  73449. }
  73450. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  73451. result.normalize();
  73452. };
  73453. /**
  73454. * Get the euler rotation of the bone in local or world space.
  73455. * @param space The space that the rotation should be in.
  73456. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73457. * @returns The euler rotation
  73458. */
  73459. Bone.prototype.getRotation = function (space, mesh) {
  73460. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73461. if (mesh === void 0) { mesh = null; }
  73462. var result = BABYLON.Vector3.Zero();
  73463. this.getRotationToRef(space, mesh, result);
  73464. return result;
  73465. };
  73466. /**
  73467. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  73468. * @param space The space that the rotation should be in.
  73469. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73470. * @param result The vector3 that the rotation should be copied to.
  73471. */
  73472. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  73473. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73474. if (mesh === void 0) { mesh = null; }
  73475. var quat = Bone._tmpQuat;
  73476. this.getRotationQuaternionToRef(space, mesh, quat);
  73477. quat.toEulerAnglesToRef(result);
  73478. };
  73479. /**
  73480. * Get the quaternion rotation of the bone in either local or world space.
  73481. * @param space The space that the rotation should be in.
  73482. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73483. * @returns The quaternion rotation
  73484. */
  73485. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  73486. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73487. if (mesh === void 0) { mesh = null; }
  73488. var result = BABYLON.Quaternion.Identity();
  73489. this.getRotationQuaternionToRef(space, mesh, result);
  73490. return result;
  73491. };
  73492. /**
  73493. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  73494. * @param space The space that the rotation should be in.
  73495. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73496. * @param result The quaternion that the rotation should be copied to.
  73497. */
  73498. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  73499. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73500. if (mesh === void 0) { mesh = null; }
  73501. if (space == BABYLON.Space.LOCAL) {
  73502. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  73503. }
  73504. else {
  73505. var mat = Bone._tmpMats[0];
  73506. var amat = this.getAbsoluteTransform();
  73507. if (mesh) {
  73508. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  73509. }
  73510. else {
  73511. mat.copyFrom(amat);
  73512. }
  73513. mat.m[0] *= this._scalingDeterminant;
  73514. mat.m[1] *= this._scalingDeterminant;
  73515. mat.m[2] *= this._scalingDeterminant;
  73516. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  73517. }
  73518. };
  73519. /**
  73520. * Get the rotation matrix of the bone in local or world space.
  73521. * @param space The space that the rotation should be in.
  73522. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73523. * @returns The rotation matrix
  73524. */
  73525. Bone.prototype.getRotationMatrix = function (space, mesh) {
  73526. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73527. var result = BABYLON.Matrix.Identity();
  73528. this.getRotationMatrixToRef(space, mesh, result);
  73529. return result;
  73530. };
  73531. /**
  73532. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  73533. * @param space The space that the rotation should be in.
  73534. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73535. * @param result The quaternion that the rotation should be copied to.
  73536. */
  73537. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  73538. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73539. if (space == BABYLON.Space.LOCAL) {
  73540. this.getLocalMatrix().getRotationMatrixToRef(result);
  73541. }
  73542. else {
  73543. var mat = Bone._tmpMats[0];
  73544. var amat = this.getAbsoluteTransform();
  73545. if (mesh) {
  73546. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  73547. }
  73548. else {
  73549. mat.copyFrom(amat);
  73550. }
  73551. mat.m[0] *= this._scalingDeterminant;
  73552. mat.m[1] *= this._scalingDeterminant;
  73553. mat.m[2] *= this._scalingDeterminant;
  73554. mat.getRotationMatrixToRef(result);
  73555. }
  73556. };
  73557. /**
  73558. * Get the world position of a point that is in the local space of the bone.
  73559. * @param position The local position
  73560. * @param mesh The mesh that this bone is attached to.
  73561. * @returns The world position
  73562. */
  73563. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  73564. if (mesh === void 0) { mesh = null; }
  73565. var result = BABYLON.Vector3.Zero();
  73566. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  73567. return result;
  73568. };
  73569. /**
  73570. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  73571. * @param position The local position
  73572. * @param mesh The mesh that this bone is attached to.
  73573. * @param result The vector3 that the world position should be copied to.
  73574. */
  73575. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  73576. if (mesh === void 0) { mesh = null; }
  73577. var wm = null;
  73578. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73579. if (mesh) {
  73580. wm = mesh.getWorldMatrix();
  73581. }
  73582. this._skeleton.computeAbsoluteTransforms();
  73583. var tmat = Bone._tmpMats[0];
  73584. if (mesh && wm) {
  73585. tmat.copyFrom(this.getAbsoluteTransform());
  73586. tmat.multiplyToRef(wm, tmat);
  73587. }
  73588. else {
  73589. tmat = this.getAbsoluteTransform();
  73590. }
  73591. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  73592. };
  73593. /**
  73594. * Get the local position of a point that is in world space.
  73595. * @param position The world position
  73596. * @param mesh The mesh that this bone is attached to.
  73597. * @returns The local position
  73598. */
  73599. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  73600. if (mesh === void 0) { mesh = null; }
  73601. var result = BABYLON.Vector3.Zero();
  73602. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  73603. return result;
  73604. };
  73605. /**
  73606. * Get the local position of a point that is in world space and copy it to the result param.
  73607. * @param position The world position
  73608. * @param mesh The mesh that this bone is attached to.
  73609. * @param result The vector3 that the local position should be copied to.
  73610. */
  73611. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  73612. if (mesh === void 0) { mesh = null; }
  73613. var wm = null;
  73614. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73615. if (mesh) {
  73616. wm = mesh.getWorldMatrix();
  73617. }
  73618. this._skeleton.computeAbsoluteTransforms();
  73619. var tmat = Bone._tmpMats[0];
  73620. tmat.copyFrom(this.getAbsoluteTransform());
  73621. if (mesh && wm) {
  73622. tmat.multiplyToRef(wm, tmat);
  73623. }
  73624. tmat.invert();
  73625. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  73626. };
  73627. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73628. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  73629. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  73630. return Bone;
  73631. }(BABYLON.Node));
  73632. BABYLON.Bone = Bone;
  73633. })(BABYLON || (BABYLON = {}));
  73634. //# sourceMappingURL=babylon.bone.js.map
  73635. "use strict";
  73636. var BABYLON;
  73637. (function (BABYLON) {
  73638. var BoneIKController = /** @class */ (function () {
  73639. function BoneIKController(mesh, bone, options) {
  73640. this.targetPosition = BABYLON.Vector3.Zero();
  73641. this.poleTargetPosition = BABYLON.Vector3.Zero();
  73642. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  73643. this.poleAngle = 0;
  73644. this.slerpAmount = 1;
  73645. this._bone1Quat = BABYLON.Quaternion.Identity();
  73646. this._bone1Mat = BABYLON.Matrix.Identity();
  73647. this._bone2Ang = Math.PI;
  73648. this._maxAngle = Math.PI;
  73649. this._rightHandedSystem = false;
  73650. this._bendAxis = BABYLON.Vector3.Right();
  73651. this._slerping = false;
  73652. this._adjustRoll = 0;
  73653. this._bone2 = bone;
  73654. this._bone1 = bone.getParent();
  73655. if (!this._bone1) {
  73656. return;
  73657. }
  73658. this.mesh = mesh;
  73659. var bonePos = bone.getPosition();
  73660. if (bone.getAbsoluteTransform().determinant() > 0) {
  73661. this._rightHandedSystem = true;
  73662. this._bendAxis.x = 0;
  73663. this._bendAxis.y = 0;
  73664. this._bendAxis.z = -1;
  73665. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  73666. this._adjustRoll = Math.PI * .5;
  73667. this._bendAxis.z = 1;
  73668. }
  73669. }
  73670. if (this._bone1.length) {
  73671. var boneScale1 = this._bone1.getScale();
  73672. var boneScale2 = this._bone2.getScale();
  73673. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  73674. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  73675. }
  73676. else if (this._bone1.children[0]) {
  73677. mesh.computeWorldMatrix(true);
  73678. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  73679. var pos2 = this._bone2.getAbsolutePosition(mesh);
  73680. var pos3 = this._bone1.getAbsolutePosition(mesh);
  73681. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  73682. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  73683. }
  73684. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  73685. this.maxAngle = Math.PI;
  73686. if (options) {
  73687. if (options.targetMesh) {
  73688. this.targetMesh = options.targetMesh;
  73689. this.targetMesh.computeWorldMatrix(true);
  73690. }
  73691. if (options.poleTargetMesh) {
  73692. this.poleTargetMesh = options.poleTargetMesh;
  73693. this.poleTargetMesh.computeWorldMatrix(true);
  73694. }
  73695. else if (options.poleTargetBone) {
  73696. this.poleTargetBone = options.poleTargetBone;
  73697. }
  73698. else if (this._bone1.getParent()) {
  73699. this.poleTargetBone = this._bone1.getParent();
  73700. }
  73701. if (options.poleTargetLocalOffset) {
  73702. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  73703. }
  73704. if (options.poleAngle) {
  73705. this.poleAngle = options.poleAngle;
  73706. }
  73707. if (options.bendAxis) {
  73708. this._bendAxis.copyFrom(options.bendAxis);
  73709. }
  73710. if (options.maxAngle) {
  73711. this.maxAngle = options.maxAngle;
  73712. }
  73713. if (options.slerpAmount) {
  73714. this.slerpAmount = options.slerpAmount;
  73715. }
  73716. }
  73717. }
  73718. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  73719. get: function () {
  73720. return this._maxAngle;
  73721. },
  73722. set: function (value) {
  73723. this._setMaxAngle(value);
  73724. },
  73725. enumerable: true,
  73726. configurable: true
  73727. });
  73728. BoneIKController.prototype._setMaxAngle = function (ang) {
  73729. if (ang < 0) {
  73730. ang = 0;
  73731. }
  73732. if (ang > Math.PI || ang == undefined) {
  73733. ang = Math.PI;
  73734. }
  73735. this._maxAngle = ang;
  73736. var a = this._bone1Length;
  73737. var b = this._bone2Length;
  73738. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  73739. };
  73740. BoneIKController.prototype.update = function () {
  73741. var bone1 = this._bone1;
  73742. if (!bone1) {
  73743. return;
  73744. }
  73745. var target = this.targetPosition;
  73746. var poleTarget = this.poleTargetPosition;
  73747. var mat1 = BoneIKController._tmpMats[0];
  73748. var mat2 = BoneIKController._tmpMats[1];
  73749. if (this.targetMesh) {
  73750. target.copyFrom(this.targetMesh.getAbsolutePosition());
  73751. }
  73752. if (this.poleTargetBone) {
  73753. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  73754. }
  73755. else if (this.poleTargetMesh) {
  73756. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  73757. }
  73758. var bonePos = BoneIKController._tmpVecs[0];
  73759. var zaxis = BoneIKController._tmpVecs[1];
  73760. var xaxis = BoneIKController._tmpVecs[2];
  73761. var yaxis = BoneIKController._tmpVecs[3];
  73762. var upAxis = BoneIKController._tmpVecs[4];
  73763. var _tmpQuat = BoneIKController._tmpQuat;
  73764. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  73765. poleTarget.subtractToRef(bonePos, upAxis);
  73766. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  73767. upAxis.y = 1;
  73768. }
  73769. else {
  73770. upAxis.normalize();
  73771. }
  73772. target.subtractToRef(bonePos, yaxis);
  73773. yaxis.normalize();
  73774. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  73775. zaxis.normalize();
  73776. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  73777. xaxis.normalize();
  73778. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  73779. var a = this._bone1Length;
  73780. var b = this._bone2Length;
  73781. var c = BABYLON.Vector3.Distance(bonePos, target);
  73782. if (this._maxReach > 0) {
  73783. c = Math.min(this._maxReach, c);
  73784. }
  73785. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  73786. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  73787. if (acosa > 1) {
  73788. acosa = 1;
  73789. }
  73790. if (acosb > 1) {
  73791. acosb = 1;
  73792. }
  73793. if (acosa < -1) {
  73794. acosa = -1;
  73795. }
  73796. if (acosb < -1) {
  73797. acosb = -1;
  73798. }
  73799. var angA = Math.acos(acosa);
  73800. var angB = Math.acos(acosb);
  73801. var angC = -angA - angB;
  73802. if (this._rightHandedSystem) {
  73803. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  73804. mat2.multiplyToRef(mat1, mat1);
  73805. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  73806. mat2.multiplyToRef(mat1, mat1);
  73807. }
  73808. else {
  73809. var _tmpVec = BoneIKController._tmpVecs[5];
  73810. _tmpVec.copyFrom(this._bendAxis);
  73811. _tmpVec.x *= -1;
  73812. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  73813. mat2.multiplyToRef(mat1, mat1);
  73814. }
  73815. if (this.poleAngle) {
  73816. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  73817. mat1.multiplyToRef(mat2, mat1);
  73818. }
  73819. if (this._bone1) {
  73820. if (this.slerpAmount < 1) {
  73821. if (!this._slerping) {
  73822. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  73823. }
  73824. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  73825. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  73826. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  73827. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  73828. this._slerping = true;
  73829. }
  73830. else {
  73831. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  73832. this._bone1Mat.copyFrom(mat1);
  73833. this._slerping = false;
  73834. }
  73835. }
  73836. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  73837. this._bone2Ang = angC;
  73838. };
  73839. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73840. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  73841. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  73842. return BoneIKController;
  73843. }());
  73844. BABYLON.BoneIKController = BoneIKController;
  73845. })(BABYLON || (BABYLON = {}));
  73846. //# sourceMappingURL=babylon.boneIKController.js.map
  73847. "use strict";
  73848. var BABYLON;
  73849. (function (BABYLON) {
  73850. var BoneLookController = /** @class */ (function () {
  73851. /**
  73852. * Create a BoneLookController
  73853. * @param mesh the mesh that the bone belongs to
  73854. * @param bone the bone that will be looking to the target
  73855. * @param target the target Vector3 to look at
  73856. * @param settings optional settings:
  73857. * - maxYaw: the maximum angle the bone will yaw to
  73858. * - minYaw: the minimum angle the bone will yaw to
  73859. * - maxPitch: the maximum angle the bone will pitch to
  73860. * - minPitch: the minimum angle the bone will yaw to
  73861. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  73862. * - upAxis: the up axis of the coordinate system
  73863. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  73864. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  73865. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  73866. * - adjustYaw: used to make an adjustment to the yaw of the bone
  73867. * - adjustPitch: used to make an adjustment to the pitch of the bone
  73868. * - adjustRoll: used to make an adjustment to the roll of the bone
  73869. **/
  73870. function BoneLookController(mesh, bone, target, options) {
  73871. /**
  73872. * The up axis of the coordinate system that is used when the bone is rotated.
  73873. */
  73874. this.upAxis = BABYLON.Vector3.Up();
  73875. /**
  73876. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  73877. */
  73878. this.upAxisSpace = BABYLON.Space.LOCAL;
  73879. /**
  73880. * Used to make an adjustment to the yaw of the bone.
  73881. */
  73882. this.adjustYaw = 0;
  73883. /**
  73884. * Used to make an adjustment to the pitch of the bone.
  73885. */
  73886. this.adjustPitch = 0;
  73887. /**
  73888. * Used to make an adjustment to the roll of the bone.
  73889. */
  73890. this.adjustRoll = 0;
  73891. /**
  73892. * 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).
  73893. */
  73894. this.slerpAmount = 1;
  73895. this._boneQuat = BABYLON.Quaternion.Identity();
  73896. this._slerping = false;
  73897. this._firstFrameSkipped = false;
  73898. this._fowardAxis = BABYLON.Vector3.Forward();
  73899. this.mesh = mesh;
  73900. this.bone = bone;
  73901. this.target = target;
  73902. if (options) {
  73903. if (options.adjustYaw) {
  73904. this.adjustYaw = options.adjustYaw;
  73905. }
  73906. if (options.adjustPitch) {
  73907. this.adjustPitch = options.adjustPitch;
  73908. }
  73909. if (options.adjustRoll) {
  73910. this.adjustRoll = options.adjustRoll;
  73911. }
  73912. if (options.maxYaw != null) {
  73913. this.maxYaw = options.maxYaw;
  73914. }
  73915. else {
  73916. this.maxYaw = Math.PI;
  73917. }
  73918. if (options.minYaw != null) {
  73919. this.minYaw = options.minYaw;
  73920. }
  73921. else {
  73922. this.minYaw = -Math.PI;
  73923. }
  73924. if (options.maxPitch != null) {
  73925. this.maxPitch = options.maxPitch;
  73926. }
  73927. else {
  73928. this.maxPitch = Math.PI;
  73929. }
  73930. if (options.minPitch != null) {
  73931. this.minPitch = options.minPitch;
  73932. }
  73933. else {
  73934. this.minPitch = -Math.PI;
  73935. }
  73936. if (options.slerpAmount != null) {
  73937. this.slerpAmount = options.slerpAmount;
  73938. }
  73939. if (options.upAxis != null) {
  73940. this.upAxis = options.upAxis;
  73941. }
  73942. if (options.upAxisSpace != null) {
  73943. this.upAxisSpace = options.upAxisSpace;
  73944. }
  73945. if (options.yawAxis != null || options.pitchAxis != null) {
  73946. var newYawAxis = BABYLON.Axis.Y;
  73947. var newPitchAxis = BABYLON.Axis.X;
  73948. if (options.yawAxis != null) {
  73949. newYawAxis = options.yawAxis.clone();
  73950. newYawAxis.normalize();
  73951. }
  73952. if (options.pitchAxis != null) {
  73953. newPitchAxis = options.pitchAxis.clone();
  73954. newPitchAxis.normalize();
  73955. }
  73956. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  73957. this._transformYawPitch = BABYLON.Matrix.Identity();
  73958. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  73959. this._transformYawPitchInv = this._transformYawPitch.clone();
  73960. this._transformYawPitch.invert();
  73961. }
  73962. }
  73963. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  73964. this.upAxisSpace = BABYLON.Space.LOCAL;
  73965. }
  73966. }
  73967. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  73968. /**
  73969. * Get/set the minimum yaw angle that the bone can look to.
  73970. */
  73971. get: function () {
  73972. return this._minYaw;
  73973. },
  73974. set: function (value) {
  73975. this._minYaw = value;
  73976. this._minYawSin = Math.sin(value);
  73977. this._minYawCos = Math.cos(value);
  73978. if (this._maxYaw != null) {
  73979. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  73980. this._yawRange = this._maxYaw - this._minYaw;
  73981. }
  73982. },
  73983. enumerable: true,
  73984. configurable: true
  73985. });
  73986. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  73987. /**
  73988. * Get/set the maximum yaw angle that the bone can look to.
  73989. */
  73990. get: function () {
  73991. return this._maxYaw;
  73992. },
  73993. set: function (value) {
  73994. this._maxYaw = value;
  73995. this._maxYawSin = Math.sin(value);
  73996. this._maxYawCos = Math.cos(value);
  73997. if (this._minYaw != null) {
  73998. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  73999. this._yawRange = this._maxYaw - this._minYaw;
  74000. }
  74001. },
  74002. enumerable: true,
  74003. configurable: true
  74004. });
  74005. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  74006. /**
  74007. * Get/set the minimum pitch angle that the bone can look to.
  74008. */
  74009. get: function () {
  74010. return this._minPitch;
  74011. },
  74012. set: function (value) {
  74013. this._minPitch = value;
  74014. this._minPitchTan = Math.tan(value);
  74015. },
  74016. enumerable: true,
  74017. configurable: true
  74018. });
  74019. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  74020. /**
  74021. * Get/set the maximum pitch angle that the bone can look to.
  74022. */
  74023. get: function () {
  74024. return this._maxPitch;
  74025. },
  74026. set: function (value) {
  74027. this._maxPitch = value;
  74028. this._maxPitchTan = Math.tan(value);
  74029. },
  74030. enumerable: true,
  74031. configurable: true
  74032. });
  74033. /**
  74034. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  74035. */
  74036. BoneLookController.prototype.update = function () {
  74037. //skip the first frame when slerping so that the mesh rotation is correct
  74038. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  74039. this._firstFrameSkipped = true;
  74040. return;
  74041. }
  74042. var bone = this.bone;
  74043. var bonePos = BoneLookController._tmpVecs[0];
  74044. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  74045. var target = this.target;
  74046. var _tmpMat1 = BoneLookController._tmpMats[0];
  74047. var _tmpMat2 = BoneLookController._tmpMats[1];
  74048. var mesh = this.mesh;
  74049. var parentBone = bone.getParent();
  74050. var upAxis = BoneLookController._tmpVecs[1];
  74051. upAxis.copyFrom(this.upAxis);
  74052. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  74053. if (this._transformYawPitch) {
  74054. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  74055. }
  74056. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  74057. }
  74058. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  74059. mesh.getDirectionToRef(upAxis, upAxis);
  74060. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  74061. upAxis.normalize();
  74062. }
  74063. }
  74064. var checkYaw = false;
  74065. var checkPitch = false;
  74066. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  74067. checkYaw = true;
  74068. }
  74069. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  74070. checkPitch = true;
  74071. }
  74072. if (checkYaw || checkPitch) {
  74073. var spaceMat = BoneLookController._tmpMats[2];
  74074. var spaceMatInv = BoneLookController._tmpMats[3];
  74075. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  74076. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  74077. }
  74078. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  74079. spaceMat.copyFrom(mesh.getWorldMatrix());
  74080. }
  74081. else {
  74082. var forwardAxis = BoneLookController._tmpVecs[2];
  74083. forwardAxis.copyFrom(this._fowardAxis);
  74084. if (this._transformYawPitch) {
  74085. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  74086. }
  74087. if (parentBone) {
  74088. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  74089. }
  74090. else {
  74091. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  74092. }
  74093. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  74094. rightAxis.normalize();
  74095. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  74096. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  74097. }
  74098. spaceMat.invertToRef(spaceMatInv);
  74099. var xzlen = null;
  74100. if (checkPitch) {
  74101. var localTarget = BoneLookController._tmpVecs[3];
  74102. target.subtractToRef(bonePos, localTarget);
  74103. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  74104. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  74105. var pitch = Math.atan2(localTarget.y, xzlen);
  74106. var newPitch = pitch;
  74107. if (pitch > this._maxPitch) {
  74108. localTarget.y = this._maxPitchTan * xzlen;
  74109. newPitch = this._maxPitch;
  74110. }
  74111. else if (pitch < this._minPitch) {
  74112. localTarget.y = this._minPitchTan * xzlen;
  74113. newPitch = this._minPitch;
  74114. }
  74115. if (pitch != newPitch) {
  74116. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  74117. localTarget.addInPlace(bonePos);
  74118. target = localTarget;
  74119. }
  74120. }
  74121. if (checkYaw) {
  74122. var localTarget = BoneLookController._tmpVecs[4];
  74123. target.subtractToRef(bonePos, localTarget);
  74124. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  74125. var yaw = Math.atan2(localTarget.x, localTarget.z);
  74126. var newYaw = yaw;
  74127. if (yaw > this._maxYaw || yaw < this._minYaw) {
  74128. if (xzlen == null) {
  74129. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  74130. }
  74131. if (this._yawRange > Math.PI) {
  74132. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  74133. localTarget.z = this._maxYawCos * xzlen;
  74134. localTarget.x = this._maxYawSin * xzlen;
  74135. newYaw = this._maxYaw;
  74136. }
  74137. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  74138. localTarget.z = this._minYawCos * xzlen;
  74139. localTarget.x = this._minYawSin * xzlen;
  74140. newYaw = this._minYaw;
  74141. }
  74142. }
  74143. else {
  74144. if (yaw > this._maxYaw) {
  74145. localTarget.z = this._maxYawCos * xzlen;
  74146. localTarget.x = this._maxYawSin * xzlen;
  74147. newYaw = this._maxYaw;
  74148. }
  74149. else if (yaw < this._minYaw) {
  74150. localTarget.z = this._minYawCos * xzlen;
  74151. localTarget.x = this._minYawSin * xzlen;
  74152. newYaw = this._minYaw;
  74153. }
  74154. }
  74155. }
  74156. if (this._slerping && this._yawRange > Math.PI) {
  74157. //are we going to be crossing into the min/max region?
  74158. var boneFwd = BoneLookController._tmpVecs[8];
  74159. boneFwd.copyFrom(BABYLON.Axis.Z);
  74160. if (this._transformYawPitch) {
  74161. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  74162. }
  74163. var boneRotMat = BoneLookController._tmpMats[4];
  74164. this._boneQuat.toRotationMatrix(boneRotMat);
  74165. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  74166. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  74167. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  74168. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  74169. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  74170. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  74171. if (angBtwTar > angBtwMidYaw) {
  74172. if (xzlen == null) {
  74173. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  74174. }
  74175. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  74176. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  74177. if (angBtwMin < angBtwMax) {
  74178. newYaw = boneYaw + Math.PI * .75;
  74179. localTarget.z = Math.cos(newYaw) * xzlen;
  74180. localTarget.x = Math.sin(newYaw) * xzlen;
  74181. }
  74182. else {
  74183. newYaw = boneYaw - Math.PI * .75;
  74184. localTarget.z = Math.cos(newYaw) * xzlen;
  74185. localTarget.x = Math.sin(newYaw) * xzlen;
  74186. }
  74187. }
  74188. }
  74189. if (yaw != newYaw) {
  74190. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  74191. localTarget.addInPlace(bonePos);
  74192. target = localTarget;
  74193. }
  74194. }
  74195. }
  74196. var zaxis = BoneLookController._tmpVecs[5];
  74197. var xaxis = BoneLookController._tmpVecs[6];
  74198. var yaxis = BoneLookController._tmpVecs[7];
  74199. var _tmpQuat = BoneLookController._tmpQuat;
  74200. target.subtractToRef(bonePos, zaxis);
  74201. zaxis.normalize();
  74202. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  74203. xaxis.normalize();
  74204. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  74205. yaxis.normalize();
  74206. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  74207. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  74208. return;
  74209. }
  74210. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  74211. return;
  74212. }
  74213. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  74214. return;
  74215. }
  74216. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  74217. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  74218. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  74219. }
  74220. if (this.slerpAmount < 1) {
  74221. if (!this._slerping) {
  74222. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  74223. }
  74224. if (this._transformYawPitch) {
  74225. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  74226. }
  74227. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  74228. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  74229. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  74230. this._slerping = true;
  74231. }
  74232. else {
  74233. if (this._transformYawPitch) {
  74234. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  74235. }
  74236. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  74237. this._slerping = false;
  74238. }
  74239. };
  74240. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  74241. var angDiff = ang2 - ang1;
  74242. angDiff %= Math.PI * 2;
  74243. if (angDiff > Math.PI) {
  74244. angDiff -= Math.PI * 2;
  74245. }
  74246. else if (angDiff < -Math.PI) {
  74247. angDiff += Math.PI * 2;
  74248. }
  74249. return angDiff;
  74250. };
  74251. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  74252. ang1 %= (2 * Math.PI);
  74253. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  74254. ang2 %= (2 * Math.PI);
  74255. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  74256. var ab = 0;
  74257. if (ang1 < ang2) {
  74258. ab = ang2 - ang1;
  74259. }
  74260. else {
  74261. ab = ang1 - ang2;
  74262. }
  74263. if (ab > Math.PI) {
  74264. ab = Math.PI * 2 - ab;
  74265. }
  74266. return ab;
  74267. };
  74268. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  74269. ang %= (2 * Math.PI);
  74270. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  74271. ang1 %= (2 * Math.PI);
  74272. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  74273. ang2 %= (2 * Math.PI);
  74274. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  74275. if (ang1 < ang2) {
  74276. if (ang > ang1 && ang < ang2) {
  74277. return true;
  74278. }
  74279. }
  74280. else {
  74281. if (ang > ang2 && ang < ang1) {
  74282. return true;
  74283. }
  74284. }
  74285. return false;
  74286. };
  74287. 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()];
  74288. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  74289. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  74290. return BoneLookController;
  74291. }());
  74292. BABYLON.BoneLookController = BoneLookController;
  74293. })(BABYLON || (BABYLON = {}));
  74294. //# sourceMappingURL=babylon.boneLookController.js.map
  74295. "use strict";
  74296. var BABYLON;
  74297. (function (BABYLON) {
  74298. var Skeleton = /** @class */ (function () {
  74299. function Skeleton(name, id, scene) {
  74300. this.name = name;
  74301. this.id = id;
  74302. this.bones = new Array();
  74303. this.needInitialSkinMatrix = false;
  74304. this._isDirty = true;
  74305. this._meshesWithPoseMatrix = new Array();
  74306. this._identity = BABYLON.Matrix.Identity();
  74307. this._ranges = {};
  74308. this._lastAbsoluteTransformsUpdateId = -1;
  74309. /**
  74310. * Specifies if the skeleton should be serialized.
  74311. */
  74312. this.doNotSerialize = false;
  74313. // Events
  74314. /**
  74315. * An event triggered before computing the skeleton's matrices
  74316. */
  74317. this.onBeforeComputeObservable = new BABYLON.Observable();
  74318. this.bones = [];
  74319. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  74320. scene.skeletons.push(this);
  74321. //make sure it will recalculate the matrix next time prepare is called.
  74322. this._isDirty = true;
  74323. }
  74324. // Members
  74325. Skeleton.prototype.getTransformMatrices = function (mesh) {
  74326. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  74327. return mesh._bonesTransformMatrices;
  74328. }
  74329. if (!this._transformMatrices) {
  74330. this.prepare();
  74331. }
  74332. return this._transformMatrices;
  74333. };
  74334. Skeleton.prototype.getScene = function () {
  74335. return this._scene;
  74336. };
  74337. // Methods
  74338. /**
  74339. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  74340. */
  74341. Skeleton.prototype.toString = function (fullDetails) {
  74342. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  74343. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  74344. if (fullDetails) {
  74345. ret += ", Ranges: {";
  74346. var first = true;
  74347. for (var name_1 in this._ranges) {
  74348. if (first) {
  74349. ret += ", ";
  74350. first = false;
  74351. }
  74352. ret += name_1;
  74353. }
  74354. ret += "}";
  74355. }
  74356. return ret;
  74357. };
  74358. /**
  74359. * Get bone's index searching by name
  74360. * @param {string} name is bone's name to search for
  74361. * @return {number} Indice of the bone. Returns -1 if not found
  74362. */
  74363. Skeleton.prototype.getBoneIndexByName = function (name) {
  74364. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  74365. if (this.bones[boneIndex].name === name) {
  74366. return boneIndex;
  74367. }
  74368. }
  74369. return -1;
  74370. };
  74371. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  74372. // check name not already in use
  74373. if (!this._ranges[name]) {
  74374. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  74375. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  74376. if (this.bones[i].animations[0]) {
  74377. this.bones[i].animations[0].createRange(name, from, to);
  74378. }
  74379. }
  74380. }
  74381. };
  74382. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  74383. if (deleteFrames === void 0) { deleteFrames = true; }
  74384. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  74385. if (this.bones[i].animations[0]) {
  74386. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  74387. }
  74388. }
  74389. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  74390. };
  74391. Skeleton.prototype.getAnimationRange = function (name) {
  74392. return this._ranges[name];
  74393. };
  74394. /**
  74395. * Returns as an Array, all AnimationRanges defined on this skeleton
  74396. */
  74397. Skeleton.prototype.getAnimationRanges = function () {
  74398. var animationRanges = [];
  74399. var name;
  74400. var i = 0;
  74401. for (name in this._ranges) {
  74402. animationRanges[i] = this._ranges[name];
  74403. i++;
  74404. }
  74405. return animationRanges;
  74406. };
  74407. /**
  74408. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  74409. */
  74410. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  74411. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  74412. if (this._ranges[name] || !source.getAnimationRange(name)) {
  74413. return false;
  74414. }
  74415. var ret = true;
  74416. var frameOffset = this._getHighestAnimationFrame() + 1;
  74417. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  74418. var boneDict = {};
  74419. var sourceBones = source.bones;
  74420. var nBones;
  74421. var i;
  74422. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  74423. boneDict[sourceBones[i].name] = sourceBones[i];
  74424. }
  74425. if (this.bones.length !== sourceBones.length) {
  74426. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  74427. ret = false;
  74428. }
  74429. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  74430. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  74431. var boneName = this.bones[i].name;
  74432. var sourceBone = boneDict[boneName];
  74433. if (sourceBone) {
  74434. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  74435. }
  74436. else {
  74437. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  74438. ret = false;
  74439. }
  74440. }
  74441. // do not call createAnimationRange(), since it also is done to bones, which was already done
  74442. var range = source.getAnimationRange(name);
  74443. if (range) {
  74444. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  74445. }
  74446. return ret;
  74447. };
  74448. Skeleton.prototype.returnToRest = function () {
  74449. for (var index = 0; index < this.bones.length; index++) {
  74450. this.bones[index].returnToRest();
  74451. }
  74452. };
  74453. Skeleton.prototype._getHighestAnimationFrame = function () {
  74454. var ret = 0;
  74455. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  74456. if (this.bones[i].animations[0]) {
  74457. var highest = this.bones[i].animations[0].getHighestFrame();
  74458. if (ret < highest) {
  74459. ret = highest;
  74460. }
  74461. }
  74462. }
  74463. return ret;
  74464. };
  74465. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  74466. var range = this.getAnimationRange(name);
  74467. if (!range) {
  74468. return null;
  74469. }
  74470. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  74471. };
  74472. Skeleton.prototype._markAsDirty = function () {
  74473. this._isDirty = true;
  74474. };
  74475. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  74476. this._meshesWithPoseMatrix.push(mesh);
  74477. };
  74478. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  74479. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  74480. if (index > -1) {
  74481. this._meshesWithPoseMatrix.splice(index, 1);
  74482. }
  74483. };
  74484. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  74485. this.onBeforeComputeObservable.notifyObservers(this);
  74486. for (var index = 0; index < this.bones.length; index++) {
  74487. var bone = this.bones[index];
  74488. var parentBone = bone.getParent();
  74489. if (parentBone) {
  74490. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  74491. }
  74492. else {
  74493. if (initialSkinMatrix) {
  74494. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  74495. }
  74496. else {
  74497. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  74498. }
  74499. }
  74500. if (bone._index !== -1) {
  74501. var mappedIndex = bone._index === null ? index : bone._index;
  74502. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  74503. }
  74504. }
  74505. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  74506. };
  74507. Skeleton.prototype.prepare = function () {
  74508. if (!this._isDirty) {
  74509. return;
  74510. }
  74511. if (this.needInitialSkinMatrix) {
  74512. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  74513. var mesh = this._meshesWithPoseMatrix[index];
  74514. var poseMatrix = mesh.getPoseMatrix();
  74515. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  74516. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  74517. }
  74518. if (this._synchronizedWithMesh !== mesh) {
  74519. this._synchronizedWithMesh = mesh;
  74520. // Prepare bones
  74521. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  74522. var bone = this.bones[boneIndex];
  74523. if (!bone.getParent()) {
  74524. var matrix = bone.getBaseMatrix();
  74525. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  74526. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  74527. }
  74528. }
  74529. }
  74530. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  74531. }
  74532. }
  74533. else {
  74534. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  74535. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  74536. }
  74537. this._computeTransformMatrices(this._transformMatrices, null);
  74538. }
  74539. this._isDirty = false;
  74540. this._scene._activeBones.addCount(this.bones.length, false);
  74541. };
  74542. Skeleton.prototype.getAnimatables = function () {
  74543. if (!this._animatables || this._animatables.length !== this.bones.length) {
  74544. this._animatables = [];
  74545. for (var index = 0; index < this.bones.length; index++) {
  74546. this._animatables.push(this.bones[index]);
  74547. }
  74548. }
  74549. return this._animatables;
  74550. };
  74551. Skeleton.prototype.clone = function (name, id) {
  74552. var result = new Skeleton(name, id || name, this._scene);
  74553. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  74554. for (var index = 0; index < this.bones.length; index++) {
  74555. var source = this.bones[index];
  74556. var parentBone = null;
  74557. var parent_1 = source.getParent();
  74558. if (parent_1) {
  74559. var parentIndex = this.bones.indexOf(parent_1);
  74560. parentBone = result.bones[parentIndex];
  74561. }
  74562. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  74563. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  74564. }
  74565. if (this._ranges) {
  74566. result._ranges = {};
  74567. for (var rangeName in this._ranges) {
  74568. var range = this._ranges[rangeName];
  74569. if (range) {
  74570. result._ranges[rangeName] = range.clone();
  74571. }
  74572. }
  74573. }
  74574. this._isDirty = true;
  74575. return result;
  74576. };
  74577. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  74578. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  74579. this.bones.forEach(function (bone) {
  74580. bone.animations.forEach(function (animation) {
  74581. animation.enableBlending = true;
  74582. animation.blendingSpeed = blendingSpeed;
  74583. });
  74584. });
  74585. };
  74586. Skeleton.prototype.dispose = function () {
  74587. this._meshesWithPoseMatrix = [];
  74588. // Animations
  74589. this.getScene().stopAnimation(this);
  74590. // Remove from scene
  74591. this.getScene().removeSkeleton(this);
  74592. };
  74593. Skeleton.prototype.serialize = function () {
  74594. var serializationObject = {};
  74595. serializationObject.name = this.name;
  74596. serializationObject.id = this.id;
  74597. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  74598. serializationObject.bones = [];
  74599. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  74600. for (var index = 0; index < this.bones.length; index++) {
  74601. var bone = this.bones[index];
  74602. var parent_2 = bone.getParent();
  74603. var serializedBone = {
  74604. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  74605. name: bone.name,
  74606. matrix: bone.getBaseMatrix().toArray(),
  74607. rest: bone.getRestPose().toArray()
  74608. };
  74609. serializationObject.bones.push(serializedBone);
  74610. if (bone.length) {
  74611. serializedBone.length = bone.length;
  74612. }
  74613. if (bone.animations && bone.animations.length > 0) {
  74614. serializedBone.animation = bone.animations[0].serialize();
  74615. }
  74616. serializationObject.ranges = [];
  74617. for (var name in this._ranges) {
  74618. var source = this._ranges[name];
  74619. if (!source) {
  74620. continue;
  74621. }
  74622. var range = {};
  74623. range.name = name;
  74624. range.from = source.from;
  74625. range.to = source.to;
  74626. serializationObject.ranges.push(range);
  74627. }
  74628. }
  74629. return serializationObject;
  74630. };
  74631. Skeleton.Parse = function (parsedSkeleton, scene) {
  74632. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  74633. if (parsedSkeleton.dimensionsAtRest) {
  74634. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  74635. }
  74636. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  74637. var index;
  74638. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  74639. var parsedBone = parsedSkeleton.bones[index];
  74640. var parentBone = null;
  74641. if (parsedBone.parentBoneIndex > -1) {
  74642. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  74643. }
  74644. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  74645. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  74646. if (parsedBone.length) {
  74647. bone.length = parsedBone.length;
  74648. }
  74649. if (parsedBone.animation) {
  74650. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  74651. }
  74652. }
  74653. // placed after bones, so createAnimationRange can cascade down
  74654. if (parsedSkeleton.ranges) {
  74655. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  74656. var data = parsedSkeleton.ranges[index];
  74657. skeleton.createAnimationRange(data.name, data.from, data.to);
  74658. }
  74659. }
  74660. return skeleton;
  74661. };
  74662. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  74663. if (forceUpdate === void 0) { forceUpdate = false; }
  74664. var renderId = this._scene.getRenderId();
  74665. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  74666. this.bones[0].computeAbsoluteTransforms();
  74667. this._lastAbsoluteTransformsUpdateId = renderId;
  74668. }
  74669. };
  74670. Skeleton.prototype.getPoseMatrix = function () {
  74671. var poseMatrix = null;
  74672. if (this._meshesWithPoseMatrix.length > 0) {
  74673. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  74674. }
  74675. return poseMatrix;
  74676. };
  74677. Skeleton.prototype.sortBones = function () {
  74678. var bones = new Array();
  74679. var visited = new Array(this.bones.length);
  74680. for (var index = 0; index < this.bones.length; index++) {
  74681. this._sortBones(index, bones, visited);
  74682. }
  74683. this.bones = bones;
  74684. };
  74685. Skeleton.prototype._sortBones = function (index, bones, visited) {
  74686. if (visited[index]) {
  74687. return;
  74688. }
  74689. visited[index] = true;
  74690. var bone = this.bones[index];
  74691. if (bone._index === undefined) {
  74692. bone._index = index;
  74693. }
  74694. var parentBone = bone.getParent();
  74695. if (parentBone) {
  74696. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  74697. }
  74698. bones.push(bone);
  74699. };
  74700. return Skeleton;
  74701. }());
  74702. BABYLON.Skeleton = Skeleton;
  74703. })(BABYLON || (BABYLON = {}));
  74704. //# sourceMappingURL=babylon.skeleton.js.map
  74705. "use strict";
  74706. var BABYLON;
  74707. (function (BABYLON) {
  74708. var SphericalPolynomial = /** @class */ (function () {
  74709. function SphericalPolynomial() {
  74710. this.x = BABYLON.Vector3.Zero();
  74711. this.y = BABYLON.Vector3.Zero();
  74712. this.z = BABYLON.Vector3.Zero();
  74713. this.xx = BABYLON.Vector3.Zero();
  74714. this.yy = BABYLON.Vector3.Zero();
  74715. this.zz = BABYLON.Vector3.Zero();
  74716. this.xy = BABYLON.Vector3.Zero();
  74717. this.yz = BABYLON.Vector3.Zero();
  74718. this.zx = BABYLON.Vector3.Zero();
  74719. }
  74720. SphericalPolynomial.prototype.addAmbient = function (color) {
  74721. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  74722. this.xx = this.xx.add(colorVector);
  74723. this.yy = this.yy.add(colorVector);
  74724. this.zz = this.zz.add(colorVector);
  74725. };
  74726. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  74727. var result = new SphericalPolynomial();
  74728. result.x = harmonics.L11.scale(1.02333);
  74729. result.y = harmonics.L1_1.scale(1.02333);
  74730. result.z = harmonics.L10.scale(1.02333);
  74731. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  74732. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  74733. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  74734. result.yz = harmonics.L2_1.scale(0.858086);
  74735. result.zx = harmonics.L21.scale(0.858086);
  74736. result.xy = harmonics.L2_2.scale(0.858086);
  74737. result.scale(1.0 / Math.PI);
  74738. return result;
  74739. };
  74740. SphericalPolynomial.prototype.scale = function (scale) {
  74741. this.x = this.x.scale(scale);
  74742. this.y = this.y.scale(scale);
  74743. this.z = this.z.scale(scale);
  74744. this.xx = this.xx.scale(scale);
  74745. this.yy = this.yy.scale(scale);
  74746. this.zz = this.zz.scale(scale);
  74747. this.yz = this.yz.scale(scale);
  74748. this.zx = this.zx.scale(scale);
  74749. this.xy = this.xy.scale(scale);
  74750. };
  74751. return SphericalPolynomial;
  74752. }());
  74753. BABYLON.SphericalPolynomial = SphericalPolynomial;
  74754. var SphericalHarmonics = /** @class */ (function () {
  74755. function SphericalHarmonics() {
  74756. this.L00 = BABYLON.Vector3.Zero();
  74757. this.L1_1 = BABYLON.Vector3.Zero();
  74758. this.L10 = BABYLON.Vector3.Zero();
  74759. this.L11 = BABYLON.Vector3.Zero();
  74760. this.L2_2 = BABYLON.Vector3.Zero();
  74761. this.L2_1 = BABYLON.Vector3.Zero();
  74762. this.L20 = BABYLON.Vector3.Zero();
  74763. this.L21 = BABYLON.Vector3.Zero();
  74764. this.L22 = BABYLON.Vector3.Zero();
  74765. }
  74766. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  74767. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  74768. var c = colorVector.scale(deltaSolidAngle);
  74769. this.L00 = this.L00.add(c.scale(0.282095));
  74770. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  74771. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  74772. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  74773. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  74774. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  74775. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  74776. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  74777. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  74778. };
  74779. SphericalHarmonics.prototype.scale = function (scale) {
  74780. this.L00 = this.L00.scale(scale);
  74781. this.L1_1 = this.L1_1.scale(scale);
  74782. this.L10 = this.L10.scale(scale);
  74783. this.L11 = this.L11.scale(scale);
  74784. this.L2_2 = this.L2_2.scale(scale);
  74785. this.L2_1 = this.L2_1.scale(scale);
  74786. this.L20 = this.L20.scale(scale);
  74787. this.L21 = this.L21.scale(scale);
  74788. this.L22 = this.L22.scale(scale);
  74789. };
  74790. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  74791. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  74792. //
  74793. // E_lm = A_l * L_lm
  74794. //
  74795. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  74796. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  74797. // the scaling factors are given in equation 9.
  74798. // Constant (Band 0)
  74799. this.L00 = this.L00.scale(3.141593);
  74800. // Linear (Band 1)
  74801. this.L1_1 = this.L1_1.scale(2.094395);
  74802. this.L10 = this.L10.scale(2.094395);
  74803. this.L11 = this.L11.scale(2.094395);
  74804. // Quadratic (Band 2)
  74805. this.L2_2 = this.L2_2.scale(0.785398);
  74806. this.L2_1 = this.L2_1.scale(0.785398);
  74807. this.L20 = this.L20.scale(0.785398);
  74808. this.L21 = this.L21.scale(0.785398);
  74809. this.L22 = this.L22.scale(0.785398);
  74810. };
  74811. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  74812. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  74813. // L = (1/pi) * E * rho
  74814. //
  74815. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  74816. this.scale(1.0 / Math.PI);
  74817. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  74818. // (The pixel shader must apply albedo after texture fetches, etc).
  74819. };
  74820. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  74821. var result = new SphericalHarmonics();
  74822. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  74823. result.L1_1 = polynomial.y.scale(0.977204);
  74824. result.L10 = polynomial.z.scale(0.977204);
  74825. result.L11 = polynomial.x.scale(0.977204);
  74826. result.L2_2 = polynomial.xy.scale(1.16538);
  74827. result.L2_1 = polynomial.yz.scale(1.16538);
  74828. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  74829. result.L21 = polynomial.zx.scale(1.16538);
  74830. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  74831. result.scale(Math.PI);
  74832. return result;
  74833. };
  74834. return SphericalHarmonics;
  74835. }());
  74836. BABYLON.SphericalHarmonics = SphericalHarmonics;
  74837. })(BABYLON || (BABYLON = {}));
  74838. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  74839. "use strict";
  74840. var BABYLON;
  74841. (function (BABYLON) {
  74842. var FileFaceOrientation = /** @class */ (function () {
  74843. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  74844. this.name = name;
  74845. this.worldAxisForNormal = worldAxisForNormal;
  74846. this.worldAxisForFileX = worldAxisForFileX;
  74847. this.worldAxisForFileY = worldAxisForFileY;
  74848. }
  74849. return FileFaceOrientation;
  74850. }());
  74851. ;
  74852. /**
  74853. * Helper class dealing with the extraction of spherical polynomial dataArray
  74854. * from a cube map.
  74855. */
  74856. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  74857. function CubeMapToSphericalPolynomialTools() {
  74858. }
  74859. /**
  74860. * Converts a texture to the according Spherical Polynomial data.
  74861. * This extracts the first 3 orders only as they are the only one used in the lighting.
  74862. *
  74863. * @param texture The texture to extract the information from.
  74864. * @return The Spherical Polynomial data.
  74865. */
  74866. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  74867. if (!texture.isCube) {
  74868. // Only supports cube Textures currently.
  74869. return null;
  74870. }
  74871. var size = texture.getSize().width;
  74872. var right = texture.readPixels(0);
  74873. var left = texture.readPixels(1);
  74874. var up;
  74875. var down;
  74876. if (texture.isRenderTarget) {
  74877. up = texture.readPixels(3);
  74878. down = texture.readPixels(2);
  74879. }
  74880. else {
  74881. up = texture.readPixels(2);
  74882. down = texture.readPixels(3);
  74883. }
  74884. var front = texture.readPixels(4);
  74885. var back = texture.readPixels(5);
  74886. var gammaSpace = texture.gammaSpace;
  74887. // Always read as RGBA.
  74888. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  74889. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  74890. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  74891. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  74892. }
  74893. var cubeInfo = {
  74894. size: size,
  74895. right: right,
  74896. left: left,
  74897. up: up,
  74898. down: down,
  74899. front: front,
  74900. back: back,
  74901. format: format,
  74902. type: type,
  74903. gammaSpace: gammaSpace,
  74904. };
  74905. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  74906. };
  74907. /**
  74908. * Converts a cubemap to the according Spherical Polynomial data.
  74909. * This extracts the first 3 orders only as they are the only one used in the lighting.
  74910. *
  74911. * @param cubeInfo The Cube map to extract the information from.
  74912. * @return The Spherical Polynomial data.
  74913. */
  74914. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  74915. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  74916. var totalSolidAngle = 0.0;
  74917. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  74918. var du = 2.0 / cubeInfo.size;
  74919. var dv = du;
  74920. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  74921. var minUV = du * 0.5 - 1.0;
  74922. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  74923. var fileFace = this.FileFaces[faceIndex];
  74924. var dataArray = cubeInfo[fileFace.name];
  74925. var v = minUV;
  74926. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  74927. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  74928. // Because SP is still linear, so summation is fine in that basis.
  74929. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  74930. for (var y = 0; y < cubeInfo.size; y++) {
  74931. var u = minUV;
  74932. for (var x = 0; x < cubeInfo.size; x++) {
  74933. // World direction (not normalised)
  74934. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  74935. worldDirection.normalize();
  74936. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  74937. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  74938. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  74939. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  74940. // Handle Integer types.
  74941. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  74942. r /= 255;
  74943. g /= 255;
  74944. b /= 255;
  74945. }
  74946. // Handle Gamma space textures.
  74947. if (cubeInfo.gammaSpace) {
  74948. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  74949. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  74950. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  74951. }
  74952. var color = new BABYLON.Color3(r, g, b);
  74953. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  74954. totalSolidAngle += deltaSolidAngle;
  74955. u += du;
  74956. }
  74957. v += dv;
  74958. }
  74959. }
  74960. // Solid angle for entire sphere is 4*pi
  74961. var sphereSolidAngle = 4.0 * Math.PI;
  74962. // Adjust the solid angle to allow for how many faces we processed.
  74963. var facesProcessed = 6.0;
  74964. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  74965. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  74966. // This is needed because the numerical integration over the cube uses a
  74967. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  74968. // and also to compensate for accumulative error due to float precision in the summation.
  74969. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  74970. sphericalHarmonics.scale(correctionFactor);
  74971. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  74972. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  74973. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  74974. };
  74975. CubeMapToSphericalPolynomialTools.FileFaces = [
  74976. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  74977. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  74978. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  74979. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  74980. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  74981. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  74982. ];
  74983. return CubeMapToSphericalPolynomialTools;
  74984. }());
  74985. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  74986. })(BABYLON || (BABYLON = {}));
  74987. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  74988. "use strict";
  74989. var BABYLON;
  74990. (function (BABYLON) {
  74991. /**
  74992. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  74993. */
  74994. var PanoramaToCubeMapTools = /** @class */ (function () {
  74995. function PanoramaToCubeMapTools() {
  74996. }
  74997. /**
  74998. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  74999. *
  75000. * @param float32Array The source data.
  75001. * @param inputWidth The width of the input panorama.
  75002. * @param inputhHeight The height of the input panorama.
  75003. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  75004. * @return The cubemap data
  75005. */
  75006. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  75007. if (!float32Array) {
  75008. throw "ConvertPanoramaToCubemap: input cannot be null";
  75009. }
  75010. if (float32Array.length != inputWidth * inputHeight * 3) {
  75011. throw "ConvertPanoramaToCubemap: input size is wrong";
  75012. }
  75013. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  75014. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  75015. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  75016. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  75017. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  75018. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  75019. return {
  75020. front: textureFront,
  75021. back: textureBack,
  75022. left: textureLeft,
  75023. right: textureRight,
  75024. up: textureUp,
  75025. down: textureDown,
  75026. size: size,
  75027. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  75028. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  75029. gammaSpace: false,
  75030. };
  75031. };
  75032. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  75033. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  75034. var textureArray = new Float32Array(buffer);
  75035. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  75036. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  75037. var dy = 1 / texSize;
  75038. var fy = 0;
  75039. for (var y = 0; y < texSize; y++) {
  75040. var xv1 = faceData[0];
  75041. var xv2 = faceData[2];
  75042. for (var x = 0; x < texSize; x++) {
  75043. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  75044. v.normalize();
  75045. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  75046. // 3 channels per pixels
  75047. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  75048. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  75049. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  75050. xv1 = xv1.add(rotDX1);
  75051. xv2 = xv2.add(rotDX2);
  75052. }
  75053. fy += dy;
  75054. }
  75055. return textureArray;
  75056. };
  75057. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  75058. var theta = Math.atan2(vDir.z, vDir.x);
  75059. var phi = Math.acos(vDir.y);
  75060. while (theta < -Math.PI)
  75061. theta += 2 * Math.PI;
  75062. while (theta > Math.PI)
  75063. theta -= 2 * Math.PI;
  75064. var dx = theta / Math.PI;
  75065. var dy = phi / Math.PI;
  75066. // recenter.
  75067. dx = dx * 0.5 + 0.5;
  75068. var px = Math.round(dx * inputWidth);
  75069. if (px < 0)
  75070. px = 0;
  75071. else if (px >= inputWidth)
  75072. px = inputWidth - 1;
  75073. var py = Math.round(dy * inputHeight);
  75074. if (py < 0)
  75075. py = 0;
  75076. else if (py >= inputHeight)
  75077. py = inputHeight - 1;
  75078. var inputY = (inputHeight - py - 1);
  75079. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  75080. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  75081. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  75082. return {
  75083. r: r,
  75084. g: g,
  75085. b: b
  75086. };
  75087. };
  75088. PanoramaToCubeMapTools.FACE_FRONT = [
  75089. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  75090. new BABYLON.Vector3(1.0, -1.0, -1.0),
  75091. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  75092. new BABYLON.Vector3(1.0, 1.0, -1.0)
  75093. ];
  75094. PanoramaToCubeMapTools.FACE_BACK = [
  75095. new BABYLON.Vector3(1.0, -1.0, 1.0),
  75096. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  75097. new BABYLON.Vector3(1.0, 1.0, 1.0),
  75098. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  75099. ];
  75100. PanoramaToCubeMapTools.FACE_RIGHT = [
  75101. new BABYLON.Vector3(1.0, -1.0, -1.0),
  75102. new BABYLON.Vector3(1.0, -1.0, 1.0),
  75103. new BABYLON.Vector3(1.0, 1.0, -1.0),
  75104. new BABYLON.Vector3(1.0, 1.0, 1.0)
  75105. ];
  75106. PanoramaToCubeMapTools.FACE_LEFT = [
  75107. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  75108. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  75109. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  75110. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  75111. ];
  75112. PanoramaToCubeMapTools.FACE_DOWN = [
  75113. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  75114. new BABYLON.Vector3(1.0, 1.0, -1.0),
  75115. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  75116. new BABYLON.Vector3(1.0, 1.0, 1.0)
  75117. ];
  75118. PanoramaToCubeMapTools.FACE_UP = [
  75119. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  75120. new BABYLON.Vector3(1.0, -1.0, 1.0),
  75121. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  75122. new BABYLON.Vector3(1.0, -1.0, -1.0)
  75123. ];
  75124. return PanoramaToCubeMapTools;
  75125. }());
  75126. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  75127. })(BABYLON || (BABYLON = {}));
  75128. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  75129. "use strict";
  75130. var BABYLON;
  75131. (function (BABYLON) {
  75132. ;
  75133. /**
  75134. * This groups tools to convert HDR texture to native colors array.
  75135. */
  75136. var HDRTools = /** @class */ (function () {
  75137. function HDRTools() {
  75138. }
  75139. HDRTools.Ldexp = function (mantissa, exponent) {
  75140. if (exponent > 1023) {
  75141. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  75142. }
  75143. if (exponent < -1074) {
  75144. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  75145. }
  75146. return mantissa * Math.pow(2, exponent);
  75147. };
  75148. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  75149. if (exponent > 0) {
  75150. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  75151. float32array[index + 0] = red * exponent;
  75152. float32array[index + 1] = green * exponent;
  75153. float32array[index + 2] = blue * exponent;
  75154. }
  75155. else {
  75156. float32array[index + 0] = 0;
  75157. float32array[index + 1] = 0;
  75158. float32array[index + 2] = 0;
  75159. }
  75160. };
  75161. HDRTools.readStringLine = function (uint8array, startIndex) {
  75162. var line = "";
  75163. var character = "";
  75164. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  75165. character = String.fromCharCode(uint8array[i]);
  75166. if (character == "\n") {
  75167. break;
  75168. }
  75169. line += character;
  75170. }
  75171. return line;
  75172. };
  75173. /**
  75174. * Reads header information from an RGBE texture stored in a native array.
  75175. * More information on this format are available here:
  75176. * https://en.wikipedia.org/wiki/RGBE_image_format
  75177. *
  75178. * @param uint8array The binary file stored in native array.
  75179. * @return The header information.
  75180. */
  75181. HDRTools.RGBE_ReadHeader = function (uint8array) {
  75182. var height = 0;
  75183. var width = 0;
  75184. var line = this.readStringLine(uint8array, 0);
  75185. if (line[0] != '#' || line[1] != '?') {
  75186. throw "Bad HDR Format.";
  75187. }
  75188. var endOfHeader = false;
  75189. var findFormat = false;
  75190. var lineIndex = 0;
  75191. do {
  75192. lineIndex += (line.length + 1);
  75193. line = this.readStringLine(uint8array, lineIndex);
  75194. if (line == "FORMAT=32-bit_rle_rgbe") {
  75195. findFormat = true;
  75196. }
  75197. else if (line.length == 0) {
  75198. endOfHeader = true;
  75199. }
  75200. } while (!endOfHeader);
  75201. if (!findFormat) {
  75202. throw "HDR Bad header format, unsupported FORMAT";
  75203. }
  75204. lineIndex += (line.length + 1);
  75205. line = this.readStringLine(uint8array, lineIndex);
  75206. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  75207. var match = sizeRegexp.exec(line);
  75208. // TODO. Support +Y and -X if needed.
  75209. if (!match || match.length < 3) {
  75210. throw "HDR Bad header format, no size";
  75211. }
  75212. width = parseInt(match[2]);
  75213. height = parseInt(match[1]);
  75214. if (width < 8 || width > 0x7fff) {
  75215. throw "HDR Bad header format, unsupported size";
  75216. }
  75217. lineIndex += (line.length + 1);
  75218. return {
  75219. height: height,
  75220. width: width,
  75221. dataPosition: lineIndex
  75222. };
  75223. };
  75224. /**
  75225. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  75226. * This RGBE texture needs to store the information as a panorama.
  75227. *
  75228. * More information on this format are available here:
  75229. * https://en.wikipedia.org/wiki/RGBE_image_format
  75230. *
  75231. * @param buffer The binary file stored in an array buffer.
  75232. * @param size The expected size of the extracted cubemap.
  75233. * @return The Cube Map information.
  75234. */
  75235. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  75236. var uint8array = new Uint8Array(buffer);
  75237. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  75238. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  75239. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  75240. return cubeMapData;
  75241. };
  75242. /**
  75243. * Returns the pixels data extracted from an RGBE texture.
  75244. * This pixels will be stored left to right up to down in the R G B order in one array.
  75245. *
  75246. * More information on this format are available here:
  75247. * https://en.wikipedia.org/wiki/RGBE_image_format
  75248. *
  75249. * @param uint8array The binary file stored in an array buffer.
  75250. * @param hdrInfo The header information of the file.
  75251. * @return The pixels data in RGB right to left up to down order.
  75252. */
  75253. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  75254. // Keep for multi format supports.
  75255. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  75256. };
  75257. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  75258. var num_scanlines = hdrInfo.height;
  75259. var scanline_width = hdrInfo.width;
  75260. var a, b, c, d, count;
  75261. var dataIndex = hdrInfo.dataPosition;
  75262. var index = 0, endIndex = 0, i = 0;
  75263. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  75264. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  75265. // 3 channels of 4 bytes per pixel in float.
  75266. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  75267. var resultArray = new Float32Array(resultBuffer);
  75268. // read in each successive scanline
  75269. while (num_scanlines > 0) {
  75270. a = uint8array[dataIndex++];
  75271. b = uint8array[dataIndex++];
  75272. c = uint8array[dataIndex++];
  75273. d = uint8array[dataIndex++];
  75274. if (a != 2 || b != 2 || (c & 0x80)) {
  75275. // this file is not run length encoded
  75276. throw "HDR Bad header format, not RLE";
  75277. }
  75278. if (((c << 8) | d) != scanline_width) {
  75279. throw "HDR Bad header format, wrong scan line width";
  75280. }
  75281. index = 0;
  75282. // read each of the four channels for the scanline into the buffer
  75283. for (i = 0; i < 4; i++) {
  75284. endIndex = (i + 1) * scanline_width;
  75285. while (index < endIndex) {
  75286. a = uint8array[dataIndex++];
  75287. b = uint8array[dataIndex++];
  75288. if (a > 128) {
  75289. // a run of the same value
  75290. count = a - 128;
  75291. if ((count == 0) || (count > endIndex - index)) {
  75292. throw "HDR Bad Format, bad scanline data (run)";
  75293. }
  75294. while (count-- > 0) {
  75295. scanLineArray[index++] = b;
  75296. }
  75297. }
  75298. else {
  75299. // a non-run
  75300. count = a;
  75301. if ((count == 0) || (count > endIndex - index)) {
  75302. throw "HDR Bad Format, bad scanline data (non-run)";
  75303. }
  75304. scanLineArray[index++] = b;
  75305. if (--count > 0) {
  75306. for (var j = 0; j < count; j++) {
  75307. scanLineArray[index++] = uint8array[dataIndex++];
  75308. }
  75309. }
  75310. }
  75311. }
  75312. }
  75313. // now convert data from buffer into floats
  75314. for (i = 0; i < scanline_width; i++) {
  75315. a = scanLineArray[i];
  75316. b = scanLineArray[i + scanline_width];
  75317. c = scanLineArray[i + 2 * scanline_width];
  75318. d = scanLineArray[i + 3 * scanline_width];
  75319. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  75320. }
  75321. num_scanlines--;
  75322. }
  75323. return resultArray;
  75324. };
  75325. return HDRTools;
  75326. }());
  75327. BABYLON.HDRTools = HDRTools;
  75328. })(BABYLON || (BABYLON = {}));
  75329. //# sourceMappingURL=babylon.hdr.js.map
  75330. "use strict";
  75331. var BABYLON;
  75332. (function (BABYLON) {
  75333. /**
  75334. * This represents a texture coming from an HDR input.
  75335. *
  75336. * The only supported format is currently panorama picture stored in RGBE format.
  75337. * Example of such files can be found on HDRLib: http://hdrlib.com/
  75338. */
  75339. var HDRCubeTexture = /** @class */ (function (_super) {
  75340. __extends(HDRCubeTexture, _super);
  75341. /**
  75342. * Instantiates an HDRTexture from the following parameters.
  75343. *
  75344. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  75345. * @param scene The scene the texture will be used in
  75346. * @param size The cubemap 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.
  75347. * @param noMipmap Forces to not generate the mipmap if true
  75348. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  75349. * @param useInGammaSpace 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)
  75350. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  75351. */
  75352. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  75353. if (noMipmap === void 0) { noMipmap = false; }
  75354. if (generateHarmonics === void 0) { generateHarmonics = true; }
  75355. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  75356. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  75357. if (onLoad === void 0) { onLoad = null; }
  75358. if (onError === void 0) { onError = null; }
  75359. var _this = _super.call(this, scene) || this;
  75360. _this._useInGammaSpace = false;
  75361. _this._generateHarmonics = true;
  75362. _this._isBABYLONPreprocessed = false;
  75363. _this._onLoad = null;
  75364. _this._onError = null;
  75365. /**
  75366. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  75367. */
  75368. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  75369. /**
  75370. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  75371. * This is usefull at run time to apply the good shader.
  75372. */
  75373. _this.isPMREM = false;
  75374. _this._isBlocking = true;
  75375. /**
  75376. * Gets or sets the center of the bounding box associated with the cube texture
  75377. * It must define where the camera used to render the texture was set
  75378. */
  75379. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  75380. if (!url) {
  75381. return _this;
  75382. }
  75383. _this.name = url;
  75384. _this.url = url;
  75385. _this.hasAlpha = false;
  75386. _this.isCube = true;
  75387. _this._textureMatrix = BABYLON.Matrix.Identity();
  75388. _this._onLoad = onLoad;
  75389. _this._onError = onError;
  75390. _this.gammaSpace = false;
  75391. var caps = scene.getEngine().getCaps();
  75392. if (size) {
  75393. _this._isBABYLONPreprocessed = false;
  75394. _this._noMipmap = noMipmap;
  75395. _this._size = size;
  75396. _this._useInGammaSpace = useInGammaSpace;
  75397. _this._usePMREMGenerator = usePMREMGenerator &&
  75398. caps.textureLOD &&
  75399. caps.textureFloat &&
  75400. !_this._useInGammaSpace;
  75401. }
  75402. else {
  75403. _this._isBABYLONPreprocessed = true;
  75404. _this._noMipmap = false;
  75405. _this._useInGammaSpace = false;
  75406. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  75407. !_this._useInGammaSpace;
  75408. }
  75409. _this.isPMREM = _this._usePMREMGenerator;
  75410. _this._texture = _this._getFromCache(url, _this._noMipmap);
  75411. if (!_this._texture) {
  75412. if (!scene.useDelayedTextureLoading) {
  75413. _this.loadTexture();
  75414. }
  75415. else {
  75416. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  75417. }
  75418. }
  75419. return _this;
  75420. }
  75421. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  75422. /**
  75423. * Gets wether or not the texture is blocking during loading.
  75424. */
  75425. get: function () {
  75426. return this._isBlocking;
  75427. },
  75428. /**
  75429. * Sets wether or not the texture is blocking during loading.
  75430. */
  75431. set: function (value) {
  75432. this._isBlocking = value;
  75433. },
  75434. enumerable: true,
  75435. configurable: true
  75436. });
  75437. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  75438. get: function () {
  75439. return this._boundingBoxSize;
  75440. },
  75441. /**
  75442. * Gets or sets the size of the bounding box associated with the cube texture
  75443. * When defined, the cubemap will switch to local mode
  75444. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  75445. * @example https://www.babylonjs-playground.com/#RNASML
  75446. */
  75447. set: function (value) {
  75448. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  75449. return;
  75450. }
  75451. this._boundingBoxSize = value;
  75452. var scene = this.getScene();
  75453. if (scene) {
  75454. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  75455. }
  75456. },
  75457. enumerable: true,
  75458. configurable: true
  75459. });
  75460. /**
  75461. * Occurs when the file is a preprocessed .babylon.hdr file.
  75462. */
  75463. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  75464. var _this = this;
  75465. var mipLevels = 0;
  75466. var floatArrayView = null;
  75467. var scene = this.getScene();
  75468. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  75469. var mips = new Array();
  75470. if (!floatArrayView) {
  75471. return mips;
  75472. }
  75473. var startIndex = 30;
  75474. for (var level = 0; level < mipLevels; level++) {
  75475. mips.push([]);
  75476. // Fill each pixel of the mip level.
  75477. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  75478. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  75479. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  75480. mips[level].push(faceData);
  75481. startIndex += faceSize;
  75482. }
  75483. }
  75484. return mips;
  75485. } : null;
  75486. var callback = function (buffer) {
  75487. var scene = _this.getScene();
  75488. if (!scene) {
  75489. return null;
  75490. }
  75491. // Create Native Array Views
  75492. var intArrayView = new Int32Array(buffer);
  75493. floatArrayView = new Float32Array(buffer);
  75494. // Fill header.
  75495. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  75496. _this._size = intArrayView[1]; // CubeMap max mip face size.
  75497. // Update Texture Information.
  75498. if (!_this._texture) {
  75499. return null;
  75500. }
  75501. _this._texture.updateSize(_this._size, _this._size);
  75502. // Fill polynomial information.
  75503. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  75504. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  75505. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  75506. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  75507. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  75508. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  75509. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  75510. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  75511. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  75512. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  75513. _this.sphericalPolynomial = sphericalPolynomial;
  75514. // Fill pixel data.
  75515. mipLevels = intArrayView[29]; // Number of mip levels.
  75516. var startIndex = 30;
  75517. var data = [];
  75518. var faceSize = Math.pow(_this._size, 2) * 3;
  75519. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  75520. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  75521. startIndex += faceSize;
  75522. }
  75523. var results = [];
  75524. var byteArray = null;
  75525. // Push each faces.
  75526. for (var k = 0; k < 6; k++) {
  75527. var dataFace = null;
  75528. // To be deprecated.
  75529. if (version === 1) {
  75530. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  75531. dataFace = data[j];
  75532. }
  75533. // If special cases.
  75534. if (!mipmapGenerator && dataFace) {
  75535. if (!scene.getEngine().getCaps().textureFloat) {
  75536. // 3 channels of 1 bytes per pixel in bytes.
  75537. var byteBuffer = new ArrayBuffer(faceSize);
  75538. byteArray = new Uint8Array(byteBuffer);
  75539. }
  75540. for (var i = 0; i < _this._size * _this._size; i++) {
  75541. // Put in gamma space if requested.
  75542. if (_this._useInGammaSpace) {
  75543. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  75544. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  75545. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  75546. }
  75547. // Convert to int texture for fallback.
  75548. if (byteArray) {
  75549. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  75550. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  75551. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  75552. // May use luminance instead if the result is not accurate.
  75553. var max = Math.max(Math.max(r, g), b);
  75554. if (max > 255) {
  75555. var scale = 255 / max;
  75556. r *= scale;
  75557. g *= scale;
  75558. b *= scale;
  75559. }
  75560. byteArray[(i * 3) + 0] = r;
  75561. byteArray[(i * 3) + 1] = g;
  75562. byteArray[(i * 3) + 2] = b;
  75563. }
  75564. }
  75565. }
  75566. // Fill the array accordingly.
  75567. if (byteArray) {
  75568. results.push(byteArray);
  75569. }
  75570. else {
  75571. results.push(dataFace);
  75572. }
  75573. }
  75574. return results;
  75575. };
  75576. if (scene) {
  75577. 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, mipmapGenerator, this._onLoad, this._onError);
  75578. }
  75579. };
  75580. /**
  75581. * Occurs when the file is raw .hdr file.
  75582. */
  75583. HDRCubeTexture.prototype.loadHDRTexture = function () {
  75584. var _this = this;
  75585. var callback = function (buffer) {
  75586. var scene = _this.getScene();
  75587. if (!scene) {
  75588. return null;
  75589. }
  75590. // Extract the raw linear data.
  75591. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  75592. // Generate harmonics if needed.
  75593. if (_this._generateHarmonics) {
  75594. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  75595. _this.sphericalPolynomial = sphericalPolynomial;
  75596. }
  75597. var results = [];
  75598. var byteArray = null;
  75599. // Push each faces.
  75600. for (var j = 0; j < 6; j++) {
  75601. // Create uintarray fallback.
  75602. if (!scene.getEngine().getCaps().textureFloat) {
  75603. // 3 channels of 1 bytes per pixel in bytes.
  75604. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  75605. byteArray = new Uint8Array(byteBuffer);
  75606. }
  75607. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  75608. // If special cases.
  75609. if (_this._useInGammaSpace || byteArray) {
  75610. for (var i = 0; i < _this._size * _this._size; i++) {
  75611. // Put in gamma space if requested.
  75612. if (_this._useInGammaSpace) {
  75613. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  75614. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  75615. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  75616. }
  75617. // Convert to int texture for fallback.
  75618. if (byteArray) {
  75619. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  75620. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  75621. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  75622. // May use luminance instead if the result is not accurate.
  75623. var max = Math.max(Math.max(r, g), b);
  75624. if (max > 255) {
  75625. var scale = 255 / max;
  75626. r *= scale;
  75627. g *= scale;
  75628. b *= scale;
  75629. }
  75630. byteArray[(i * 3) + 0] = r;
  75631. byteArray[(i * 3) + 1] = g;
  75632. byteArray[(i * 3) + 2] = b;
  75633. }
  75634. }
  75635. }
  75636. if (byteArray) {
  75637. results.push(byteArray);
  75638. }
  75639. else {
  75640. results.push(dataFace);
  75641. }
  75642. }
  75643. return results;
  75644. };
  75645. var mipmapGenerator = null;
  75646. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  75647. // if (!this._noMipmap &&
  75648. // this._usePMREMGenerator) {
  75649. // mipmapGenerator = (data: ArrayBufferView[]) => {
  75650. // // Custom setup of the generator matching with the PBR shader values.
  75651. // var generator = new BABYLON.PMREMGenerator(data,
  75652. // this._size,
  75653. // this._size,
  75654. // 0,
  75655. // 3,
  75656. // this.getScene().getEngine().getCaps().textureFloat,
  75657. // 2048,
  75658. // 0.25,
  75659. // false,
  75660. // true);
  75661. // return generator.filterCubeMap();
  75662. // };
  75663. // }
  75664. var scene = this.getScene();
  75665. if (scene) {
  75666. 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, mipmapGenerator, this._onLoad, this._onError);
  75667. }
  75668. };
  75669. /**
  75670. * Starts the loading process of the texture.
  75671. */
  75672. HDRCubeTexture.prototype.loadTexture = function () {
  75673. if (this._isBABYLONPreprocessed) {
  75674. this.loadBabylonTexture();
  75675. }
  75676. else {
  75677. this.loadHDRTexture();
  75678. }
  75679. };
  75680. HDRCubeTexture.prototype.clone = function () {
  75681. var scene = this.getScene();
  75682. if (!scene) {
  75683. return this;
  75684. }
  75685. var size = (this._isBABYLONPreprocessed ? null : this._size);
  75686. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  75687. // Base texture
  75688. newTexture.level = this.level;
  75689. newTexture.wrapU = this.wrapU;
  75690. newTexture.wrapV = this.wrapV;
  75691. newTexture.coordinatesIndex = this.coordinatesIndex;
  75692. newTexture.coordinatesMode = this.coordinatesMode;
  75693. return newTexture;
  75694. };
  75695. // Methods
  75696. HDRCubeTexture.prototype.delayLoad = function () {
  75697. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  75698. return;
  75699. }
  75700. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  75701. this._texture = this._getFromCache(this.url, this._noMipmap);
  75702. if (!this._texture) {
  75703. this.loadTexture();
  75704. }
  75705. };
  75706. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  75707. return this._textureMatrix;
  75708. };
  75709. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  75710. this._textureMatrix = value;
  75711. };
  75712. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  75713. var texture = null;
  75714. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  75715. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  75716. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  75717. texture.name = parsedTexture.name;
  75718. texture.hasAlpha = parsedTexture.hasAlpha;
  75719. texture.level = parsedTexture.level;
  75720. texture.coordinatesMode = parsedTexture.coordinatesMode;
  75721. texture.isBlocking = parsedTexture.isBlocking;
  75722. }
  75723. if (texture) {
  75724. if (parsedTexture.boundingBoxPosition) {
  75725. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  75726. }
  75727. if (parsedTexture.boundingBoxSize) {
  75728. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  75729. }
  75730. }
  75731. return texture;
  75732. };
  75733. HDRCubeTexture.prototype.serialize = function () {
  75734. if (!this.name) {
  75735. return null;
  75736. }
  75737. var serializationObject = {};
  75738. serializationObject.name = this.name;
  75739. serializationObject.hasAlpha = this.hasAlpha;
  75740. serializationObject.isCube = true;
  75741. serializationObject.level = this.level;
  75742. serializationObject.size = this._size;
  75743. serializationObject.coordinatesMode = this.coordinatesMode;
  75744. serializationObject.useInGammaSpace = this._useInGammaSpace;
  75745. serializationObject.generateHarmonics = this._generateHarmonics;
  75746. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  75747. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  75748. serializationObject.customType = "BABYLON.HDRCubeTexture";
  75749. serializationObject.noMipmap = this._noMipmap;
  75750. serializationObject.isBlocking = this._isBlocking;
  75751. return serializationObject;
  75752. };
  75753. /**
  75754. * Saves as a file the data contained in the texture in a binary format.
  75755. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  75756. * as the spherical used in the lighting.
  75757. * @param url The HDR file url.
  75758. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  75759. * @param onError Method called if any error happens during download.
  75760. * @return The packed binary data.
  75761. */
  75762. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  75763. if (onError === void 0) { onError = null; }
  75764. var callback = function (buffer) {
  75765. var data = new Blob([buffer], { type: 'application/octet-stream' });
  75766. // Returns a URL you can use as a href.
  75767. var objUrl = window.URL.createObjectURL(data);
  75768. // Simulates a link to it and click to dowload.
  75769. var a = document.createElement("a");
  75770. document.body.appendChild(a);
  75771. a.style.display = "none";
  75772. a.href = objUrl;
  75773. a.download = "envmap.babylon.hdr";
  75774. a.click();
  75775. };
  75776. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  75777. };
  75778. /**
  75779. * Serializes the data contained in the texture in a binary format.
  75780. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  75781. * as the spherical used in the lighting.
  75782. * @param url The HDR file url.
  75783. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  75784. * @param onError Method called if any error happens during download.
  75785. * @return The packed binary data.
  75786. */
  75787. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  75788. if (onError === void 0) { onError = null; }
  75789. // Needs the url tho create the texture.
  75790. if (!url) {
  75791. return;
  75792. }
  75793. // Check Power of two size.
  75794. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  75795. return;
  75796. }
  75797. // Coming Back in 3.x.
  75798. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  75799. };
  75800. HDRCubeTexture._facesMapping = [
  75801. "right",
  75802. "left",
  75803. "up",
  75804. "down",
  75805. "front",
  75806. "back"
  75807. ];
  75808. return HDRCubeTexture;
  75809. }(BABYLON.BaseTexture));
  75810. BABYLON.HDRCubeTexture = HDRCubeTexture;
  75811. })(BABYLON || (BABYLON = {}));
  75812. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  75813. "use strict";
  75814. var BABYLON;
  75815. (function (BABYLON) {
  75816. var IndexedVector2 = /** @class */ (function (_super) {
  75817. __extends(IndexedVector2, _super);
  75818. function IndexedVector2(original, index) {
  75819. var _this = _super.call(this, original.x, original.y) || this;
  75820. _this.index = index;
  75821. return _this;
  75822. }
  75823. return IndexedVector2;
  75824. }(BABYLON.Vector2));
  75825. var PolygonPoints = /** @class */ (function () {
  75826. function PolygonPoints() {
  75827. this.elements = new Array();
  75828. }
  75829. PolygonPoints.prototype.add = function (originalPoints) {
  75830. var _this = this;
  75831. var result = new Array();
  75832. originalPoints.forEach(function (point) {
  75833. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  75834. var newPoint = new IndexedVector2(point, _this.elements.length);
  75835. result.push(newPoint);
  75836. _this.elements.push(newPoint);
  75837. }
  75838. });
  75839. return result;
  75840. };
  75841. PolygonPoints.prototype.computeBounds = function () {
  75842. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  75843. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  75844. this.elements.forEach(function (point) {
  75845. // x
  75846. if (point.x < lmin.x) {
  75847. lmin.x = point.x;
  75848. }
  75849. else if (point.x > lmax.x) {
  75850. lmax.x = point.x;
  75851. }
  75852. // y
  75853. if (point.y < lmin.y) {
  75854. lmin.y = point.y;
  75855. }
  75856. else if (point.y > lmax.y) {
  75857. lmax.y = point.y;
  75858. }
  75859. });
  75860. return {
  75861. min: lmin,
  75862. max: lmax,
  75863. width: lmax.x - lmin.x,
  75864. height: lmax.y - lmin.y
  75865. };
  75866. };
  75867. return PolygonPoints;
  75868. }());
  75869. var Polygon = /** @class */ (function () {
  75870. function Polygon() {
  75871. }
  75872. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  75873. return [
  75874. new BABYLON.Vector2(xmin, ymin),
  75875. new BABYLON.Vector2(xmax, ymin),
  75876. new BABYLON.Vector2(xmax, ymax),
  75877. new BABYLON.Vector2(xmin, ymax)
  75878. ];
  75879. };
  75880. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  75881. if (cx === void 0) { cx = 0; }
  75882. if (cy === void 0) { cy = 0; }
  75883. if (numberOfSides === void 0) { numberOfSides = 32; }
  75884. var result = new Array();
  75885. var angle = 0;
  75886. var increment = (Math.PI * 2) / numberOfSides;
  75887. for (var i = 0; i < numberOfSides; i++) {
  75888. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  75889. angle -= increment;
  75890. }
  75891. return result;
  75892. };
  75893. Polygon.Parse = function (input) {
  75894. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  75895. var i, result = [];
  75896. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  75897. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  75898. }
  75899. return result;
  75900. };
  75901. Polygon.StartingAt = function (x, y) {
  75902. return BABYLON.Path2.StartingAt(x, y);
  75903. };
  75904. return Polygon;
  75905. }());
  75906. BABYLON.Polygon = Polygon;
  75907. var PolygonMeshBuilder = /** @class */ (function () {
  75908. function PolygonMeshBuilder(name, contours, scene) {
  75909. this._points = new PolygonPoints();
  75910. this._outlinepoints = new PolygonPoints();
  75911. this._holes = new Array();
  75912. this._epoints = new Array();
  75913. this._eholes = new Array();
  75914. this._name = name;
  75915. this._scene = scene;
  75916. var points;
  75917. if (contours instanceof BABYLON.Path2) {
  75918. points = contours.getPoints();
  75919. }
  75920. else {
  75921. points = contours;
  75922. }
  75923. this._addToepoint(points);
  75924. this._points.add(points);
  75925. this._outlinepoints.add(points);
  75926. if (typeof earcut === 'undefined') {
  75927. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  75928. }
  75929. }
  75930. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  75931. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  75932. var p = points_1[_i];
  75933. this._epoints.push(p.x, p.y);
  75934. }
  75935. };
  75936. PolygonMeshBuilder.prototype.addHole = function (hole) {
  75937. this._points.add(hole);
  75938. var holepoints = new PolygonPoints();
  75939. holepoints.add(hole);
  75940. this._holes.push(holepoints);
  75941. this._eholes.push(this._epoints.length / 2);
  75942. this._addToepoint(hole);
  75943. return this;
  75944. };
  75945. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  75946. var _this = this;
  75947. if (updatable === void 0) { updatable = false; }
  75948. if (depth === void 0) { depth = 0; }
  75949. var result = new BABYLON.Mesh(this._name, this._scene);
  75950. var normals = new Array();
  75951. var positions = new Array();
  75952. var uvs = new Array();
  75953. var bounds = this._points.computeBounds();
  75954. this._points.elements.forEach(function (p) {
  75955. normals.push(0, 1.0, 0);
  75956. positions.push(p.x, 0, p.y);
  75957. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  75958. });
  75959. var indices = new Array();
  75960. var res = earcut(this._epoints, this._eholes, 2);
  75961. for (var i = 0; i < res.length; i++) {
  75962. indices.push(res[i]);
  75963. }
  75964. if (depth > 0) {
  75965. var positionscount = (positions.length / 3); //get the current pointcount
  75966. this._points.elements.forEach(function (p) {
  75967. normals.push(0, -1.0, 0);
  75968. positions.push(p.x, -depth, p.y);
  75969. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  75970. });
  75971. var totalCount = indices.length;
  75972. for (var i = 0; i < totalCount; i += 3) {
  75973. var i0 = indices[i + 0];
  75974. var i1 = indices[i + 1];
  75975. var i2 = indices[i + 2];
  75976. indices.push(i2 + positionscount);
  75977. indices.push(i1 + positionscount);
  75978. indices.push(i0 + positionscount);
  75979. }
  75980. //Add the sides
  75981. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  75982. this._holes.forEach(function (hole) {
  75983. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  75984. });
  75985. }
  75986. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  75987. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  75988. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  75989. result.setIndices(indices);
  75990. return result;
  75991. };
  75992. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  75993. var StartIndex = positions.length / 3;
  75994. var ulength = 0;
  75995. for (var i = 0; i < points.elements.length; i++) {
  75996. var p = points.elements[i];
  75997. var p1;
  75998. if ((i + 1) > points.elements.length - 1) {
  75999. p1 = points.elements[0];
  76000. }
  76001. else {
  76002. p1 = points.elements[i + 1];
  76003. }
  76004. positions.push(p.x, 0, p.y);
  76005. positions.push(p.x, -depth, p.y);
  76006. positions.push(p1.x, 0, p1.y);
  76007. positions.push(p1.x, -depth, p1.y);
  76008. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  76009. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  76010. var v3 = v2.subtract(v1);
  76011. var v4 = new BABYLON.Vector3(0, 1, 0);
  76012. var vn = BABYLON.Vector3.Cross(v3, v4);
  76013. vn = vn.normalize();
  76014. uvs.push(ulength / bounds.width, 0);
  76015. uvs.push(ulength / bounds.width, 1);
  76016. ulength += v3.length();
  76017. uvs.push((ulength / bounds.width), 0);
  76018. uvs.push((ulength / bounds.width), 1);
  76019. if (!flip) {
  76020. normals.push(-vn.x, -vn.y, -vn.z);
  76021. normals.push(-vn.x, -vn.y, -vn.z);
  76022. normals.push(-vn.x, -vn.y, -vn.z);
  76023. normals.push(-vn.x, -vn.y, -vn.z);
  76024. indices.push(StartIndex);
  76025. indices.push(StartIndex + 1);
  76026. indices.push(StartIndex + 2);
  76027. indices.push(StartIndex + 1);
  76028. indices.push(StartIndex + 3);
  76029. indices.push(StartIndex + 2);
  76030. }
  76031. else {
  76032. normals.push(vn.x, vn.y, vn.z);
  76033. normals.push(vn.x, vn.y, vn.z);
  76034. normals.push(vn.x, vn.y, vn.z);
  76035. normals.push(vn.x, vn.y, vn.z);
  76036. indices.push(StartIndex);
  76037. indices.push(StartIndex + 2);
  76038. indices.push(StartIndex + 1);
  76039. indices.push(StartIndex + 1);
  76040. indices.push(StartIndex + 2);
  76041. indices.push(StartIndex + 3);
  76042. }
  76043. StartIndex += 4;
  76044. }
  76045. ;
  76046. };
  76047. return PolygonMeshBuilder;
  76048. }());
  76049. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  76050. })(BABYLON || (BABYLON = {}));
  76051. //# sourceMappingURL=babylon.polygonMesh.js.map
  76052. "use strict";
  76053. var BABYLON;
  76054. (function (BABYLON) {
  76055. // Unique ID when we import meshes from Babylon to CSG
  76056. var currentCSGMeshId = 0;
  76057. // # class Vertex
  76058. // Represents a vertex of a polygon. Use your own vertex class instead of this
  76059. // one to provide additional features like texture coordinates and vertex
  76060. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  76061. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  76062. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  76063. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  76064. // is not used anywhere else.
  76065. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  76066. var Vertex = /** @class */ (function () {
  76067. function Vertex(pos, normal, uv) {
  76068. this.pos = pos;
  76069. this.normal = normal;
  76070. this.uv = uv;
  76071. }
  76072. Vertex.prototype.clone = function () {
  76073. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  76074. };
  76075. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  76076. // orientation of a polygon is flipped.
  76077. Vertex.prototype.flip = function () {
  76078. this.normal = this.normal.scale(-1);
  76079. };
  76080. // Create a new vertex between this vertex and `other` by linearly
  76081. // interpolating all properties using a parameter of `t`. Subclasses should
  76082. // override this to interpolate additional properties.
  76083. Vertex.prototype.interpolate = function (other, t) {
  76084. 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));
  76085. };
  76086. return Vertex;
  76087. }());
  76088. // # class Plane
  76089. // Represents a plane in 3D space.
  76090. var Plane = /** @class */ (function () {
  76091. function Plane(normal, w) {
  76092. this.normal = normal;
  76093. this.w = w;
  76094. }
  76095. Plane.FromPoints = function (a, b, c) {
  76096. var v0 = c.subtract(a);
  76097. var v1 = b.subtract(a);
  76098. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  76099. return null;
  76100. }
  76101. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  76102. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  76103. };
  76104. Plane.prototype.clone = function () {
  76105. return new Plane(this.normal.clone(), this.w);
  76106. };
  76107. Plane.prototype.flip = function () {
  76108. this.normal.scaleInPlace(-1);
  76109. this.w = -this.w;
  76110. };
  76111. // Split `polygon` by this plane if needed, then put the polygon or polygon
  76112. // fragments in the appropriate lists. Coplanar polygons go into either
  76113. // `coplanarFront` or `coplanarBack` depending on their orientation with
  76114. // respect to this plane. Polygons in front or in back of this plane go into
  76115. // either `front` or `back`.
  76116. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  76117. var COPLANAR = 0;
  76118. var FRONT = 1;
  76119. var BACK = 2;
  76120. var SPANNING = 3;
  76121. // Classify each point as well as the entire polygon into one of the above
  76122. // four classes.
  76123. var polygonType = 0;
  76124. var types = [];
  76125. var i;
  76126. var t;
  76127. for (i = 0; i < polygon.vertices.length; i++) {
  76128. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  76129. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  76130. polygonType |= type;
  76131. types.push(type);
  76132. }
  76133. // Put the polygon in the correct list, splitting it when necessary.
  76134. switch (polygonType) {
  76135. case COPLANAR:
  76136. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  76137. break;
  76138. case FRONT:
  76139. front.push(polygon);
  76140. break;
  76141. case BACK:
  76142. back.push(polygon);
  76143. break;
  76144. case SPANNING:
  76145. var f = [], b = [];
  76146. for (i = 0; i < polygon.vertices.length; i++) {
  76147. var j = (i + 1) % polygon.vertices.length;
  76148. var ti = types[i], tj = types[j];
  76149. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  76150. if (ti !== BACK)
  76151. f.push(vi);
  76152. if (ti !== FRONT)
  76153. b.push(ti !== BACK ? vi.clone() : vi);
  76154. if ((ti | tj) === SPANNING) {
  76155. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  76156. var v = vi.interpolate(vj, t);
  76157. f.push(v);
  76158. b.push(v.clone());
  76159. }
  76160. }
  76161. var poly;
  76162. if (f.length >= 3) {
  76163. poly = new Polygon(f, polygon.shared);
  76164. if (poly.plane)
  76165. front.push(poly);
  76166. }
  76167. if (b.length >= 3) {
  76168. poly = new Polygon(b, polygon.shared);
  76169. if (poly.plane)
  76170. back.push(poly);
  76171. }
  76172. break;
  76173. }
  76174. };
  76175. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  76176. // point is on the plane.
  76177. Plane.EPSILON = 1e-5;
  76178. return Plane;
  76179. }());
  76180. // # class Polygon
  76181. // Represents a convex polygon. The vertices used to initialize a polygon must
  76182. // be coplanar and form a convex loop.
  76183. //
  76184. // Each convex polygon has a `shared` property, which is shared between all
  76185. // polygons that are clones of each other or were split from the same polygon.
  76186. // This can be used to define per-polygon properties (such as surface color).
  76187. var Polygon = /** @class */ (function () {
  76188. function Polygon(vertices, shared) {
  76189. this.vertices = vertices;
  76190. this.shared = shared;
  76191. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  76192. }
  76193. Polygon.prototype.clone = function () {
  76194. var vertices = this.vertices.map(function (v) { return v.clone(); });
  76195. return new Polygon(vertices, this.shared);
  76196. };
  76197. Polygon.prototype.flip = function () {
  76198. this.vertices.reverse().map(function (v) { v.flip(); });
  76199. this.plane.flip();
  76200. };
  76201. return Polygon;
  76202. }());
  76203. // # class Node
  76204. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  76205. // by picking a polygon to split along. That polygon (and all other coplanar
  76206. // polygons) are added directly to that node and the other polygons are added to
  76207. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  76208. // no distinction between internal and leaf nodes.
  76209. var Node = /** @class */ (function () {
  76210. function Node(polygons) {
  76211. this.plane = null;
  76212. this.front = null;
  76213. this.back = null;
  76214. this.polygons = new Array();
  76215. if (polygons) {
  76216. this.build(polygons);
  76217. }
  76218. }
  76219. Node.prototype.clone = function () {
  76220. var node = new Node();
  76221. node.plane = this.plane && this.plane.clone();
  76222. node.front = this.front && this.front.clone();
  76223. node.back = this.back && this.back.clone();
  76224. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  76225. return node;
  76226. };
  76227. // Convert solid space to empty space and empty space to solid space.
  76228. Node.prototype.invert = function () {
  76229. for (var i = 0; i < this.polygons.length; i++) {
  76230. this.polygons[i].flip();
  76231. }
  76232. if (this.plane) {
  76233. this.plane.flip();
  76234. }
  76235. if (this.front) {
  76236. this.front.invert();
  76237. }
  76238. if (this.back) {
  76239. this.back.invert();
  76240. }
  76241. var temp = this.front;
  76242. this.front = this.back;
  76243. this.back = temp;
  76244. };
  76245. // Recursively remove all polygons in `polygons` that are inside this BSP
  76246. // tree.
  76247. Node.prototype.clipPolygons = function (polygons) {
  76248. if (!this.plane)
  76249. return polygons.slice();
  76250. var front = new Array(), back = new Array();
  76251. for (var i = 0; i < polygons.length; i++) {
  76252. this.plane.splitPolygon(polygons[i], front, back, front, back);
  76253. }
  76254. if (this.front) {
  76255. front = this.front.clipPolygons(front);
  76256. }
  76257. if (this.back) {
  76258. back = this.back.clipPolygons(back);
  76259. }
  76260. else {
  76261. back = [];
  76262. }
  76263. return front.concat(back);
  76264. };
  76265. // Remove all polygons in this BSP tree that are inside the other BSP tree
  76266. // `bsp`.
  76267. Node.prototype.clipTo = function (bsp) {
  76268. this.polygons = bsp.clipPolygons(this.polygons);
  76269. if (this.front)
  76270. this.front.clipTo(bsp);
  76271. if (this.back)
  76272. this.back.clipTo(bsp);
  76273. };
  76274. // Return a list of all polygons in this BSP tree.
  76275. Node.prototype.allPolygons = function () {
  76276. var polygons = this.polygons.slice();
  76277. if (this.front)
  76278. polygons = polygons.concat(this.front.allPolygons());
  76279. if (this.back)
  76280. polygons = polygons.concat(this.back.allPolygons());
  76281. return polygons;
  76282. };
  76283. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  76284. // new polygons are filtered down to the bottom of the tree and become new
  76285. // nodes there. Each set of polygons is partitioned using the first polygon
  76286. // (no heuristic is used to pick a good split).
  76287. Node.prototype.build = function (polygons) {
  76288. if (!polygons.length)
  76289. return;
  76290. if (!this.plane)
  76291. this.plane = polygons[0].plane.clone();
  76292. var front = new Array(), back = new Array();
  76293. for (var i = 0; i < polygons.length; i++) {
  76294. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  76295. }
  76296. if (front.length) {
  76297. if (!this.front)
  76298. this.front = new Node();
  76299. this.front.build(front);
  76300. }
  76301. if (back.length) {
  76302. if (!this.back)
  76303. this.back = new Node();
  76304. this.back.build(back);
  76305. }
  76306. };
  76307. return Node;
  76308. }());
  76309. var CSG = /** @class */ (function () {
  76310. function CSG() {
  76311. this.polygons = new Array();
  76312. }
  76313. // Convert BABYLON.Mesh to BABYLON.CSG
  76314. CSG.FromMesh = function (mesh) {
  76315. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  76316. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  76317. if (mesh instanceof BABYLON.Mesh) {
  76318. mesh.computeWorldMatrix(true);
  76319. matrix = mesh.getWorldMatrix();
  76320. meshPosition = mesh.position.clone();
  76321. meshRotation = mesh.rotation.clone();
  76322. if (mesh.rotationQuaternion) {
  76323. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  76324. }
  76325. meshScaling = mesh.scaling.clone();
  76326. }
  76327. else {
  76328. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  76329. }
  76330. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  76331. var subMeshes = mesh.subMeshes;
  76332. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  76333. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  76334. vertices = [];
  76335. for (var j = 0; j < 3; j++) {
  76336. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  76337. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  76338. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  76339. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  76340. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  76341. vertex = new Vertex(position, normal, uv);
  76342. vertices.push(vertex);
  76343. }
  76344. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  76345. // To handle the case of degenerated triangle
  76346. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  76347. if (polygon.plane)
  76348. polygons.push(polygon);
  76349. }
  76350. }
  76351. var csg = CSG.FromPolygons(polygons);
  76352. csg.matrix = matrix;
  76353. csg.position = meshPosition;
  76354. csg.rotation = meshRotation;
  76355. csg.scaling = meshScaling;
  76356. csg.rotationQuaternion = meshRotationQuaternion;
  76357. currentCSGMeshId++;
  76358. return csg;
  76359. };
  76360. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  76361. CSG.FromPolygons = function (polygons) {
  76362. var csg = new CSG();
  76363. csg.polygons = polygons;
  76364. return csg;
  76365. };
  76366. CSG.prototype.clone = function () {
  76367. var csg = new CSG();
  76368. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  76369. csg.copyTransformAttributes(this);
  76370. return csg;
  76371. };
  76372. CSG.prototype.union = function (csg) {
  76373. var a = new Node(this.clone().polygons);
  76374. var b = new Node(csg.clone().polygons);
  76375. a.clipTo(b);
  76376. b.clipTo(a);
  76377. b.invert();
  76378. b.clipTo(a);
  76379. b.invert();
  76380. a.build(b.allPolygons());
  76381. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76382. };
  76383. CSG.prototype.unionInPlace = function (csg) {
  76384. var a = new Node(this.polygons);
  76385. var b = new Node(csg.polygons);
  76386. a.clipTo(b);
  76387. b.clipTo(a);
  76388. b.invert();
  76389. b.clipTo(a);
  76390. b.invert();
  76391. a.build(b.allPolygons());
  76392. this.polygons = a.allPolygons();
  76393. };
  76394. CSG.prototype.subtract = function (csg) {
  76395. var a = new Node(this.clone().polygons);
  76396. var b = new Node(csg.clone().polygons);
  76397. a.invert();
  76398. a.clipTo(b);
  76399. b.clipTo(a);
  76400. b.invert();
  76401. b.clipTo(a);
  76402. b.invert();
  76403. a.build(b.allPolygons());
  76404. a.invert();
  76405. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76406. };
  76407. CSG.prototype.subtractInPlace = function (csg) {
  76408. var a = new Node(this.polygons);
  76409. var b = new Node(csg.polygons);
  76410. a.invert();
  76411. a.clipTo(b);
  76412. b.clipTo(a);
  76413. b.invert();
  76414. b.clipTo(a);
  76415. b.invert();
  76416. a.build(b.allPolygons());
  76417. a.invert();
  76418. this.polygons = a.allPolygons();
  76419. };
  76420. CSG.prototype.intersect = function (csg) {
  76421. var a = new Node(this.clone().polygons);
  76422. var b = new Node(csg.clone().polygons);
  76423. a.invert();
  76424. b.clipTo(a);
  76425. b.invert();
  76426. a.clipTo(b);
  76427. b.clipTo(a);
  76428. a.build(b.allPolygons());
  76429. a.invert();
  76430. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76431. };
  76432. CSG.prototype.intersectInPlace = function (csg) {
  76433. var a = new Node(this.polygons);
  76434. var b = new Node(csg.polygons);
  76435. a.invert();
  76436. b.clipTo(a);
  76437. b.invert();
  76438. a.clipTo(b);
  76439. b.clipTo(a);
  76440. a.build(b.allPolygons());
  76441. a.invert();
  76442. this.polygons = a.allPolygons();
  76443. };
  76444. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  76445. // not modified.
  76446. CSG.prototype.inverse = function () {
  76447. var csg = this.clone();
  76448. csg.inverseInPlace();
  76449. return csg;
  76450. };
  76451. CSG.prototype.inverseInPlace = function () {
  76452. this.polygons.map(function (p) { p.flip(); });
  76453. };
  76454. // This is used to keep meshes transformations so they can be restored
  76455. // when we build back a Babylon Mesh
  76456. // NB : All CSG operations are performed in world coordinates
  76457. CSG.prototype.copyTransformAttributes = function (csg) {
  76458. this.matrix = csg.matrix;
  76459. this.position = csg.position;
  76460. this.rotation = csg.rotation;
  76461. this.scaling = csg.scaling;
  76462. this.rotationQuaternion = csg.rotationQuaternion;
  76463. return this;
  76464. };
  76465. // Build Raw mesh from CSG
  76466. // Coordinates here are in world space
  76467. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  76468. var matrix = this.matrix.clone();
  76469. matrix.invert();
  76470. 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;
  76471. if (keepSubMeshes) {
  76472. // Sort Polygons, since subMeshes are indices range
  76473. polygons.sort(function (a, b) {
  76474. if (a.shared.meshId === b.shared.meshId) {
  76475. return a.shared.subMeshId - b.shared.subMeshId;
  76476. }
  76477. else {
  76478. return a.shared.meshId - b.shared.meshId;
  76479. }
  76480. });
  76481. }
  76482. for (var i = 0, il = polygons.length; i < il; i++) {
  76483. polygon = polygons[i];
  76484. // Building SubMeshes
  76485. if (!subMesh_dict[polygon.shared.meshId]) {
  76486. subMesh_dict[polygon.shared.meshId] = {};
  76487. }
  76488. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  76489. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  76490. indexStart: +Infinity,
  76491. indexEnd: -Infinity,
  76492. materialIndex: polygon.shared.materialIndex
  76493. };
  76494. }
  76495. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  76496. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  76497. polygonIndices[0] = 0;
  76498. polygonIndices[1] = j - 1;
  76499. polygonIndices[2] = j;
  76500. for (var k = 0; k < 3; k++) {
  76501. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  76502. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  76503. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  76504. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  76505. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  76506. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  76507. // Check if 2 points can be merged
  76508. if (!(typeof vertex_idx !== 'undefined' &&
  76509. normals[vertex_idx * 3] === localNormal.x &&
  76510. normals[vertex_idx * 3 + 1] === localNormal.y &&
  76511. normals[vertex_idx * 3 + 2] === localNormal.z &&
  76512. uvs[vertex_idx * 2] === uv.x &&
  76513. uvs[vertex_idx * 2 + 1] === uv.y)) {
  76514. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  76515. uvs.push(uv.x, uv.y);
  76516. normals.push(normal.x, normal.y, normal.z);
  76517. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  76518. }
  76519. indices.push(vertex_idx);
  76520. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  76521. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  76522. currentIndex++;
  76523. }
  76524. }
  76525. }
  76526. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  76527. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  76528. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  76529. mesh.setIndices(indices, null);
  76530. if (keepSubMeshes) {
  76531. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  76532. var materialIndexOffset = 0, materialMaxIndex;
  76533. mesh.subMeshes = new Array();
  76534. for (var m in subMesh_dict) {
  76535. materialMaxIndex = -1;
  76536. for (var sm in subMesh_dict[m]) {
  76537. subMesh_obj = subMesh_dict[m][sm];
  76538. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  76539. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  76540. }
  76541. materialIndexOffset += ++materialMaxIndex;
  76542. }
  76543. }
  76544. return mesh;
  76545. };
  76546. // Build Mesh from CSG taking material and transforms into account
  76547. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  76548. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  76549. mesh.material = material;
  76550. mesh.position.copyFrom(this.position);
  76551. mesh.rotation.copyFrom(this.rotation);
  76552. if (this.rotationQuaternion) {
  76553. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  76554. }
  76555. mesh.scaling.copyFrom(this.scaling);
  76556. mesh.computeWorldMatrix(true);
  76557. return mesh;
  76558. };
  76559. return CSG;
  76560. }());
  76561. BABYLON.CSG = CSG;
  76562. })(BABYLON || (BABYLON = {}));
  76563. //# sourceMappingURL=babylon.csg.js.map
  76564. "use strict";
  76565. var BABYLON;
  76566. (function (BABYLON) {
  76567. var LensFlare = /** @class */ (function () {
  76568. function LensFlare(size, position, color, imgUrl, system) {
  76569. this.size = size;
  76570. this.position = position;
  76571. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  76572. this.color = color || new BABYLON.Color3(1, 1, 1);
  76573. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  76574. this._system = system;
  76575. system.lensFlares.push(this);
  76576. }
  76577. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  76578. return new LensFlare(size, position, color, imgUrl, system);
  76579. };
  76580. LensFlare.prototype.dispose = function () {
  76581. if (this.texture) {
  76582. this.texture.dispose();
  76583. }
  76584. // Remove from scene
  76585. var index = this._system.lensFlares.indexOf(this);
  76586. this._system.lensFlares.splice(index, 1);
  76587. };
  76588. ;
  76589. return LensFlare;
  76590. }());
  76591. BABYLON.LensFlare = LensFlare;
  76592. })(BABYLON || (BABYLON = {}));
  76593. //# sourceMappingURL=babylon.lensFlare.js.map
  76594. "use strict";
  76595. var BABYLON;
  76596. (function (BABYLON) {
  76597. var LensFlareSystem = /** @class */ (function () {
  76598. function LensFlareSystem(name, emitter, scene) {
  76599. this.name = name;
  76600. this.lensFlares = new Array();
  76601. this.borderLimit = 300;
  76602. this.viewportBorder = 0;
  76603. this.layerMask = 0x0FFFFFFF;
  76604. this._vertexBuffers = {};
  76605. this._isEnabled = true;
  76606. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  76607. this._emitter = emitter;
  76608. this.id = name;
  76609. scene.lensFlareSystems.push(this);
  76610. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  76611. var engine = scene.getEngine();
  76612. // VBO
  76613. var vertices = [];
  76614. vertices.push(1, 1);
  76615. vertices.push(-1, 1);
  76616. vertices.push(-1, -1);
  76617. vertices.push(1, -1);
  76618. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  76619. // Indices
  76620. var indices = [];
  76621. indices.push(0);
  76622. indices.push(1);
  76623. indices.push(2);
  76624. indices.push(0);
  76625. indices.push(2);
  76626. indices.push(3);
  76627. this._indexBuffer = engine.createIndexBuffer(indices);
  76628. // Effects
  76629. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  76630. }
  76631. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  76632. get: function () {
  76633. return this._isEnabled;
  76634. },
  76635. set: function (value) {
  76636. this._isEnabled = value;
  76637. },
  76638. enumerable: true,
  76639. configurable: true
  76640. });
  76641. LensFlareSystem.prototype.getScene = function () {
  76642. return this._scene;
  76643. };
  76644. LensFlareSystem.prototype.getEmitter = function () {
  76645. return this._emitter;
  76646. };
  76647. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  76648. this._emitter = newEmitter;
  76649. };
  76650. LensFlareSystem.prototype.getEmitterPosition = function () {
  76651. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  76652. };
  76653. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  76654. var position = this.getEmitterPosition();
  76655. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  76656. this._positionX = position.x;
  76657. this._positionY = position.y;
  76658. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  76659. if (this.viewportBorder > 0) {
  76660. globalViewport.x -= this.viewportBorder;
  76661. globalViewport.y -= this.viewportBorder;
  76662. globalViewport.width += this.viewportBorder * 2;
  76663. globalViewport.height += this.viewportBorder * 2;
  76664. position.x += this.viewportBorder;
  76665. position.y += this.viewportBorder;
  76666. this._positionX += this.viewportBorder;
  76667. this._positionY += this.viewportBorder;
  76668. }
  76669. if (position.z > 0) {
  76670. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  76671. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  76672. return true;
  76673. }
  76674. return true;
  76675. }
  76676. return false;
  76677. };
  76678. LensFlareSystem.prototype._isVisible = function () {
  76679. if (!this._isEnabled || !this._scene.activeCamera) {
  76680. return false;
  76681. }
  76682. var emitterPosition = this.getEmitterPosition();
  76683. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  76684. var distance = direction.length();
  76685. direction.normalize();
  76686. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  76687. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  76688. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  76689. };
  76690. LensFlareSystem.prototype.render = function () {
  76691. if (!this._effect.isReady() || !this._scene.activeCamera)
  76692. return false;
  76693. var engine = this._scene.getEngine();
  76694. var viewport = this._scene.activeCamera.viewport;
  76695. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  76696. // Position
  76697. if (!this.computeEffectivePosition(globalViewport)) {
  76698. return false;
  76699. }
  76700. // Visibility
  76701. if (!this._isVisible()) {
  76702. return false;
  76703. }
  76704. // Intensity
  76705. var awayX;
  76706. var awayY;
  76707. if (this._positionX < this.borderLimit + globalViewport.x) {
  76708. awayX = this.borderLimit + globalViewport.x - this._positionX;
  76709. }
  76710. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  76711. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  76712. }
  76713. else {
  76714. awayX = 0;
  76715. }
  76716. if (this._positionY < this.borderLimit + globalViewport.y) {
  76717. awayY = this.borderLimit + globalViewport.y - this._positionY;
  76718. }
  76719. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  76720. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  76721. }
  76722. else {
  76723. awayY = 0;
  76724. }
  76725. var away = (awayX > awayY) ? awayX : awayY;
  76726. away -= this.viewportBorder;
  76727. if (away > this.borderLimit) {
  76728. away = this.borderLimit;
  76729. }
  76730. var intensity = 1.0 - (away / this.borderLimit);
  76731. if (intensity < 0) {
  76732. return false;
  76733. }
  76734. if (intensity > 1.0) {
  76735. intensity = 1.0;
  76736. }
  76737. if (this.viewportBorder > 0) {
  76738. globalViewport.x += this.viewportBorder;
  76739. globalViewport.y += this.viewportBorder;
  76740. globalViewport.width -= this.viewportBorder * 2;
  76741. globalViewport.height -= this.viewportBorder * 2;
  76742. this._positionX -= this.viewportBorder;
  76743. this._positionY -= this.viewportBorder;
  76744. }
  76745. // Position
  76746. var centerX = globalViewport.x + globalViewport.width / 2;
  76747. var centerY = globalViewport.y + globalViewport.height / 2;
  76748. var distX = centerX - this._positionX;
  76749. var distY = centerY - this._positionY;
  76750. // Effects
  76751. engine.enableEffect(this._effect);
  76752. engine.setState(false);
  76753. engine.setDepthBuffer(false);
  76754. // VBOs
  76755. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  76756. // Flares
  76757. for (var index = 0; index < this.lensFlares.length; index++) {
  76758. var flare = this.lensFlares[index];
  76759. engine.setAlphaMode(flare.alphaMode);
  76760. var x = centerX - (distX * flare.position);
  76761. var y = centerY - (distY * flare.position);
  76762. var cw = flare.size;
  76763. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  76764. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  76765. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  76766. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  76767. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  76768. // Texture
  76769. this._effect.setTexture("textureSampler", flare.texture);
  76770. // Color
  76771. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  76772. // Draw order
  76773. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  76774. }
  76775. engine.setDepthBuffer(true);
  76776. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  76777. return true;
  76778. };
  76779. LensFlareSystem.prototype.dispose = function () {
  76780. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76781. if (vertexBuffer) {
  76782. vertexBuffer.dispose();
  76783. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  76784. }
  76785. if (this._indexBuffer) {
  76786. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  76787. this._indexBuffer = null;
  76788. }
  76789. while (this.lensFlares.length) {
  76790. this.lensFlares[0].dispose();
  76791. }
  76792. // Remove from scene
  76793. var index = this._scene.lensFlareSystems.indexOf(this);
  76794. this._scene.lensFlareSystems.splice(index, 1);
  76795. };
  76796. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  76797. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  76798. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  76799. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  76800. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  76801. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  76802. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  76803. var parsedFlare = parsedLensFlareSystem.flares[index];
  76804. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  76805. }
  76806. return lensFlareSystem;
  76807. };
  76808. LensFlareSystem.prototype.serialize = function () {
  76809. var serializationObject = {};
  76810. serializationObject.id = this.id;
  76811. serializationObject.name = this.name;
  76812. serializationObject.emitterId = this.getEmitter().id;
  76813. serializationObject.borderLimit = this.borderLimit;
  76814. serializationObject.flares = [];
  76815. for (var index = 0; index < this.lensFlares.length; index++) {
  76816. var flare = this.lensFlares[index];
  76817. serializationObject.flares.push({
  76818. size: flare.size,
  76819. position: flare.position,
  76820. color: flare.color.asArray(),
  76821. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  76822. });
  76823. }
  76824. return serializationObject;
  76825. };
  76826. return LensFlareSystem;
  76827. }());
  76828. BABYLON.LensFlareSystem = LensFlareSystem;
  76829. })(BABYLON || (BABYLON = {}));
  76830. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  76831. "use strict";
  76832. var BABYLON;
  76833. (function (BABYLON) {
  76834. /**
  76835. * This is a holder class for the physics joint created by the physics plugin.
  76836. * It holds a set of functions to control the underlying joint.
  76837. */
  76838. var PhysicsJoint = /** @class */ (function () {
  76839. function PhysicsJoint(type, jointData) {
  76840. this.type = type;
  76841. this.jointData = jointData;
  76842. jointData.nativeParams = jointData.nativeParams || {};
  76843. }
  76844. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  76845. get: function () {
  76846. return this._physicsJoint;
  76847. },
  76848. set: function (newJoint) {
  76849. if (this._physicsJoint) {
  76850. //remove from the wolrd
  76851. }
  76852. this._physicsJoint = newJoint;
  76853. },
  76854. enumerable: true,
  76855. configurable: true
  76856. });
  76857. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  76858. set: function (physicsPlugin) {
  76859. this._physicsPlugin = physicsPlugin;
  76860. },
  76861. enumerable: true,
  76862. configurable: true
  76863. });
  76864. /**
  76865. * Execute a function that is physics-plugin specific.
  76866. * @param {Function} func the function that will be executed.
  76867. * It accepts two parameters: the physics world and the physics joint.
  76868. */
  76869. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  76870. func(this._physicsPlugin.world, this._physicsJoint);
  76871. };
  76872. //TODO check if the native joints are the same
  76873. //Joint Types
  76874. PhysicsJoint.DistanceJoint = 0;
  76875. PhysicsJoint.HingeJoint = 1;
  76876. PhysicsJoint.BallAndSocketJoint = 2;
  76877. PhysicsJoint.WheelJoint = 3;
  76878. PhysicsJoint.SliderJoint = 4;
  76879. //OIMO
  76880. PhysicsJoint.PrismaticJoint = 5;
  76881. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  76882. PhysicsJoint.UniversalJoint = 6;
  76883. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  76884. //Cannon
  76885. //Similar to a Ball-Joint. Different in params
  76886. PhysicsJoint.PointToPointJoint = 8;
  76887. //Cannon only at the moment
  76888. PhysicsJoint.SpringJoint = 9;
  76889. PhysicsJoint.LockJoint = 10;
  76890. return PhysicsJoint;
  76891. }());
  76892. BABYLON.PhysicsJoint = PhysicsJoint;
  76893. /**
  76894. * A class representing a physics distance joint.
  76895. */
  76896. var DistanceJoint = /** @class */ (function (_super) {
  76897. __extends(DistanceJoint, _super);
  76898. function DistanceJoint(jointData) {
  76899. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  76900. }
  76901. /**
  76902. * Update the predefined distance.
  76903. */
  76904. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  76905. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  76906. };
  76907. return DistanceJoint;
  76908. }(PhysicsJoint));
  76909. BABYLON.DistanceJoint = DistanceJoint;
  76910. var MotorEnabledJoint = /** @class */ (function (_super) {
  76911. __extends(MotorEnabledJoint, _super);
  76912. function MotorEnabledJoint(type, jointData) {
  76913. return _super.call(this, type, jointData) || this;
  76914. }
  76915. /**
  76916. * Set the motor values.
  76917. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76918. * @param {number} force the force to apply
  76919. * @param {number} maxForce max force for this motor.
  76920. */
  76921. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  76922. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  76923. };
  76924. /**
  76925. * Set the motor's limits.
  76926. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76927. */
  76928. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  76929. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  76930. };
  76931. return MotorEnabledJoint;
  76932. }(PhysicsJoint));
  76933. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  76934. /**
  76935. * This class represents a single hinge physics joint
  76936. */
  76937. var HingeJoint = /** @class */ (function (_super) {
  76938. __extends(HingeJoint, _super);
  76939. function HingeJoint(jointData) {
  76940. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  76941. }
  76942. /**
  76943. * Set the motor values.
  76944. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76945. * @param {number} force the force to apply
  76946. * @param {number} maxForce max force for this motor.
  76947. */
  76948. HingeJoint.prototype.setMotor = function (force, maxForce) {
  76949. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  76950. };
  76951. /**
  76952. * Set the motor's limits.
  76953. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76954. */
  76955. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  76956. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  76957. };
  76958. return HingeJoint;
  76959. }(MotorEnabledJoint));
  76960. BABYLON.HingeJoint = HingeJoint;
  76961. /**
  76962. * This class represents a dual hinge physics joint (same as wheel joint)
  76963. */
  76964. var Hinge2Joint = /** @class */ (function (_super) {
  76965. __extends(Hinge2Joint, _super);
  76966. function Hinge2Joint(jointData) {
  76967. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  76968. }
  76969. /**
  76970. * Set the motor values.
  76971. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76972. * @param {number} force the force to apply
  76973. * @param {number} maxForce max force for this motor.
  76974. * @param {motorIndex} the motor's index, 0 or 1.
  76975. */
  76976. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  76977. if (motorIndex === void 0) { motorIndex = 0; }
  76978. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  76979. };
  76980. /**
  76981. * Set the motor limits.
  76982. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76983. * @param {number} upperLimit the upper limit
  76984. * @param {number} lowerLimit lower limit
  76985. * @param {motorIndex} the motor's index, 0 or 1.
  76986. */
  76987. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  76988. if (motorIndex === void 0) { motorIndex = 0; }
  76989. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  76990. };
  76991. return Hinge2Joint;
  76992. }(MotorEnabledJoint));
  76993. BABYLON.Hinge2Joint = Hinge2Joint;
  76994. })(BABYLON || (BABYLON = {}));
  76995. //# sourceMappingURL=babylon.physicsJoint.js.map
  76996. "use strict";
  76997. var BABYLON;
  76998. (function (BABYLON) {
  76999. var PhysicsImpostor = /** @class */ (function () {
  77000. function PhysicsImpostor(object, type, _options, _scene) {
  77001. if (_options === void 0) { _options = { mass: 0 }; }
  77002. var _this = this;
  77003. this.object = object;
  77004. this.type = type;
  77005. this._options = _options;
  77006. this._scene = _scene;
  77007. this._bodyUpdateRequired = false;
  77008. this._onBeforePhysicsStepCallbacks = new Array();
  77009. this._onAfterPhysicsStepCallbacks = new Array();
  77010. this._onPhysicsCollideCallbacks = [];
  77011. this._deltaPosition = BABYLON.Vector3.Zero();
  77012. this._isDisposed = false;
  77013. //temp variables for parent rotation calculations
  77014. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  77015. this._tmpQuat = new BABYLON.Quaternion();
  77016. this._tmpQuat2 = new BABYLON.Quaternion();
  77017. /**
  77018. * this function is executed by the physics engine.
  77019. */
  77020. this.beforeStep = function () {
  77021. if (!_this._physicsEngine) {
  77022. return;
  77023. }
  77024. _this.object.translate(_this._deltaPosition, -1);
  77025. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  77026. _this.object.computeWorldMatrix(false);
  77027. if (_this.object.parent && _this.object.rotationQuaternion) {
  77028. _this.getParentsRotation();
  77029. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  77030. }
  77031. else {
  77032. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  77033. }
  77034. if (!_this._options.disableBidirectionalTransformation) {
  77035. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  77036. }
  77037. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  77038. func(_this);
  77039. });
  77040. };
  77041. /**
  77042. * this function is executed by the physics engine.
  77043. */
  77044. this.afterStep = function () {
  77045. if (!_this._physicsEngine) {
  77046. return;
  77047. }
  77048. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  77049. func(_this);
  77050. });
  77051. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  77052. // object has now its world rotation. needs to be converted to local.
  77053. if (_this.object.parent && _this.object.rotationQuaternion) {
  77054. _this.getParentsRotation();
  77055. _this._tmpQuat.conjugateInPlace();
  77056. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  77057. }
  77058. // take the position set and make it the absolute position of this object.
  77059. _this.object.setAbsolutePosition(_this.object.position);
  77060. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  77061. _this.object.translate(_this._deltaPosition, 1);
  77062. };
  77063. /**
  77064. * Legacy collision detection event support
  77065. */
  77066. this.onCollideEvent = null;
  77067. //event and body object due to cannon's event-based architecture.
  77068. this.onCollide = function (e) {
  77069. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  77070. return;
  77071. }
  77072. if (!_this._physicsEngine) {
  77073. return;
  77074. }
  77075. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  77076. if (otherImpostor) {
  77077. // Legacy collision detection event support
  77078. if (_this.onCollideEvent) {
  77079. _this.onCollideEvent(_this, otherImpostor);
  77080. }
  77081. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  77082. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  77083. }).forEach(function (obj) {
  77084. obj.callback(_this, otherImpostor);
  77085. });
  77086. }
  77087. };
  77088. //sanity check!
  77089. if (!this.object) {
  77090. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  77091. return;
  77092. }
  77093. //legacy support for old syntax.
  77094. if (!this._scene && object.getScene) {
  77095. this._scene = object.getScene();
  77096. }
  77097. if (!this._scene) {
  77098. return;
  77099. }
  77100. this._physicsEngine = this._scene.getPhysicsEngine();
  77101. if (!this._physicsEngine) {
  77102. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  77103. }
  77104. else {
  77105. //set the object's quaternion, if not set
  77106. if (!this.object.rotationQuaternion) {
  77107. if (this.object.rotation) {
  77108. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  77109. }
  77110. else {
  77111. this.object.rotationQuaternion = new BABYLON.Quaternion();
  77112. }
  77113. }
  77114. //default options params
  77115. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  77116. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  77117. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  77118. this._joints = [];
  77119. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  77120. if (!this.object.parent || this._options.ignoreParent) {
  77121. this._init();
  77122. }
  77123. else if (this.object.parent.physicsImpostor) {
  77124. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  77125. }
  77126. }
  77127. }
  77128. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  77129. get: function () {
  77130. return this._isDisposed;
  77131. },
  77132. enumerable: true,
  77133. configurable: true
  77134. });
  77135. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  77136. get: function () {
  77137. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  77138. },
  77139. set: function (value) {
  77140. this.setMass(value);
  77141. },
  77142. enumerable: true,
  77143. configurable: true
  77144. });
  77145. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  77146. get: function () {
  77147. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  77148. },
  77149. set: function (value) {
  77150. if (!this._physicsEngine) {
  77151. return;
  77152. }
  77153. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  77154. },
  77155. enumerable: true,
  77156. configurable: true
  77157. });
  77158. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  77159. get: function () {
  77160. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  77161. },
  77162. set: function (value) {
  77163. if (!this._physicsEngine) {
  77164. return;
  77165. }
  77166. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  77167. },
  77168. enumerable: true,
  77169. configurable: true
  77170. });
  77171. /**
  77172. * This function will completly initialize this impostor.
  77173. * It will create a new body - but only if this mesh has no parent.
  77174. * If it has, this impostor will not be used other than to define the impostor
  77175. * of the child mesh.
  77176. */
  77177. PhysicsImpostor.prototype._init = function () {
  77178. if (!this._physicsEngine) {
  77179. return;
  77180. }
  77181. this._physicsEngine.removeImpostor(this);
  77182. this.physicsBody = null;
  77183. this._parent = this._parent || this._getPhysicsParent();
  77184. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  77185. this._physicsEngine.addImpostor(this);
  77186. }
  77187. };
  77188. PhysicsImpostor.prototype._getPhysicsParent = function () {
  77189. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  77190. var parentMesh = this.object.parent;
  77191. return parentMesh.physicsImpostor;
  77192. }
  77193. return null;
  77194. };
  77195. /**
  77196. * Should a new body be generated.
  77197. */
  77198. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  77199. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  77200. };
  77201. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  77202. this.forceUpdate();
  77203. };
  77204. /**
  77205. * Force a regeneration of this or the parent's impostor's body.
  77206. * Use under cautious - This will remove all joints already implemented.
  77207. */
  77208. PhysicsImpostor.prototype.forceUpdate = function () {
  77209. this._init();
  77210. if (this.parent && !this._options.ignoreParent) {
  77211. this.parent.forceUpdate();
  77212. }
  77213. };
  77214. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  77215. /*public get mesh(): AbstractMesh {
  77216. return this._mesh;
  77217. }*/
  77218. /**
  77219. * Gets the body that holds this impostor. Either its own, or its parent.
  77220. */
  77221. get: function () {
  77222. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  77223. },
  77224. /**
  77225. * Set the physics body. Used mainly by the physics engine/plugin
  77226. */
  77227. set: function (physicsBody) {
  77228. if (this._physicsBody && this._physicsEngine) {
  77229. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  77230. }
  77231. this._physicsBody = physicsBody;
  77232. this.resetUpdateFlags();
  77233. },
  77234. enumerable: true,
  77235. configurable: true
  77236. });
  77237. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  77238. get: function () {
  77239. return !this._options.ignoreParent && this._parent ? this._parent : null;
  77240. },
  77241. set: function (value) {
  77242. this._parent = value;
  77243. },
  77244. enumerable: true,
  77245. configurable: true
  77246. });
  77247. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  77248. this._bodyUpdateRequired = false;
  77249. };
  77250. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  77251. if (this.object.getBoundingInfo) {
  77252. var q = this.object.rotationQuaternion;
  77253. //reset rotation
  77254. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  77255. //calculate the world matrix with no rotation
  77256. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  77257. var boundingInfo = this.object.getBoundingInfo();
  77258. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  77259. //bring back the rotation
  77260. this.object.rotationQuaternion = q;
  77261. //calculate the world matrix with the new rotation
  77262. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  77263. return size;
  77264. }
  77265. else {
  77266. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  77267. }
  77268. };
  77269. PhysicsImpostor.prototype.getObjectCenter = function () {
  77270. if (this.object.getBoundingInfo) {
  77271. var boundingInfo = this.object.getBoundingInfo();
  77272. return boundingInfo.boundingBox.centerWorld;
  77273. }
  77274. else {
  77275. return this.object.position;
  77276. }
  77277. };
  77278. /**
  77279. * Get a specific parametes from the options parameter.
  77280. */
  77281. PhysicsImpostor.prototype.getParam = function (paramName) {
  77282. return this._options[paramName];
  77283. };
  77284. /**
  77285. * Sets a specific parameter in the options given to the physics plugin
  77286. */
  77287. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  77288. this._options[paramName] = value;
  77289. this._bodyUpdateRequired = true;
  77290. };
  77291. /**
  77292. * Specifically change the body's mass option. Won't recreate the physics body object
  77293. */
  77294. PhysicsImpostor.prototype.setMass = function (mass) {
  77295. if (this.getParam("mass") !== mass) {
  77296. this.setParam("mass", mass);
  77297. }
  77298. if (this._physicsEngine) {
  77299. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  77300. }
  77301. };
  77302. PhysicsImpostor.prototype.getLinearVelocity = function () {
  77303. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  77304. };
  77305. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  77306. if (this._physicsEngine) {
  77307. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  77308. }
  77309. };
  77310. PhysicsImpostor.prototype.getAngularVelocity = function () {
  77311. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  77312. };
  77313. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  77314. if (this._physicsEngine) {
  77315. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  77316. }
  77317. };
  77318. /**
  77319. * Execute a function with the physics plugin native code.
  77320. * Provide a function the will have two variables - the world object and the physics body object.
  77321. */
  77322. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  77323. if (this._physicsEngine) {
  77324. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  77325. }
  77326. };
  77327. /**
  77328. * Register a function that will be executed before the physics world is stepping forward.
  77329. */
  77330. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  77331. this._onBeforePhysicsStepCallbacks.push(func);
  77332. };
  77333. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  77334. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  77335. if (index > -1) {
  77336. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  77337. }
  77338. else {
  77339. BABYLON.Tools.Warn("Function to remove was not found");
  77340. }
  77341. };
  77342. /**
  77343. * Register a function that will be executed after the physics step
  77344. */
  77345. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  77346. this._onAfterPhysicsStepCallbacks.push(func);
  77347. };
  77348. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  77349. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  77350. if (index > -1) {
  77351. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  77352. }
  77353. else {
  77354. BABYLON.Tools.Warn("Function to remove was not found");
  77355. }
  77356. };
  77357. /**
  77358. * register a function that will be executed when this impostor collides against a different body.
  77359. */
  77360. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  77361. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  77362. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  77363. };
  77364. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  77365. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  77366. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  77367. if (index > -1) {
  77368. this._onPhysicsCollideCallbacks.splice(index, 1);
  77369. }
  77370. else {
  77371. BABYLON.Tools.Warn("Function to remove was not found");
  77372. }
  77373. };
  77374. PhysicsImpostor.prototype.getParentsRotation = function () {
  77375. var parent = this.object.parent;
  77376. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  77377. while (parent) {
  77378. if (parent.rotationQuaternion) {
  77379. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  77380. }
  77381. else {
  77382. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  77383. }
  77384. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  77385. parent = parent.parent;
  77386. }
  77387. return this._tmpQuat;
  77388. };
  77389. /**
  77390. * Apply a force
  77391. */
  77392. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  77393. if (this._physicsEngine) {
  77394. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  77395. }
  77396. return this;
  77397. };
  77398. /**
  77399. * Apply an impulse
  77400. */
  77401. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  77402. if (this._physicsEngine) {
  77403. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  77404. }
  77405. return this;
  77406. };
  77407. /**
  77408. * A help function to create a joint.
  77409. */
  77410. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  77411. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  77412. this.addJoint(otherImpostor, joint);
  77413. return this;
  77414. };
  77415. /**
  77416. * Add a joint to this impostor with a different impostor.
  77417. */
  77418. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  77419. this._joints.push({
  77420. otherImpostor: otherImpostor,
  77421. joint: joint
  77422. });
  77423. if (this._physicsEngine) {
  77424. this._physicsEngine.addJoint(this, otherImpostor, joint);
  77425. }
  77426. return this;
  77427. };
  77428. /**
  77429. * Will keep this body still, in a sleep mode.
  77430. */
  77431. PhysicsImpostor.prototype.sleep = function () {
  77432. if (this._physicsEngine) {
  77433. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  77434. }
  77435. return this;
  77436. };
  77437. /**
  77438. * Wake the body up.
  77439. */
  77440. PhysicsImpostor.prototype.wakeUp = function () {
  77441. if (this._physicsEngine) {
  77442. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  77443. }
  77444. return this;
  77445. };
  77446. PhysicsImpostor.prototype.clone = function (newObject) {
  77447. if (!newObject)
  77448. return null;
  77449. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  77450. };
  77451. PhysicsImpostor.prototype.dispose = function () {
  77452. var _this = this;
  77453. //no dispose if no physics engine is available.
  77454. if (!this._physicsEngine) {
  77455. return;
  77456. }
  77457. this._joints.forEach(function (j) {
  77458. if (_this._physicsEngine) {
  77459. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  77460. }
  77461. });
  77462. //dispose the physics body
  77463. this._physicsEngine.removeImpostor(this);
  77464. if (this.parent) {
  77465. this.parent.forceUpdate();
  77466. }
  77467. else {
  77468. /*this._object.getChildMeshes().forEach(function(mesh) {
  77469. if (mesh.physicsImpostor) {
  77470. if (disposeChildren) {
  77471. mesh.physicsImpostor.dispose();
  77472. mesh.physicsImpostor = null;
  77473. }
  77474. }
  77475. })*/
  77476. }
  77477. this._isDisposed = true;
  77478. };
  77479. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  77480. this._deltaPosition.copyFrom(position);
  77481. };
  77482. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  77483. if (!this._deltaRotation) {
  77484. this._deltaRotation = new BABYLON.Quaternion();
  77485. }
  77486. this._deltaRotation.copyFrom(rotation);
  77487. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  77488. };
  77489. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  77490. if (this._physicsEngine) {
  77491. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  77492. }
  77493. return this;
  77494. };
  77495. PhysicsImpostor.prototype.getRadius = function () {
  77496. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  77497. };
  77498. /**
  77499. * Sync a bone with this impostor
  77500. * @param bone The bone to sync to the impostor.
  77501. * @param boneMesh The mesh that the bone is influencing.
  77502. * @param jointPivot The pivot of the joint / bone in local space.
  77503. * @param distToJoint Optional distance from the impostor to the joint.
  77504. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  77505. */
  77506. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  77507. var tempVec = PhysicsImpostor._tmpVecs[0];
  77508. var mesh = this.object;
  77509. if (mesh.rotationQuaternion) {
  77510. if (adjustRotation) {
  77511. var tempQuat = PhysicsImpostor._tmpQuat;
  77512. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  77513. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  77514. }
  77515. else {
  77516. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  77517. }
  77518. }
  77519. tempVec.x = 0;
  77520. tempVec.y = 0;
  77521. tempVec.z = 0;
  77522. if (jointPivot) {
  77523. tempVec.x = jointPivot.x;
  77524. tempVec.y = jointPivot.y;
  77525. tempVec.z = jointPivot.z;
  77526. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  77527. if (distToJoint === undefined || distToJoint === null) {
  77528. distToJoint = jointPivot.length();
  77529. }
  77530. tempVec.x *= distToJoint;
  77531. tempVec.y *= distToJoint;
  77532. tempVec.z *= distToJoint;
  77533. }
  77534. if (bone.getParent()) {
  77535. tempVec.addInPlace(mesh.getAbsolutePosition());
  77536. bone.setAbsolutePosition(tempVec, boneMesh);
  77537. }
  77538. else {
  77539. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  77540. boneMesh.position.x -= tempVec.x;
  77541. boneMesh.position.y -= tempVec.y;
  77542. boneMesh.position.z -= tempVec.z;
  77543. }
  77544. };
  77545. /**
  77546. * Sync impostor to a bone
  77547. * @param bone The bone that the impostor will be synced to.
  77548. * @param boneMesh The mesh that the bone is influencing.
  77549. * @param jointPivot The pivot of the joint / bone in local space.
  77550. * @param distToJoint Optional distance from the impostor to the joint.
  77551. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  77552. * @param boneAxis Optional vector3 axis the bone is aligned with
  77553. */
  77554. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  77555. var mesh = this.object;
  77556. if (mesh.rotationQuaternion) {
  77557. if (adjustRotation) {
  77558. var tempQuat = PhysicsImpostor._tmpQuat;
  77559. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  77560. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  77561. }
  77562. else {
  77563. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  77564. }
  77565. }
  77566. var pos = PhysicsImpostor._tmpVecs[0];
  77567. var boneDir = PhysicsImpostor._tmpVecs[1];
  77568. if (!boneAxis) {
  77569. boneAxis = PhysicsImpostor._tmpVecs[2];
  77570. boneAxis.x = 0;
  77571. boneAxis.y = 1;
  77572. boneAxis.z = 0;
  77573. }
  77574. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  77575. bone.getAbsolutePositionToRef(boneMesh, pos);
  77576. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  77577. distToJoint = jointPivot.length();
  77578. }
  77579. if (distToJoint !== undefined && distToJoint !== null) {
  77580. pos.x += boneDir.x * distToJoint;
  77581. pos.y += boneDir.y * distToJoint;
  77582. pos.z += boneDir.z * distToJoint;
  77583. }
  77584. mesh.setAbsolutePosition(pos);
  77585. };
  77586. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  77587. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  77588. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77589. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  77590. //Impostor types
  77591. PhysicsImpostor.NoImpostor = 0;
  77592. PhysicsImpostor.SphereImpostor = 1;
  77593. PhysicsImpostor.BoxImpostor = 2;
  77594. PhysicsImpostor.PlaneImpostor = 3;
  77595. PhysicsImpostor.MeshImpostor = 4;
  77596. PhysicsImpostor.CylinderImpostor = 7;
  77597. PhysicsImpostor.ParticleImpostor = 8;
  77598. PhysicsImpostor.HeightmapImpostor = 9;
  77599. return PhysicsImpostor;
  77600. }());
  77601. BABYLON.PhysicsImpostor = PhysicsImpostor;
  77602. })(BABYLON || (BABYLON = {}));
  77603. //# sourceMappingURL=babylon.physicsImpostor.js.map
  77604. "use strict";
  77605. var BABYLON;
  77606. (function (BABYLON) {
  77607. var PhysicsEngine = /** @class */ (function () {
  77608. function PhysicsEngine(gravity, _physicsPlugin) {
  77609. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  77610. this._physicsPlugin = _physicsPlugin;
  77611. //new methods and parameters
  77612. this._impostors = [];
  77613. this._joints = [];
  77614. if (!this._physicsPlugin.isSupported()) {
  77615. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  77616. + "Please make sure it is included.");
  77617. }
  77618. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  77619. this.setGravity(gravity);
  77620. this.setTimeStep();
  77621. }
  77622. PhysicsEngine.prototype.setGravity = function (gravity) {
  77623. this.gravity = gravity;
  77624. this._physicsPlugin.setGravity(this.gravity);
  77625. };
  77626. /**
  77627. * Set the time step of the physics engine.
  77628. * default is 1/60.
  77629. * To slow it down, enter 1/600 for example.
  77630. * To speed it up, 1/30
  77631. * @param {number} newTimeStep the new timestep to apply to this world.
  77632. */
  77633. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  77634. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  77635. this._physicsPlugin.setTimeStep(newTimeStep);
  77636. };
  77637. /**
  77638. * Get the time step of the physics engine.
  77639. */
  77640. PhysicsEngine.prototype.getTimeStep = function () {
  77641. return this._physicsPlugin.getTimeStep();
  77642. };
  77643. PhysicsEngine.prototype.dispose = function () {
  77644. this._impostors.forEach(function (impostor) {
  77645. impostor.dispose();
  77646. });
  77647. this._physicsPlugin.dispose();
  77648. };
  77649. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  77650. return this._physicsPlugin.name;
  77651. };
  77652. /**
  77653. * Adding a new impostor for the impostor tracking.
  77654. * This will be done by the impostor itself.
  77655. * @param {PhysicsImpostor} impostor the impostor to add
  77656. */
  77657. PhysicsEngine.prototype.addImpostor = function (impostor) {
  77658. impostor.uniqueId = this._impostors.push(impostor);
  77659. //if no parent, generate the body
  77660. if (!impostor.parent) {
  77661. this._physicsPlugin.generatePhysicsBody(impostor);
  77662. }
  77663. };
  77664. /**
  77665. * Remove an impostor from the engine.
  77666. * This impostor and its mesh will not longer be updated by the physics engine.
  77667. * @param {PhysicsImpostor} impostor the impostor to remove
  77668. */
  77669. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  77670. var index = this._impostors.indexOf(impostor);
  77671. if (index > -1) {
  77672. var removed = this._impostors.splice(index, 1);
  77673. //Is it needed?
  77674. if (removed.length) {
  77675. //this will also remove it from the world.
  77676. removed[0].physicsBody = null;
  77677. }
  77678. }
  77679. };
  77680. /**
  77681. * Add a joint to the physics engine
  77682. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  77683. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  77684. * @param {PhysicsJoint} the joint that will connect both impostors.
  77685. */
  77686. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  77687. var impostorJoint = {
  77688. mainImpostor: mainImpostor,
  77689. connectedImpostor: connectedImpostor,
  77690. joint: joint
  77691. };
  77692. joint.physicsPlugin = this._physicsPlugin;
  77693. this._joints.push(impostorJoint);
  77694. this._physicsPlugin.generateJoint(impostorJoint);
  77695. };
  77696. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  77697. var matchingJoints = this._joints.filter(function (impostorJoint) {
  77698. return (impostorJoint.connectedImpostor === connectedImpostor
  77699. && impostorJoint.joint === joint
  77700. && impostorJoint.mainImpostor === mainImpostor);
  77701. });
  77702. if (matchingJoints.length) {
  77703. this._physicsPlugin.removeJoint(matchingJoints[0]);
  77704. //TODO remove it from the list as well
  77705. }
  77706. };
  77707. /**
  77708. * Called by the scene. no need to call it.
  77709. */
  77710. PhysicsEngine.prototype._step = function (delta) {
  77711. var _this = this;
  77712. //check if any mesh has no body / requires an update
  77713. this._impostors.forEach(function (impostor) {
  77714. if (impostor.isBodyInitRequired()) {
  77715. _this._physicsPlugin.generatePhysicsBody(impostor);
  77716. }
  77717. });
  77718. if (delta > 0.1) {
  77719. delta = 0.1;
  77720. }
  77721. else if (delta <= 0) {
  77722. delta = 1.0 / 60.0;
  77723. }
  77724. this._physicsPlugin.executeStep(delta, this._impostors);
  77725. };
  77726. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  77727. return this._physicsPlugin;
  77728. };
  77729. PhysicsEngine.prototype.getImpostors = function () {
  77730. return this._impostors;
  77731. };
  77732. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  77733. for (var i = 0; i < this._impostors.length; ++i) {
  77734. if (this._impostors[i].object === object) {
  77735. return this._impostors[i];
  77736. }
  77737. }
  77738. return null;
  77739. };
  77740. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  77741. for (var i = 0; i < this._impostors.length; ++i) {
  77742. if (this._impostors[i].physicsBody === body) {
  77743. return this._impostors[i];
  77744. }
  77745. }
  77746. return null;
  77747. };
  77748. // Statics
  77749. PhysicsEngine.Epsilon = 0.001;
  77750. return PhysicsEngine;
  77751. }());
  77752. BABYLON.PhysicsEngine = PhysicsEngine;
  77753. })(BABYLON || (BABYLON = {}));
  77754. //# sourceMappingURL=babylon.physicsEngine.js.map
  77755. "use strict";
  77756. var BABYLON;
  77757. (function (BABYLON) {
  77758. var PhysicsHelper = /** @class */ (function () {
  77759. function PhysicsHelper(scene) {
  77760. this._scene = scene;
  77761. this._physicsEngine = this._scene.getPhysicsEngine();
  77762. if (!this._physicsEngine) {
  77763. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  77764. }
  77765. }
  77766. /**
  77767. * @param {Vector3} origin the origin of the explosion
  77768. * @param {number} radius the explosion radius
  77769. * @param {number} strength the explosion strength
  77770. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  77771. */
  77772. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  77773. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77774. if (!this._physicsEngine) {
  77775. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  77776. return null;
  77777. }
  77778. var impostors = this._physicsEngine.getImpostors();
  77779. if (impostors.length === 0) {
  77780. return null;
  77781. }
  77782. var event = new PhysicsRadialExplosionEvent(this._scene);
  77783. impostors.forEach(function (impostor) {
  77784. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  77785. if (!impostorForceAndContactPoint) {
  77786. return;
  77787. }
  77788. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77789. });
  77790. event.dispose(false);
  77791. return event;
  77792. };
  77793. /**
  77794. * @param {Vector3} origin the origin of the explosion
  77795. * @param {number} radius the explosion radius
  77796. * @param {number} strength the explosion strength
  77797. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  77798. */
  77799. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  77800. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77801. if (!this._physicsEngine) {
  77802. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77803. return null;
  77804. }
  77805. var impostors = this._physicsEngine.getImpostors();
  77806. if (impostors.length === 0) {
  77807. return null;
  77808. }
  77809. var event = new PhysicsRadialExplosionEvent(this._scene);
  77810. impostors.forEach(function (impostor) {
  77811. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  77812. if (!impostorForceAndContactPoint) {
  77813. return;
  77814. }
  77815. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77816. });
  77817. event.dispose(false);
  77818. return event;
  77819. };
  77820. /**
  77821. * @param {Vector3} origin the origin of the explosion
  77822. * @param {number} radius the explosion radius
  77823. * @param {number} strength the explosion strength
  77824. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  77825. */
  77826. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  77827. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77828. if (!this._physicsEngine) {
  77829. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77830. return null;
  77831. }
  77832. var impostors = this._physicsEngine.getImpostors();
  77833. if (impostors.length === 0) {
  77834. return null;
  77835. }
  77836. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  77837. event.dispose(false);
  77838. return event;
  77839. };
  77840. /**
  77841. * @param {Vector3} origin the origin of the updraft
  77842. * @param {number} radius the radius of the updraft
  77843. * @param {number} strength the strength of the updraft
  77844. * @param {number} height the height of the updraft
  77845. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  77846. */
  77847. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  77848. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  77849. if (!this._physicsEngine) {
  77850. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77851. return null;
  77852. }
  77853. if (this._physicsEngine.getImpostors().length === 0) {
  77854. return null;
  77855. }
  77856. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  77857. event.dispose(false);
  77858. return event;
  77859. };
  77860. /**
  77861. * @param {Vector3} origin the of the vortex
  77862. * @param {number} radius the radius of the vortex
  77863. * @param {number} strength the strength of the vortex
  77864. * @param {number} height the height of the vortex
  77865. */
  77866. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  77867. if (!this._physicsEngine) {
  77868. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77869. return null;
  77870. }
  77871. if (this._physicsEngine.getImpostors().length === 0) {
  77872. return null;
  77873. }
  77874. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  77875. event.dispose(false);
  77876. return event;
  77877. };
  77878. return PhysicsHelper;
  77879. }());
  77880. BABYLON.PhysicsHelper = PhysicsHelper;
  77881. /***** Radial explosion *****/
  77882. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  77883. function PhysicsRadialExplosionEvent(scene) {
  77884. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  77885. this._rays = [];
  77886. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  77887. this._scene = scene;
  77888. }
  77889. /**
  77890. * Returns the data related to the radial explosion event (sphere & rays).
  77891. * @returns {PhysicsRadialExplosionEventData}
  77892. */
  77893. PhysicsRadialExplosionEvent.prototype.getData = function () {
  77894. this._dataFetched = true;
  77895. return {
  77896. sphere: this._sphere,
  77897. rays: this._rays,
  77898. };
  77899. };
  77900. /**
  77901. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  77902. * @param impostor
  77903. * @param {Vector3} origin the origin of the explosion
  77904. * @param {number} radius the explosion radius
  77905. * @param {number} strength the explosion strength
  77906. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  77907. * @returns {Nullable<PhysicsForceAndContactPoint>}
  77908. */
  77909. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  77910. if (impostor.mass === 0) {
  77911. return null;
  77912. }
  77913. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  77914. return null;
  77915. }
  77916. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  77917. return null;
  77918. }
  77919. var impostorObjectCenter = impostor.getObjectCenter();
  77920. var direction = impostorObjectCenter.subtract(origin);
  77921. var ray = new BABYLON.Ray(origin, direction, radius);
  77922. this._rays.push(ray);
  77923. var hit = ray.intersectsMesh(impostor.object);
  77924. var contactPoint = hit.pickedPoint;
  77925. if (!contactPoint) {
  77926. return null;
  77927. }
  77928. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  77929. if (distanceFromOrigin > radius) {
  77930. return null;
  77931. }
  77932. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  77933. ? strength
  77934. : strength * (1 - (distanceFromOrigin / radius));
  77935. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  77936. return { force: force, contactPoint: contactPoint };
  77937. };
  77938. /**
  77939. * Disposes the sphere.
  77940. * @param {bolean} force
  77941. */
  77942. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  77943. var _this = this;
  77944. if (force === void 0) { force = true; }
  77945. if (force) {
  77946. this._sphere.dispose();
  77947. }
  77948. else {
  77949. setTimeout(function () {
  77950. if (!_this._dataFetched) {
  77951. _this._sphere.dispose();
  77952. }
  77953. }, 0);
  77954. }
  77955. };
  77956. /*** Helpers ***/
  77957. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  77958. if (!this._sphere) {
  77959. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  77960. this._sphere.isVisible = false;
  77961. }
  77962. };
  77963. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  77964. var impostorObject = impostor.object;
  77965. this._prepareSphere();
  77966. this._sphere.position = origin;
  77967. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  77968. this._sphere._updateBoundingInfo();
  77969. this._sphere.computeWorldMatrix(true);
  77970. return this._sphere.intersectsMesh(impostorObject, true);
  77971. };
  77972. return PhysicsRadialExplosionEvent;
  77973. }());
  77974. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  77975. /***** Gravitational Field *****/
  77976. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  77977. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  77978. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77979. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  77980. this._physicsHelper = physicsHelper;
  77981. this._scene = scene;
  77982. this._origin = origin;
  77983. this._radius = radius;
  77984. this._strength = strength;
  77985. this._falloff = falloff;
  77986. this._tickCallback = this._tick.bind(this);
  77987. }
  77988. /**
  77989. * Returns the data related to the gravitational field event (sphere).
  77990. * @returns {PhysicsGravitationalFieldEventData}
  77991. */
  77992. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  77993. this._dataFetched = true;
  77994. return {
  77995. sphere: this._sphere,
  77996. };
  77997. };
  77998. /**
  77999. * Enables the gravitational field.
  78000. */
  78001. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  78002. this._tickCallback.call(this);
  78003. this._scene.registerBeforeRender(this._tickCallback);
  78004. };
  78005. /**
  78006. * Disables the gravitational field.
  78007. */
  78008. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  78009. this._scene.unregisterBeforeRender(this._tickCallback);
  78010. };
  78011. /**
  78012. * Disposes the sphere.
  78013. * @param {bolean} force
  78014. */
  78015. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  78016. var _this = this;
  78017. if (force === void 0) { force = true; }
  78018. if (force) {
  78019. this._sphere.dispose();
  78020. }
  78021. else {
  78022. setTimeout(function () {
  78023. if (!_this._dataFetched) {
  78024. _this._sphere.dispose();
  78025. }
  78026. }, 0);
  78027. }
  78028. };
  78029. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  78030. // Since the params won't change, we fetch the event only once
  78031. if (this._sphere) {
  78032. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  78033. }
  78034. else {
  78035. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  78036. if (radialExplosionEvent) {
  78037. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  78038. }
  78039. }
  78040. };
  78041. return PhysicsGravitationalFieldEvent;
  78042. }());
  78043. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  78044. /***** Updraft *****/
  78045. var PhysicsUpdraftEvent = /** @class */ (function () {
  78046. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  78047. this._scene = _scene;
  78048. this._origin = _origin;
  78049. this._radius = _radius;
  78050. this._strength = _strength;
  78051. this._height = _height;
  78052. this._updraftMode = _updraftMode;
  78053. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  78054. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  78055. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  78056. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  78057. this._physicsEngine = this._scene.getPhysicsEngine();
  78058. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  78059. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  78060. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  78061. this._originDirection = this._origin.subtract(this._originTop).normalize();
  78062. }
  78063. this._tickCallback = this._tick.bind(this);
  78064. }
  78065. /**
  78066. * Returns the data related to the updraft event (cylinder).
  78067. * @returns {PhysicsUpdraftEventData}
  78068. */
  78069. PhysicsUpdraftEvent.prototype.getData = function () {
  78070. this._dataFetched = true;
  78071. return {
  78072. cylinder: this._cylinder,
  78073. };
  78074. };
  78075. /**
  78076. * Enables the updraft.
  78077. */
  78078. PhysicsUpdraftEvent.prototype.enable = function () {
  78079. this._tickCallback.call(this);
  78080. this._scene.registerBeforeRender(this._tickCallback);
  78081. };
  78082. /**
  78083. * Disables the cortex.
  78084. */
  78085. PhysicsUpdraftEvent.prototype.disable = function () {
  78086. this._scene.unregisterBeforeRender(this._tickCallback);
  78087. };
  78088. /**
  78089. * Disposes the sphere.
  78090. * @param {bolean} force
  78091. */
  78092. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  78093. var _this = this;
  78094. if (force === void 0) { force = true; }
  78095. if (force) {
  78096. this._cylinder.dispose();
  78097. }
  78098. else {
  78099. setTimeout(function () {
  78100. if (!_this._dataFetched) {
  78101. _this._cylinder.dispose();
  78102. }
  78103. }, 0);
  78104. }
  78105. };
  78106. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  78107. if (impostor.mass === 0) {
  78108. return null;
  78109. }
  78110. if (!this._intersectsWithCylinder(impostor)) {
  78111. return null;
  78112. }
  78113. var impostorObjectCenter = impostor.getObjectCenter();
  78114. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  78115. var direction = this._originDirection;
  78116. }
  78117. else {
  78118. var direction = impostorObjectCenter.subtract(this._originTop);
  78119. }
  78120. var multiplier = this._strength * -1;
  78121. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  78122. return { force: force, contactPoint: impostorObjectCenter };
  78123. };
  78124. PhysicsUpdraftEvent.prototype._tick = function () {
  78125. var _this = this;
  78126. this._physicsEngine.getImpostors().forEach(function (impostor) {
  78127. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  78128. if (!impostorForceAndContactPoint) {
  78129. return;
  78130. }
  78131. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  78132. });
  78133. };
  78134. /*** Helpers ***/
  78135. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  78136. if (!this._cylinder) {
  78137. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  78138. height: this._height,
  78139. diameter: this._radius * 2,
  78140. }, this._scene);
  78141. this._cylinder.isVisible = false;
  78142. }
  78143. };
  78144. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  78145. var impostorObject = impostor.object;
  78146. this._prepareCylinder();
  78147. this._cylinder.position = this._cylinderPosition;
  78148. return this._cylinder.intersectsMesh(impostorObject, true);
  78149. };
  78150. return PhysicsUpdraftEvent;
  78151. }());
  78152. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  78153. /***** Vortex *****/
  78154. var PhysicsVortexEvent = /** @class */ (function () {
  78155. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  78156. this._scene = _scene;
  78157. this._origin = _origin;
  78158. this._radius = _radius;
  78159. this._strength = _strength;
  78160. this._height = _height;
  78161. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  78162. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  78163. this._updraftMultiplier = 0.02;
  78164. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  78165. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  78166. this._physicsEngine = this._scene.getPhysicsEngine();
  78167. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  78168. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  78169. this._tickCallback = this._tick.bind(this);
  78170. }
  78171. /**
  78172. * Returns the data related to the vortex event (cylinder).
  78173. * @returns {PhysicsVortexEventData}
  78174. */
  78175. PhysicsVortexEvent.prototype.getData = function () {
  78176. this._dataFetched = true;
  78177. return {
  78178. cylinder: this._cylinder,
  78179. };
  78180. };
  78181. /**
  78182. * Enables the vortex.
  78183. */
  78184. PhysicsVortexEvent.prototype.enable = function () {
  78185. this._tickCallback.call(this);
  78186. this._scene.registerBeforeRender(this._tickCallback);
  78187. };
  78188. /**
  78189. * Disables the cortex.
  78190. */
  78191. PhysicsVortexEvent.prototype.disable = function () {
  78192. this._scene.unregisterBeforeRender(this._tickCallback);
  78193. };
  78194. /**
  78195. * Disposes the sphere.
  78196. * @param {bolean} force
  78197. */
  78198. PhysicsVortexEvent.prototype.dispose = function (force) {
  78199. var _this = this;
  78200. if (force === void 0) { force = true; }
  78201. if (force) {
  78202. this._cylinder.dispose();
  78203. }
  78204. else {
  78205. setTimeout(function () {
  78206. if (!_this._dataFetched) {
  78207. _this._cylinder.dispose();
  78208. }
  78209. }, 0);
  78210. }
  78211. };
  78212. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  78213. if (impostor.mass === 0) {
  78214. return null;
  78215. }
  78216. if (!this._intersectsWithCylinder(impostor)) {
  78217. return null;
  78218. }
  78219. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  78220. return null;
  78221. }
  78222. var impostorObjectCenter = impostor.getObjectCenter();
  78223. 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)
  78224. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  78225. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  78226. var hit = ray.intersectsMesh(impostor.object);
  78227. var contactPoint = hit.pickedPoint;
  78228. if (!contactPoint) {
  78229. return null;
  78230. }
  78231. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  78232. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  78233. var directionToOrigin = contactPoint.normalize();
  78234. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  78235. directionToOrigin = directionToOrigin.negate();
  78236. }
  78237. // TODO: find a more physically based solution
  78238. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  78239. var forceX = directionToOrigin.x * this._strength / 8;
  78240. var forceY = directionToOrigin.y * this._updraftMultiplier;
  78241. var forceZ = directionToOrigin.z * this._strength / 8;
  78242. }
  78243. else {
  78244. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  78245. var forceY = this._originTop.y * this._updraftMultiplier;
  78246. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  78247. }
  78248. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  78249. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  78250. return { force: force, contactPoint: impostorObjectCenter };
  78251. };
  78252. PhysicsVortexEvent.prototype._tick = function () {
  78253. var _this = this;
  78254. this._physicsEngine.getImpostors().forEach(function (impostor) {
  78255. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  78256. if (!impostorForceAndContactPoint) {
  78257. return;
  78258. }
  78259. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  78260. });
  78261. };
  78262. /*** Helpers ***/
  78263. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  78264. if (!this._cylinder) {
  78265. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  78266. height: this._height,
  78267. diameter: this._radius * 2,
  78268. }, this._scene);
  78269. this._cylinder.isVisible = false;
  78270. }
  78271. };
  78272. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  78273. var impostorObject = impostor.object;
  78274. this._prepareCylinder();
  78275. this._cylinder.position = this._cylinderPosition;
  78276. return this._cylinder.intersectsMesh(impostorObject, true);
  78277. };
  78278. return PhysicsVortexEvent;
  78279. }());
  78280. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  78281. /***** Enums *****/
  78282. /**
  78283. * The strenght of the force in correspondence to the distance of the affected object
  78284. */
  78285. var PhysicsRadialImpulseFalloff;
  78286. (function (PhysicsRadialImpulseFalloff) {
  78287. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  78288. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  78289. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  78290. /**
  78291. * The strenght of the force in correspondence to the distance of the affected object
  78292. */
  78293. var PhysicsUpdraftMode;
  78294. (function (PhysicsUpdraftMode) {
  78295. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  78296. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  78297. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  78298. })(BABYLON || (BABYLON = {}));
  78299. //# sourceMappingURL=babylon.physicsHelper.js.map
  78300. "use strict";
  78301. var BABYLON;
  78302. (function (BABYLON) {
  78303. var CannonJSPlugin = /** @class */ (function () {
  78304. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  78305. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  78306. if (iterations === void 0) { iterations = 10; }
  78307. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  78308. this.name = "CannonJSPlugin";
  78309. this._physicsMaterials = new Array();
  78310. this._fixedTimeStep = 1 / 60;
  78311. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  78312. this.BJSCANNON = CANNON;
  78313. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  78314. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  78315. this._tmpPosition = BABYLON.Vector3.Zero();
  78316. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  78317. this._tmpUnityRotation = new BABYLON.Quaternion();
  78318. if (!this.isSupported()) {
  78319. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  78320. return;
  78321. }
  78322. this._extendNamespace();
  78323. this.world = new this.BJSCANNON.World();
  78324. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  78325. this.world.solver.iterations = iterations;
  78326. }
  78327. CannonJSPlugin.prototype.setGravity = function (gravity) {
  78328. this.world.gravity.copy(gravity);
  78329. };
  78330. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  78331. this._fixedTimeStep = timeStep;
  78332. };
  78333. CannonJSPlugin.prototype.getTimeStep = function () {
  78334. return this._fixedTimeStep;
  78335. };
  78336. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  78337. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  78338. };
  78339. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  78340. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  78341. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  78342. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  78343. };
  78344. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  78345. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  78346. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  78347. impostor.physicsBody.applyForce(impulse, worldPoint);
  78348. };
  78349. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  78350. //parent-child relationship. Does this impostor has a parent impostor?
  78351. if (impostor.parent) {
  78352. if (impostor.physicsBody) {
  78353. this.removePhysicsBody(impostor);
  78354. //TODO is that needed?
  78355. impostor.forceUpdate();
  78356. }
  78357. return;
  78358. }
  78359. //should a new body be created for this impostor?
  78360. if (impostor.isBodyInitRequired()) {
  78361. var shape = this._createShape(impostor);
  78362. //unregister events, if body is being changed
  78363. var oldBody = impostor.physicsBody;
  78364. if (oldBody) {
  78365. this.removePhysicsBody(impostor);
  78366. }
  78367. //create the body and material
  78368. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  78369. var bodyCreationObject = {
  78370. mass: impostor.getParam("mass"),
  78371. material: material
  78372. };
  78373. // A simple extend, in case native options were used.
  78374. var nativeOptions = impostor.getParam("nativeOptions");
  78375. for (var key in nativeOptions) {
  78376. if (nativeOptions.hasOwnProperty(key)) {
  78377. bodyCreationObject[key] = nativeOptions[key];
  78378. }
  78379. }
  78380. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  78381. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  78382. this.world.addEventListener("preStep", impostor.beforeStep);
  78383. this.world.addEventListener("postStep", impostor.afterStep);
  78384. impostor.physicsBody.addShape(shape);
  78385. this.world.add(impostor.physicsBody);
  78386. //try to keep the body moving in the right direction by taking old properties.
  78387. //Should be tested!
  78388. if (oldBody) {
  78389. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  78390. impostor.physicsBody[param].copy(oldBody[param]);
  78391. });
  78392. }
  78393. this._processChildMeshes(impostor);
  78394. }
  78395. //now update the body's transformation
  78396. this._updatePhysicsBodyTransformation(impostor);
  78397. };
  78398. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  78399. var _this = this;
  78400. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  78401. var currentRotation = mainImpostor.object.rotationQuaternion;
  78402. if (meshChildren.length) {
  78403. var processMesh = function (localPosition, mesh) {
  78404. if (!currentRotation || !mesh.rotationQuaternion) {
  78405. return;
  78406. }
  78407. var childImpostor = mesh.getPhysicsImpostor();
  78408. if (childImpostor) {
  78409. var parent = childImpostor.parent;
  78410. if (parent !== mainImpostor) {
  78411. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  78412. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  78413. if (childImpostor.physicsBody) {
  78414. _this.removePhysicsBody(childImpostor);
  78415. childImpostor.physicsBody = null;
  78416. }
  78417. childImpostor.parent = mainImpostor;
  78418. childImpostor.resetUpdateFlags();
  78419. 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));
  78420. //Add the mass of the children.
  78421. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  78422. }
  78423. }
  78424. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  78425. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  78426. };
  78427. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  78428. }
  78429. };
  78430. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  78431. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  78432. this.world.removeEventListener("preStep", impostor.beforeStep);
  78433. this.world.removeEventListener("postStep", impostor.afterStep);
  78434. this.world.remove(impostor.physicsBody);
  78435. };
  78436. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  78437. var mainBody = impostorJoint.mainImpostor.physicsBody;
  78438. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  78439. if (!mainBody || !connectedBody) {
  78440. return;
  78441. }
  78442. var constraint;
  78443. var jointData = impostorJoint.joint.jointData;
  78444. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  78445. var constraintData = {
  78446. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  78447. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  78448. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  78449. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  78450. maxForce: jointData.nativeParams.maxForce,
  78451. collideConnected: !!jointData.collision
  78452. };
  78453. switch (impostorJoint.joint.type) {
  78454. case BABYLON.PhysicsJoint.HingeJoint:
  78455. case BABYLON.PhysicsJoint.Hinge2Joint:
  78456. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  78457. break;
  78458. case BABYLON.PhysicsJoint.DistanceJoint:
  78459. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  78460. break;
  78461. case BABYLON.PhysicsJoint.SpringJoint:
  78462. var springData = jointData;
  78463. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  78464. restLength: springData.length,
  78465. stiffness: springData.stiffness,
  78466. damping: springData.damping,
  78467. localAnchorA: constraintData.pivotA,
  78468. localAnchorB: constraintData.pivotB
  78469. });
  78470. break;
  78471. case BABYLON.PhysicsJoint.LockJoint:
  78472. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  78473. break;
  78474. case BABYLON.PhysicsJoint.PointToPointJoint:
  78475. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  78476. default:
  78477. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  78478. break;
  78479. }
  78480. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  78481. constraint.collideConnected = !!jointData.collision;
  78482. impostorJoint.joint.physicsJoint = constraint;
  78483. //don't add spring as constraint, as it is not one.
  78484. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  78485. this.world.addConstraint(constraint);
  78486. }
  78487. else {
  78488. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  78489. constraint.applyForce();
  78490. });
  78491. }
  78492. };
  78493. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  78494. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  78495. };
  78496. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  78497. var index;
  78498. var mat;
  78499. for (index = 0; index < this._physicsMaterials.length; index++) {
  78500. mat = this._physicsMaterials[index];
  78501. if (mat.friction === friction && mat.restitution === restitution) {
  78502. return mat;
  78503. }
  78504. }
  78505. var currentMat = new this.BJSCANNON.Material(name);
  78506. currentMat.friction = friction;
  78507. currentMat.restitution = restitution;
  78508. this._physicsMaterials.push(currentMat);
  78509. return currentMat;
  78510. };
  78511. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  78512. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  78513. };
  78514. CannonJSPlugin.prototype._createShape = function (impostor) {
  78515. var object = impostor.object;
  78516. var returnValue;
  78517. var extendSize = impostor.getObjectExtendSize();
  78518. switch (impostor.type) {
  78519. case BABYLON.PhysicsImpostor.SphereImpostor:
  78520. var radiusX = extendSize.x;
  78521. var radiusY = extendSize.y;
  78522. var radiusZ = extendSize.z;
  78523. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  78524. break;
  78525. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  78526. case BABYLON.PhysicsImpostor.CylinderImpostor:
  78527. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  78528. break;
  78529. case BABYLON.PhysicsImpostor.BoxImpostor:
  78530. var box = extendSize.scale(0.5);
  78531. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  78532. break;
  78533. case BABYLON.PhysicsImpostor.PlaneImpostor:
  78534. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  78535. returnValue = new this.BJSCANNON.Plane();
  78536. break;
  78537. case BABYLON.PhysicsImpostor.MeshImpostor:
  78538. // should transform the vertex data to world coordinates!!
  78539. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  78540. var rawFaces = object.getIndices ? object.getIndices() : [];
  78541. if (!rawVerts)
  78542. return;
  78543. // get only scale! so the object could transform correctly.
  78544. var oldPosition = object.position.clone();
  78545. var oldRotation = object.rotation && object.rotation.clone();
  78546. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  78547. object.position.copyFromFloats(0, 0, 0);
  78548. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  78549. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  78550. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  78551. var transform = object.computeWorldMatrix(true);
  78552. // convert rawVerts to object space
  78553. var temp = new Array();
  78554. var index;
  78555. for (index = 0; index < rawVerts.length; index += 3) {
  78556. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  78557. }
  78558. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  78559. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  78560. //now set back the transformation!
  78561. object.position.copyFrom(oldPosition);
  78562. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  78563. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  78564. break;
  78565. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  78566. var oldPosition2 = object.position.clone();
  78567. var oldRotation2 = object.rotation && object.rotation.clone();
  78568. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  78569. object.position.copyFromFloats(0, 0, 0);
  78570. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  78571. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  78572. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  78573. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  78574. returnValue = this._createHeightmap(object);
  78575. object.position.copyFrom(oldPosition2);
  78576. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  78577. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  78578. object.computeWorldMatrix(true);
  78579. break;
  78580. case BABYLON.PhysicsImpostor.ParticleImpostor:
  78581. returnValue = new this.BJSCANNON.Particle();
  78582. break;
  78583. }
  78584. return returnValue;
  78585. };
  78586. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  78587. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  78588. var transform = object.computeWorldMatrix(true);
  78589. // convert rawVerts to object space
  78590. var temp = new Array();
  78591. var index;
  78592. for (index = 0; index < pos.length; index += 3) {
  78593. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  78594. }
  78595. pos = temp;
  78596. var matrix = new Array();
  78597. //For now pointDepth will not be used and will be automatically calculated.
  78598. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  78599. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  78600. var boundingInfo = object.getBoundingInfo();
  78601. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  78602. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  78603. var elementSize = dim * 2 / arraySize;
  78604. for (var i = 0; i < pos.length; i = i + 3) {
  78605. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  78606. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  78607. var y = -pos[i + 2] + minY;
  78608. if (!matrix[x]) {
  78609. matrix[x] = [];
  78610. }
  78611. if (!matrix[x][z]) {
  78612. matrix[x][z] = y;
  78613. }
  78614. matrix[x][z] = Math.max(y, matrix[x][z]);
  78615. }
  78616. for (var x = 0; x <= arraySize; ++x) {
  78617. if (!matrix[x]) {
  78618. var loc = 1;
  78619. while (!matrix[(x + loc) % arraySize]) {
  78620. loc++;
  78621. }
  78622. matrix[x] = matrix[(x + loc) % arraySize].slice();
  78623. //console.log("missing x", x);
  78624. }
  78625. for (var z = 0; z <= arraySize; ++z) {
  78626. if (!matrix[x][z]) {
  78627. var loc = 1;
  78628. var newValue;
  78629. while (newValue === undefined) {
  78630. newValue = matrix[x][(z + loc++) % arraySize];
  78631. }
  78632. matrix[x][z] = newValue;
  78633. }
  78634. }
  78635. }
  78636. var shape = new this.BJSCANNON.Heightfield(matrix, {
  78637. elementSize: elementSize
  78638. });
  78639. //For future reference, needed for body transformation
  78640. shape.minY = minY;
  78641. return shape;
  78642. };
  78643. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  78644. var object = impostor.object;
  78645. //make sure it is updated...
  78646. object.computeWorldMatrix && object.computeWorldMatrix(true);
  78647. // The delta between the mesh position and the mesh bounding box center
  78648. var bInfo = object.getBoundingInfo();
  78649. if (!bInfo)
  78650. return;
  78651. var center = impostor.getObjectCenter();
  78652. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  78653. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  78654. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  78655. this._tmpPosition.copyFrom(center);
  78656. var quaternion = object.rotationQuaternion;
  78657. if (!quaternion) {
  78658. return;
  78659. }
  78660. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  78661. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  78662. //-90 DEG in X, precalculated
  78663. quaternion = quaternion.multiply(this._minus90X);
  78664. //Invert! (Precalculated, 90 deg in X)
  78665. //No need to clone. this will never change.
  78666. impostor.setDeltaRotation(this._plus90X);
  78667. }
  78668. //If it is a heightfield, if should be centered.
  78669. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  78670. var mesh = object;
  78671. var boundingInfo = mesh.getBoundingInfo();
  78672. //calculate the correct body position:
  78673. var rotationQuaternion = mesh.rotationQuaternion;
  78674. mesh.rotationQuaternion = this._tmpUnityRotation;
  78675. mesh.computeWorldMatrix(true);
  78676. //get original center with no rotation
  78677. var c = center.clone();
  78678. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  78679. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  78680. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  78681. mesh.setPreTransformMatrix(p);
  78682. mesh.computeWorldMatrix(true);
  78683. //calculate the translation
  78684. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  78685. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  78686. //add it inverted to the delta
  78687. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  78688. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  78689. //rotation is back
  78690. mesh.rotationQuaternion = rotationQuaternion;
  78691. mesh.setPreTransformMatrix(oldPivot);
  78692. mesh.computeWorldMatrix(true);
  78693. }
  78694. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  78695. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  78696. //this._tmpPosition.copyFrom(object.position);
  78697. }
  78698. impostor.setDeltaPosition(this._tmpDeltaPosition);
  78699. //Now update the impostor object
  78700. impostor.physicsBody.position.copy(this._tmpPosition);
  78701. impostor.physicsBody.quaternion.copy(quaternion);
  78702. };
  78703. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  78704. impostor.object.position.copyFrom(impostor.physicsBody.position);
  78705. if (impostor.object.rotationQuaternion) {
  78706. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  78707. }
  78708. };
  78709. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  78710. impostor.physicsBody.position.copy(newPosition);
  78711. impostor.physicsBody.quaternion.copy(newRotation);
  78712. };
  78713. CannonJSPlugin.prototype.isSupported = function () {
  78714. return this.BJSCANNON !== undefined;
  78715. };
  78716. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  78717. impostor.physicsBody.velocity.copy(velocity);
  78718. };
  78719. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  78720. impostor.physicsBody.angularVelocity.copy(velocity);
  78721. };
  78722. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  78723. var v = impostor.physicsBody.velocity;
  78724. if (!v) {
  78725. return null;
  78726. }
  78727. return new BABYLON.Vector3(v.x, v.y, v.z);
  78728. };
  78729. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  78730. var v = impostor.physicsBody.angularVelocity;
  78731. if (!v) {
  78732. return null;
  78733. }
  78734. return new BABYLON.Vector3(v.x, v.y, v.z);
  78735. };
  78736. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  78737. impostor.physicsBody.mass = mass;
  78738. impostor.physicsBody.updateMassProperties();
  78739. };
  78740. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  78741. return impostor.physicsBody.mass;
  78742. };
  78743. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  78744. return impostor.physicsBody.material.friction;
  78745. };
  78746. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  78747. impostor.physicsBody.material.friction = friction;
  78748. };
  78749. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  78750. return impostor.physicsBody.material.restitution;
  78751. };
  78752. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  78753. impostor.physicsBody.material.restitution = restitution;
  78754. };
  78755. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  78756. impostor.physicsBody.sleep();
  78757. };
  78758. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  78759. impostor.physicsBody.wakeUp();
  78760. };
  78761. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  78762. joint.physicsJoint.distance = maxDistance;
  78763. };
  78764. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  78765. // if (!motorIndex) {
  78766. // joint.physicsJoint.enableMotor();
  78767. // }
  78768. // }
  78769. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  78770. // if (!motorIndex) {
  78771. // joint.physicsJoint.disableMotor();
  78772. // }
  78773. // }
  78774. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  78775. if (!motorIndex) {
  78776. joint.physicsJoint.enableMotor();
  78777. joint.physicsJoint.setMotorSpeed(speed);
  78778. if (maxForce) {
  78779. this.setLimit(joint, maxForce);
  78780. }
  78781. }
  78782. };
  78783. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  78784. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  78785. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  78786. };
  78787. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  78788. var body = impostor.physicsBody;
  78789. mesh.position.x = body.position.x;
  78790. mesh.position.y = body.position.y;
  78791. mesh.position.z = body.position.z;
  78792. if (mesh.rotationQuaternion) {
  78793. mesh.rotationQuaternion.x = body.quaternion.x;
  78794. mesh.rotationQuaternion.y = body.quaternion.y;
  78795. mesh.rotationQuaternion.z = body.quaternion.z;
  78796. mesh.rotationQuaternion.w = body.quaternion.w;
  78797. }
  78798. };
  78799. CannonJSPlugin.prototype.getRadius = function (impostor) {
  78800. var shape = impostor.physicsBody.shapes[0];
  78801. return shape.boundingSphereRadius;
  78802. };
  78803. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  78804. var shape = impostor.physicsBody.shapes[0];
  78805. result.x = shape.halfExtents.x * 2;
  78806. result.y = shape.halfExtents.y * 2;
  78807. result.z = shape.halfExtents.z * 2;
  78808. };
  78809. CannonJSPlugin.prototype.dispose = function () {
  78810. };
  78811. CannonJSPlugin.prototype._extendNamespace = function () {
  78812. //this will force cannon to execute at least one step when using interpolation
  78813. var step_tmp1 = new this.BJSCANNON.Vec3();
  78814. var Engine = this.BJSCANNON;
  78815. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  78816. maxSubSteps = maxSubSteps || 10;
  78817. timeSinceLastCalled = timeSinceLastCalled || 0;
  78818. if (timeSinceLastCalled === 0) {
  78819. this.internalStep(dt);
  78820. this.time += dt;
  78821. }
  78822. else {
  78823. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  78824. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  78825. var t0 = performance.now();
  78826. for (var i = 0; i !== internalSteps; i++) {
  78827. this.internalStep(dt);
  78828. if (performance.now() - t0 > dt * 1000) {
  78829. break;
  78830. }
  78831. }
  78832. this.time += timeSinceLastCalled;
  78833. var h = this.time % dt;
  78834. var h_div_dt = h / dt;
  78835. var interpvelo = step_tmp1;
  78836. var bodies = this.bodies;
  78837. for (var j = 0; j !== bodies.length; j++) {
  78838. var b = bodies[j];
  78839. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  78840. b.position.vsub(b.previousPosition, interpvelo);
  78841. interpvelo.scale(h_div_dt, interpvelo);
  78842. b.position.vadd(interpvelo, b.interpolatedPosition);
  78843. }
  78844. else {
  78845. b.interpolatedPosition.copy(b.position);
  78846. b.interpolatedQuaternion.copy(b.quaternion);
  78847. }
  78848. }
  78849. }
  78850. };
  78851. };
  78852. return CannonJSPlugin;
  78853. }());
  78854. BABYLON.CannonJSPlugin = CannonJSPlugin;
  78855. })(BABYLON || (BABYLON = {}));
  78856. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  78857. "use strict";
  78858. var BABYLON;
  78859. (function (BABYLON) {
  78860. var OimoJSPlugin = /** @class */ (function () {
  78861. function OimoJSPlugin(iterations) {
  78862. this.name = "OimoJSPlugin";
  78863. this._tmpImpostorsArray = [];
  78864. this._tmpPositionVector = BABYLON.Vector3.Zero();
  78865. this.BJSOIMO = OIMO;
  78866. this.world = new this.BJSOIMO.World({
  78867. iterations: iterations
  78868. });
  78869. this.world.clear();
  78870. }
  78871. OimoJSPlugin.prototype.setGravity = function (gravity) {
  78872. this.world.gravity.copy(gravity);
  78873. };
  78874. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  78875. this.world.timeStep = timeStep;
  78876. };
  78877. OimoJSPlugin.prototype.getTimeStep = function () {
  78878. return this.world.timeStep;
  78879. };
  78880. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  78881. var _this = this;
  78882. impostors.forEach(function (impostor) {
  78883. impostor.beforeStep();
  78884. });
  78885. this.world.step();
  78886. impostors.forEach(function (impostor) {
  78887. impostor.afterStep();
  78888. //update the ordered impostors array
  78889. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  78890. });
  78891. //check for collisions
  78892. var contact = this.world.contacts;
  78893. while (contact !== null) {
  78894. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  78895. contact = contact.next;
  78896. continue;
  78897. }
  78898. //is this body colliding with any other? get the impostor
  78899. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  78900. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  78901. if (!mainImpostor || !collidingImpostor) {
  78902. contact = contact.next;
  78903. continue;
  78904. }
  78905. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  78906. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  78907. contact = contact.next;
  78908. }
  78909. };
  78910. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  78911. var mass = impostor.physicsBody.mass;
  78912. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  78913. };
  78914. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  78915. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  78916. this.applyImpulse(impostor, force, contactPoint);
  78917. };
  78918. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  78919. var _this = this;
  78920. //parent-child relationship. Does this impostor has a parent impostor?
  78921. if (impostor.parent) {
  78922. if (impostor.physicsBody) {
  78923. this.removePhysicsBody(impostor);
  78924. //TODO is that needed?
  78925. impostor.forceUpdate();
  78926. }
  78927. return;
  78928. }
  78929. if (impostor.isBodyInitRequired()) {
  78930. var bodyConfig = {
  78931. name: impostor.uniqueId,
  78932. //Oimo must have mass, also for static objects.
  78933. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  78934. size: [],
  78935. type: [],
  78936. pos: [],
  78937. posShape: [],
  78938. rot: [],
  78939. rotShape: [],
  78940. move: impostor.getParam("mass") !== 0,
  78941. density: impostor.getParam("mass"),
  78942. friction: impostor.getParam("friction"),
  78943. restitution: impostor.getParam("restitution"),
  78944. //Supporting older versions of Oimo
  78945. world: this.world
  78946. };
  78947. var impostors = [impostor];
  78948. var addToArray = function (parent) {
  78949. if (!parent.getChildMeshes)
  78950. return;
  78951. parent.getChildMeshes().forEach(function (m) {
  78952. if (m.physicsImpostor) {
  78953. impostors.push(m.physicsImpostor);
  78954. //m.physicsImpostor._init();
  78955. }
  78956. });
  78957. };
  78958. addToArray(impostor.object);
  78959. var checkWithEpsilon_1 = function (value) {
  78960. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  78961. };
  78962. impostors.forEach(function (i) {
  78963. if (!i.object.rotationQuaternion) {
  78964. return;
  78965. }
  78966. //get the correct bounding box
  78967. var oldQuaternion = i.object.rotationQuaternion;
  78968. var rot = oldQuaternion.toEulerAngles();
  78969. var extendSize = i.getObjectExtendSize();
  78970. var radToDeg = 57.295779513082320876;
  78971. if (i === impostor) {
  78972. var center = impostor.getObjectCenter();
  78973. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  78974. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  78975. //Can also use Array.prototype.push.apply
  78976. bodyConfig.pos.push(center.x);
  78977. bodyConfig.pos.push(center.y);
  78978. bodyConfig.pos.push(center.z);
  78979. bodyConfig.posShape.push(0, 0, 0);
  78980. //tmp solution
  78981. bodyConfig.rot.push(rot.x * radToDeg);
  78982. bodyConfig.rot.push(rot.y * radToDeg);
  78983. bodyConfig.rot.push(rot.z * radToDeg);
  78984. bodyConfig.rotShape.push(0, 0, 0);
  78985. }
  78986. else {
  78987. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  78988. bodyConfig.posShape.push(localPosition.x);
  78989. bodyConfig.posShape.push(localPosition.y);
  78990. bodyConfig.posShape.push(localPosition.z);
  78991. bodyConfig.pos.push(0, 0, 0);
  78992. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  78993. bodyConfig.rot.push(0);
  78994. bodyConfig.rot.push(0);
  78995. bodyConfig.rot.push(0);
  78996. bodyConfig.rotShape.push(rot.x * radToDeg);
  78997. bodyConfig.rotShape.push(rot.y * radToDeg);
  78998. bodyConfig.rotShape.push(rot.z * radToDeg);
  78999. }
  79000. // register mesh
  79001. switch (i.type) {
  79002. case BABYLON.PhysicsImpostor.ParticleImpostor:
  79003. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  79004. case BABYLON.PhysicsImpostor.SphereImpostor:
  79005. var radiusX = extendSize.x;
  79006. var radiusY = extendSize.y;
  79007. var radiusZ = extendSize.z;
  79008. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  79009. bodyConfig.type.push('sphere');
  79010. //due to the way oimo works with compounds, add 3 times
  79011. bodyConfig.size.push(size);
  79012. bodyConfig.size.push(size);
  79013. bodyConfig.size.push(size);
  79014. break;
  79015. case BABYLON.PhysicsImpostor.CylinderImpostor:
  79016. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  79017. var sizeY = checkWithEpsilon_1(extendSize.y);
  79018. bodyConfig.type.push('cylinder');
  79019. bodyConfig.size.push(sizeX);
  79020. bodyConfig.size.push(sizeY);
  79021. //due to the way oimo works with compounds, add one more value.
  79022. bodyConfig.size.push(sizeY);
  79023. break;
  79024. case BABYLON.PhysicsImpostor.PlaneImpostor:
  79025. case BABYLON.PhysicsImpostor.BoxImpostor:
  79026. default:
  79027. var sizeX = checkWithEpsilon_1(extendSize.x);
  79028. var sizeY = checkWithEpsilon_1(extendSize.y);
  79029. var sizeZ = checkWithEpsilon_1(extendSize.z);
  79030. bodyConfig.type.push('box');
  79031. //if (i === impostor) {
  79032. bodyConfig.size.push(sizeX);
  79033. bodyConfig.size.push(sizeY);
  79034. bodyConfig.size.push(sizeZ);
  79035. //} else {
  79036. // bodyConfig.size.push(0,0,0);
  79037. //}
  79038. break;
  79039. }
  79040. //actually not needed, but hey...
  79041. i.object.rotationQuaternion = oldQuaternion;
  79042. });
  79043. impostor.physicsBody = this.world.add(bodyConfig);
  79044. }
  79045. else {
  79046. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  79047. }
  79048. impostor.setDeltaPosition(this._tmpPositionVector);
  79049. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  79050. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  79051. };
  79052. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  79053. //impostor.physicsBody.dispose();
  79054. //Same as : (older oimo versions)
  79055. this.world.removeRigidBody(impostor.physicsBody);
  79056. };
  79057. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  79058. var mainBody = impostorJoint.mainImpostor.physicsBody;
  79059. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  79060. if (!mainBody || !connectedBody) {
  79061. return;
  79062. }
  79063. var jointData = impostorJoint.joint.jointData;
  79064. var options = jointData.nativeParams || {};
  79065. var type;
  79066. var nativeJointData = {
  79067. body1: mainBody,
  79068. body2: connectedBody,
  79069. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  79070. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  79071. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  79072. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  79073. min: options.min,
  79074. max: options.max,
  79075. collision: options.collision || jointData.collision,
  79076. spring: options.spring,
  79077. //supporting older version of Oimo
  79078. world: this.world
  79079. };
  79080. switch (impostorJoint.joint.type) {
  79081. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  79082. type = "jointBall";
  79083. break;
  79084. case BABYLON.PhysicsJoint.SpringJoint:
  79085. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  79086. var springData = jointData;
  79087. nativeJointData.min = springData.length || nativeJointData.min;
  79088. //Max should also be set, just make sure it is at least min
  79089. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  79090. case BABYLON.PhysicsJoint.DistanceJoint:
  79091. type = "jointDistance";
  79092. nativeJointData.max = jointData.maxDistance;
  79093. break;
  79094. case BABYLON.PhysicsJoint.PrismaticJoint:
  79095. type = "jointPrisme";
  79096. break;
  79097. case BABYLON.PhysicsJoint.SliderJoint:
  79098. type = "jointSlide";
  79099. break;
  79100. case BABYLON.PhysicsJoint.WheelJoint:
  79101. type = "jointWheel";
  79102. break;
  79103. case BABYLON.PhysicsJoint.HingeJoint:
  79104. default:
  79105. type = "jointHinge";
  79106. break;
  79107. }
  79108. nativeJointData.type = type;
  79109. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  79110. };
  79111. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  79112. //Bug in Oimo prevents us from disposing a joint in the playground
  79113. //joint.joint.physicsJoint.dispose();
  79114. //So we will bruteforce it!
  79115. try {
  79116. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  79117. }
  79118. catch (e) {
  79119. BABYLON.Tools.Warn(e);
  79120. }
  79121. };
  79122. OimoJSPlugin.prototype.isSupported = function () {
  79123. return this.BJSOIMO !== undefined;
  79124. };
  79125. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  79126. if (!impostor.physicsBody.sleeping) {
  79127. //TODO check that
  79128. /*if (impostor.physicsBody.shapes.next) {
  79129. var parentShape = this._getLastShape(impostor.physicsBody);
  79130. impostor.object.position.copyFrom(parentShape.position);
  79131. console.log(parentShape.position);
  79132. } else {*/
  79133. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  79134. //}
  79135. if (impostor.object.rotationQuaternion) {
  79136. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  79137. }
  79138. }
  79139. };
  79140. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  79141. var body = impostor.physicsBody;
  79142. body.position.copy(newPosition);
  79143. body.orientation.copy(newRotation);
  79144. body.syncShapes();
  79145. body.awake();
  79146. };
  79147. /*private _getLastShape(body: any): any {
  79148. var lastShape = body.shapes;
  79149. while (lastShape.next) {
  79150. lastShape = lastShape.next;
  79151. }
  79152. return lastShape;
  79153. }*/
  79154. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  79155. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  79156. };
  79157. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  79158. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  79159. };
  79160. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  79161. var v = impostor.physicsBody.linearVelocity;
  79162. if (!v) {
  79163. return null;
  79164. }
  79165. return new BABYLON.Vector3(v.x, v.y, v.z);
  79166. };
  79167. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  79168. var v = impostor.physicsBody.angularVelocity;
  79169. if (!v) {
  79170. return null;
  79171. }
  79172. return new BABYLON.Vector3(v.x, v.y, v.z);
  79173. };
  79174. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  79175. var staticBody = mass === 0;
  79176. //this will actually set the body's density and not its mass.
  79177. //But this is how oimo treats the mass variable.
  79178. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  79179. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  79180. };
  79181. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  79182. return impostor.physicsBody.shapes.density;
  79183. };
  79184. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  79185. return impostor.physicsBody.shapes.friction;
  79186. };
  79187. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  79188. impostor.physicsBody.shapes.friction = friction;
  79189. };
  79190. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  79191. return impostor.physicsBody.shapes.restitution;
  79192. };
  79193. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  79194. impostor.physicsBody.shapes.restitution = restitution;
  79195. };
  79196. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  79197. impostor.physicsBody.sleep();
  79198. };
  79199. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  79200. impostor.physicsBody.awake();
  79201. };
  79202. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  79203. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  79204. if (minDistance !== void 0) {
  79205. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  79206. }
  79207. };
  79208. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  79209. //TODO separate rotational and transational motors.
  79210. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  79211. if (motor) {
  79212. motor.setMotor(speed, maxForce);
  79213. }
  79214. };
  79215. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  79216. //TODO separate rotational and transational motors.
  79217. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  79218. if (motor) {
  79219. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  79220. }
  79221. };
  79222. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  79223. var body = impostor.physicsBody;
  79224. mesh.position.x = body.position.x;
  79225. mesh.position.y = body.position.y;
  79226. mesh.position.z = body.position.z;
  79227. if (mesh.rotationQuaternion) {
  79228. mesh.rotationQuaternion.x = body.orientation.x;
  79229. mesh.rotationQuaternion.y = body.orientation.y;
  79230. mesh.rotationQuaternion.z = body.orientation.z;
  79231. mesh.rotationQuaternion.w = body.orientation.s;
  79232. }
  79233. };
  79234. OimoJSPlugin.prototype.getRadius = function (impostor) {
  79235. return impostor.physicsBody.shapes.radius;
  79236. };
  79237. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  79238. var shape = impostor.physicsBody.shapes;
  79239. result.x = shape.halfWidth * 2;
  79240. result.y = shape.halfHeight * 2;
  79241. result.z = shape.halfDepth * 2;
  79242. };
  79243. OimoJSPlugin.prototype.dispose = function () {
  79244. this.world.clear();
  79245. };
  79246. return OimoJSPlugin;
  79247. }());
  79248. BABYLON.OimoJSPlugin = OimoJSPlugin;
  79249. })(BABYLON || (BABYLON = {}));
  79250. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  79251. "use strict";
  79252. var BABYLON;
  79253. (function (BABYLON) {
  79254. /*
  79255. * Based on jsTGALoader - Javascript loader for TGA file
  79256. * By Vincent Thibault
  79257. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  79258. */
  79259. var TGATools = /** @class */ (function () {
  79260. function TGATools() {
  79261. }
  79262. TGATools.GetTGAHeader = function (data) {
  79263. var offset = 0;
  79264. var header = {
  79265. id_length: data[offset++],
  79266. colormap_type: data[offset++],
  79267. image_type: data[offset++],
  79268. colormap_index: data[offset++] | data[offset++] << 8,
  79269. colormap_length: data[offset++] | data[offset++] << 8,
  79270. colormap_size: data[offset++],
  79271. origin: [
  79272. data[offset++] | data[offset++] << 8,
  79273. data[offset++] | data[offset++] << 8
  79274. ],
  79275. width: data[offset++] | data[offset++] << 8,
  79276. height: data[offset++] | data[offset++] << 8,
  79277. pixel_size: data[offset++],
  79278. flags: data[offset++]
  79279. };
  79280. return header;
  79281. };
  79282. TGATools.UploadContent = function (gl, data) {
  79283. // Not enough data to contain header ?
  79284. if (data.length < 19) {
  79285. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  79286. return;
  79287. }
  79288. // Read Header
  79289. var offset = 18;
  79290. var header = TGATools.GetTGAHeader(data);
  79291. // Assume it's a valid Targa file.
  79292. if (header.id_length + offset > data.length) {
  79293. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  79294. return;
  79295. }
  79296. // Skip not needed data
  79297. offset += header.id_length;
  79298. var use_rle = false;
  79299. var use_pal = false;
  79300. var use_grey = false;
  79301. // Get some informations.
  79302. switch (header.image_type) {
  79303. case TGATools._TYPE_RLE_INDEXED:
  79304. use_rle = true;
  79305. case TGATools._TYPE_INDEXED:
  79306. use_pal = true;
  79307. break;
  79308. case TGATools._TYPE_RLE_RGB:
  79309. use_rle = true;
  79310. case TGATools._TYPE_RGB:
  79311. // use_rgb = true;
  79312. break;
  79313. case TGATools._TYPE_RLE_GREY:
  79314. use_rle = true;
  79315. case TGATools._TYPE_GREY:
  79316. use_grey = true;
  79317. break;
  79318. }
  79319. var pixel_data;
  79320. // var numAlphaBits = header.flags & 0xf;
  79321. var pixel_size = header.pixel_size >> 3;
  79322. var pixel_total = header.width * header.height * pixel_size;
  79323. // Read palettes
  79324. var palettes;
  79325. if (use_pal) {
  79326. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  79327. }
  79328. // Read LRE
  79329. if (use_rle) {
  79330. pixel_data = new Uint8Array(pixel_total);
  79331. var c, count, i;
  79332. var localOffset = 0;
  79333. var pixels = new Uint8Array(pixel_size);
  79334. while (offset < pixel_total && localOffset < pixel_total) {
  79335. c = data[offset++];
  79336. count = (c & 0x7f) + 1;
  79337. // RLE pixels
  79338. if (c & 0x80) {
  79339. // Bind pixel tmp array
  79340. for (i = 0; i < pixel_size; ++i) {
  79341. pixels[i] = data[offset++];
  79342. }
  79343. // Copy pixel array
  79344. for (i = 0; i < count; ++i) {
  79345. pixel_data.set(pixels, localOffset + i * pixel_size);
  79346. }
  79347. localOffset += pixel_size * count;
  79348. }
  79349. else {
  79350. count *= pixel_size;
  79351. for (i = 0; i < count; ++i) {
  79352. pixel_data[localOffset + i] = data[offset++];
  79353. }
  79354. localOffset += count;
  79355. }
  79356. }
  79357. }
  79358. else {
  79359. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  79360. }
  79361. // Load to texture
  79362. var x_start, y_start, x_step, y_step, y_end, x_end;
  79363. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  79364. default:
  79365. case TGATools._ORIGIN_UL:
  79366. x_start = 0;
  79367. x_step = 1;
  79368. x_end = header.width;
  79369. y_start = 0;
  79370. y_step = 1;
  79371. y_end = header.height;
  79372. break;
  79373. case TGATools._ORIGIN_BL:
  79374. x_start = 0;
  79375. x_step = 1;
  79376. x_end = header.width;
  79377. y_start = header.height - 1;
  79378. y_step = -1;
  79379. y_end = -1;
  79380. break;
  79381. case TGATools._ORIGIN_UR:
  79382. x_start = header.width - 1;
  79383. x_step = -1;
  79384. x_end = -1;
  79385. y_start = 0;
  79386. y_step = 1;
  79387. y_end = header.height;
  79388. break;
  79389. case TGATools._ORIGIN_BR:
  79390. x_start = header.width - 1;
  79391. x_step = -1;
  79392. x_end = -1;
  79393. y_start = header.height - 1;
  79394. y_step = -1;
  79395. y_end = -1;
  79396. break;
  79397. }
  79398. // Load the specify method
  79399. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  79400. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  79401. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  79402. };
  79403. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79404. var image = pixel_data, colormap = palettes;
  79405. var width = header.width, height = header.height;
  79406. var color, i = 0, x, y;
  79407. var imageData = new Uint8Array(width * height * 4);
  79408. for (y = y_start; y !== y_end; y += y_step) {
  79409. for (x = x_start; x !== x_end; x += x_step, i++) {
  79410. color = image[i];
  79411. imageData[(x + width * y) * 4 + 3] = 255;
  79412. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  79413. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  79414. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  79415. }
  79416. }
  79417. return imageData;
  79418. };
  79419. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79420. var image = pixel_data;
  79421. var width = header.width, height = header.height;
  79422. var color, i = 0, x, y;
  79423. var imageData = new Uint8Array(width * height * 4);
  79424. for (y = y_start; y !== y_end; y += y_step) {
  79425. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  79426. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  79427. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  79428. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  79429. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  79430. imageData[(x + width * y) * 4 + 0] = r;
  79431. imageData[(x + width * y) * 4 + 1] = g;
  79432. imageData[(x + width * y) * 4 + 2] = b;
  79433. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  79434. }
  79435. }
  79436. return imageData;
  79437. };
  79438. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79439. var image = pixel_data;
  79440. var width = header.width, height = header.height;
  79441. var i = 0, x, y;
  79442. var imageData = new Uint8Array(width * height * 4);
  79443. for (y = y_start; y !== y_end; y += y_step) {
  79444. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  79445. imageData[(x + width * y) * 4 + 3] = 255;
  79446. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  79447. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  79448. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  79449. }
  79450. }
  79451. return imageData;
  79452. };
  79453. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79454. var image = pixel_data;
  79455. var width = header.width, height = header.height;
  79456. var i = 0, x, y;
  79457. var imageData = new Uint8Array(width * height * 4);
  79458. for (y = y_start; y !== y_end; y += y_step) {
  79459. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  79460. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  79461. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  79462. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  79463. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  79464. }
  79465. }
  79466. return imageData;
  79467. };
  79468. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79469. var image = pixel_data;
  79470. var width = header.width, height = header.height;
  79471. var color, i = 0, x, y;
  79472. var imageData = new Uint8Array(width * height * 4);
  79473. for (y = y_start; y !== y_end; y += y_step) {
  79474. for (x = x_start; x !== x_end; x += x_step, i++) {
  79475. color = image[i];
  79476. imageData[(x + width * y) * 4 + 0] = color;
  79477. imageData[(x + width * y) * 4 + 1] = color;
  79478. imageData[(x + width * y) * 4 + 2] = color;
  79479. imageData[(x + width * y) * 4 + 3] = 255;
  79480. }
  79481. }
  79482. return imageData;
  79483. };
  79484. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79485. var image = pixel_data;
  79486. var width = header.width, height = header.height;
  79487. var i = 0, x, y;
  79488. var imageData = new Uint8Array(width * height * 4);
  79489. for (y = y_start; y !== y_end; y += y_step) {
  79490. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  79491. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  79492. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  79493. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  79494. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  79495. }
  79496. }
  79497. return imageData;
  79498. };
  79499. //private static _TYPE_NO_DATA = 0;
  79500. TGATools._TYPE_INDEXED = 1;
  79501. TGATools._TYPE_RGB = 2;
  79502. TGATools._TYPE_GREY = 3;
  79503. TGATools._TYPE_RLE_INDEXED = 9;
  79504. TGATools._TYPE_RLE_RGB = 10;
  79505. TGATools._TYPE_RLE_GREY = 11;
  79506. TGATools._ORIGIN_MASK = 0x30;
  79507. TGATools._ORIGIN_SHIFT = 0x04;
  79508. TGATools._ORIGIN_BL = 0x00;
  79509. TGATools._ORIGIN_BR = 0x01;
  79510. TGATools._ORIGIN_UL = 0x02;
  79511. TGATools._ORIGIN_UR = 0x03;
  79512. return TGATools;
  79513. }());
  79514. BABYLON.TGATools = TGATools;
  79515. })(BABYLON || (BABYLON = {}));
  79516. //# sourceMappingURL=babylon.tga.js.map
  79517. "use strict";
  79518. var BABYLON;
  79519. (function (BABYLON) {
  79520. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  79521. // All values and structures referenced from:
  79522. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  79523. var DDS_MAGIC = 0x20534444;
  79524. var
  79525. //DDSD_CAPS = 0x1,
  79526. //DDSD_HEIGHT = 0x2,
  79527. //DDSD_WIDTH = 0x4,
  79528. //DDSD_PITCH = 0x8,
  79529. //DDSD_PIXELFORMAT = 0x1000,
  79530. DDSD_MIPMAPCOUNT = 0x20000;
  79531. //DDSD_LINEARSIZE = 0x80000,
  79532. //DDSD_DEPTH = 0x800000;
  79533. // var DDSCAPS_COMPLEX = 0x8,
  79534. // DDSCAPS_MIPMAP = 0x400000,
  79535. // DDSCAPS_TEXTURE = 0x1000;
  79536. var DDSCAPS2_CUBEMAP = 0x200;
  79537. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  79538. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  79539. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  79540. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  79541. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  79542. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  79543. // DDSCAPS2_VOLUME = 0x200000;
  79544. var
  79545. //DDPF_ALPHAPIXELS = 0x1,
  79546. //DDPF_ALPHA = 0x2,
  79547. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  79548. //DDPF_YUV = 0x200,
  79549. DDPF_LUMINANCE = 0x20000;
  79550. function FourCCToInt32(value) {
  79551. return value.charCodeAt(0) +
  79552. (value.charCodeAt(1) << 8) +
  79553. (value.charCodeAt(2) << 16) +
  79554. (value.charCodeAt(3) << 24);
  79555. }
  79556. function Int32ToFourCC(value) {
  79557. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  79558. }
  79559. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  79560. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  79561. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  79562. var FOURCC_DX10 = FourCCToInt32("DX10");
  79563. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  79564. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  79565. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  79566. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  79567. var headerLengthInt = 31; // The header length in 32 bit ints
  79568. // Offsets into the header array
  79569. var off_magic = 0;
  79570. var off_size = 1;
  79571. var off_flags = 2;
  79572. var off_height = 3;
  79573. var off_width = 4;
  79574. var off_mipmapCount = 7;
  79575. var off_pfFlags = 20;
  79576. var off_pfFourCC = 21;
  79577. var off_RGBbpp = 22;
  79578. var off_RMask = 23;
  79579. var off_GMask = 24;
  79580. var off_BMask = 25;
  79581. var off_AMask = 26;
  79582. // var off_caps1 = 27;
  79583. var off_caps2 = 28;
  79584. // var off_caps3 = 29;
  79585. // var off_caps4 = 30;
  79586. var off_dxgiFormat = 32;
  79587. ;
  79588. var DDSTools = /** @class */ (function () {
  79589. function DDSTools() {
  79590. }
  79591. DDSTools.GetDDSInfo = function (arrayBuffer) {
  79592. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  79593. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  79594. var mipmapCount = 1;
  79595. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  79596. mipmapCount = Math.max(1, header[off_mipmapCount]);
  79597. }
  79598. var fourCC = header[off_pfFourCC];
  79599. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  79600. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79601. switch (fourCC) {
  79602. case FOURCC_D3DFMT_R16G16B16A16F:
  79603. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79604. break;
  79605. case FOURCC_D3DFMT_R32G32B32A32F:
  79606. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79607. break;
  79608. case FOURCC_DX10:
  79609. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  79610. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79611. break;
  79612. }
  79613. }
  79614. return {
  79615. width: header[off_width],
  79616. height: header[off_height],
  79617. mipmapCount: mipmapCount,
  79618. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  79619. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  79620. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  79621. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  79622. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  79623. dxgiFormat: dxgiFormat,
  79624. textureType: textureType
  79625. };
  79626. };
  79627. DDSTools._ToHalfFloat = function (value) {
  79628. if (!DDSTools._FloatView) {
  79629. DDSTools._FloatView = new Float32Array(1);
  79630. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  79631. }
  79632. DDSTools._FloatView[0] = value;
  79633. var x = DDSTools._Int32View[0];
  79634. var bits = (x >> 16) & 0x8000; /* Get the sign */
  79635. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  79636. var e = (x >> 23) & 0xff; /* Using int is faster here */
  79637. /* If zero, or denormal, or exponent underflows too much for a denormal
  79638. * half, return signed zero. */
  79639. if (e < 103) {
  79640. return bits;
  79641. }
  79642. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  79643. if (e > 142) {
  79644. bits |= 0x7c00;
  79645. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  79646. * not Inf, so make sure we set one mantissa bit too. */
  79647. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  79648. return bits;
  79649. }
  79650. /* If exponent underflows but not too much, return a denormal */
  79651. if (e < 113) {
  79652. m |= 0x0800;
  79653. /* Extra rounding may overflow and set mantissa to 0 and exponent
  79654. * to 1, which is OK. */
  79655. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  79656. return bits;
  79657. }
  79658. bits |= ((e - 112) << 10) | (m >> 1);
  79659. bits += m & 1;
  79660. return bits;
  79661. };
  79662. DDSTools._FromHalfFloat = function (value) {
  79663. var s = (value & 0x8000) >> 15;
  79664. var e = (value & 0x7C00) >> 10;
  79665. var f = value & 0x03FF;
  79666. if (e === 0) {
  79667. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  79668. }
  79669. else if (e == 0x1F) {
  79670. return f ? NaN : ((s ? -1 : 1) * Infinity);
  79671. }
  79672. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  79673. };
  79674. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79675. var destArray = new Float32Array(dataLength);
  79676. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  79677. var index = 0;
  79678. for (var y = 0; y < height; y++) {
  79679. for (var x = 0; x < width; x++) {
  79680. var srcPos = (x + y * width) * 4;
  79681. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  79682. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  79683. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  79684. if (DDSTools.StoreLODInAlphaChannel) {
  79685. destArray[index + 3] = lod;
  79686. }
  79687. else {
  79688. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  79689. }
  79690. index += 4;
  79691. }
  79692. }
  79693. return destArray;
  79694. };
  79695. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79696. if (DDSTools.StoreLODInAlphaChannel) {
  79697. var destArray = new Uint16Array(dataLength);
  79698. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  79699. var index = 0;
  79700. for (var y = 0; y < height; y++) {
  79701. for (var x = 0; x < width; x++) {
  79702. var srcPos = (x + y * width) * 4;
  79703. destArray[index] = srcData[srcPos];
  79704. destArray[index + 1] = srcData[srcPos + 1];
  79705. destArray[index + 2] = srcData[srcPos + 2];
  79706. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  79707. index += 4;
  79708. }
  79709. }
  79710. return destArray;
  79711. }
  79712. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  79713. };
  79714. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79715. if (DDSTools.StoreLODInAlphaChannel) {
  79716. var destArray = new Float32Array(dataLength);
  79717. var srcData = new Float32Array(arrayBuffer, dataOffset);
  79718. var index = 0;
  79719. for (var y = 0; y < height; y++) {
  79720. for (var x = 0; x < width; x++) {
  79721. var srcPos = (x + y * width) * 4;
  79722. destArray[index] = srcData[srcPos];
  79723. destArray[index + 1] = srcData[srcPos + 1];
  79724. destArray[index + 2] = srcData[srcPos + 2];
  79725. destArray[index + 3] = lod;
  79726. index += 4;
  79727. }
  79728. }
  79729. return destArray;
  79730. }
  79731. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  79732. };
  79733. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79734. var destArray = new Uint8Array(dataLength);
  79735. var srcData = new Float32Array(arrayBuffer, dataOffset);
  79736. var index = 0;
  79737. for (var y = 0; y < height; y++) {
  79738. for (var x = 0; x < width; x++) {
  79739. var srcPos = (x + y * width) * 4;
  79740. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  79741. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  79742. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  79743. if (DDSTools.StoreLODInAlphaChannel) {
  79744. destArray[index + 3] = lod;
  79745. }
  79746. else {
  79747. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  79748. }
  79749. index += 4;
  79750. }
  79751. }
  79752. return destArray;
  79753. };
  79754. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79755. var destArray = new Uint8Array(dataLength);
  79756. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  79757. var index = 0;
  79758. for (var y = 0; y < height; y++) {
  79759. for (var x = 0; x < width; x++) {
  79760. var srcPos = (x + y * width) * 4;
  79761. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  79762. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  79763. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  79764. if (DDSTools.StoreLODInAlphaChannel) {
  79765. destArray[index + 3] = lod;
  79766. }
  79767. else {
  79768. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  79769. }
  79770. index += 4;
  79771. }
  79772. }
  79773. return destArray;
  79774. };
  79775. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  79776. var byteArray = new Uint8Array(dataLength);
  79777. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  79778. var index = 0;
  79779. for (var y = 0; y < height; y++) {
  79780. for (var x = 0; x < width; x++) {
  79781. var srcPos = (x + y * width) * 4;
  79782. byteArray[index] = srcData[srcPos + rOffset];
  79783. byteArray[index + 1] = srcData[srcPos + gOffset];
  79784. byteArray[index + 2] = srcData[srcPos + bOffset];
  79785. byteArray[index + 3] = srcData[srcPos + aOffset];
  79786. index += 4;
  79787. }
  79788. }
  79789. return byteArray;
  79790. };
  79791. DDSTools._ExtractLongWordOrder = function (value) {
  79792. if (value === 0 || value === 255 || value === -16777216) {
  79793. return 0;
  79794. }
  79795. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  79796. };
  79797. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  79798. var byteArray = new Uint8Array(dataLength);
  79799. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  79800. var index = 0;
  79801. for (var y = 0; y < height; y++) {
  79802. for (var x = 0; x < width; x++) {
  79803. var srcPos = (x + y * width) * 3;
  79804. byteArray[index] = srcData[srcPos + rOffset];
  79805. byteArray[index + 1] = srcData[srcPos + gOffset];
  79806. byteArray[index + 2] = srcData[srcPos + bOffset];
  79807. index += 3;
  79808. }
  79809. }
  79810. return byteArray;
  79811. };
  79812. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  79813. var byteArray = new Uint8Array(dataLength);
  79814. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  79815. var index = 0;
  79816. for (var y = 0; y < height; y++) {
  79817. for (var x = 0; x < width; x++) {
  79818. var srcPos = (x + y * width);
  79819. byteArray[index] = srcData[srcPos];
  79820. index++;
  79821. }
  79822. }
  79823. return byteArray;
  79824. };
  79825. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  79826. if (lodIndex === void 0) { lodIndex = -1; }
  79827. var ext = engine.getCaps().s3tc;
  79828. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  79829. var fourCC, width, height, dataLength = 0, dataOffset;
  79830. var byteArray, mipmapCount, mip;
  79831. var internalFormat = 0;
  79832. var format = 0;
  79833. var blockBytes = 1;
  79834. if (header[off_magic] !== DDS_MAGIC) {
  79835. BABYLON.Tools.Error("Invalid magic number in DDS header");
  79836. return;
  79837. }
  79838. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  79839. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  79840. return;
  79841. }
  79842. if (info.isCompressed && !ext) {
  79843. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  79844. return;
  79845. }
  79846. var bpp = header[off_RGBbpp];
  79847. dataOffset = header[off_size] + 4;
  79848. var computeFormats = false;
  79849. if (info.isFourCC) {
  79850. fourCC = header[off_pfFourCC];
  79851. switch (fourCC) {
  79852. case FOURCC_DXT1:
  79853. blockBytes = 8;
  79854. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  79855. break;
  79856. case FOURCC_DXT3:
  79857. blockBytes = 16;
  79858. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  79859. break;
  79860. case FOURCC_DXT5:
  79861. blockBytes = 16;
  79862. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  79863. break;
  79864. case FOURCC_D3DFMT_R16G16B16A16F:
  79865. computeFormats = true;
  79866. break;
  79867. case FOURCC_D3DFMT_R32G32B32A32F:
  79868. computeFormats = true;
  79869. break;
  79870. case FOURCC_DX10:
  79871. // There is an additionnal header so dataOffset need to be changed
  79872. dataOffset += 5 * 4; // 5 uints
  79873. var supported = false;
  79874. switch (info.dxgiFormat) {
  79875. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  79876. computeFormats = true;
  79877. supported = true;
  79878. break;
  79879. case DXGI_FORMAT_B8G8R8X8_UNORM:
  79880. info.isRGB = true;
  79881. info.isFourCC = false;
  79882. bpp = 32;
  79883. supported = true;
  79884. break;
  79885. }
  79886. if (supported) {
  79887. break;
  79888. }
  79889. default:
  79890. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  79891. return;
  79892. }
  79893. }
  79894. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  79895. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  79896. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  79897. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  79898. if (computeFormats) {
  79899. format = engine._getWebGLTextureType(info.textureType);
  79900. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  79901. }
  79902. mipmapCount = 1;
  79903. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  79904. mipmapCount = Math.max(1, header[off_mipmapCount]);
  79905. }
  79906. for (var face = 0; face < faces; face++) {
  79907. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  79908. width = header[off_width];
  79909. height = header[off_height];
  79910. for (mip = 0; mip < mipmapCount; ++mip) {
  79911. if (lodIndex === -1 || lodIndex === mip) {
  79912. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  79913. var i = (lodIndex === -1) ? mip : 0;
  79914. if (!info.isCompressed && info.isFourCC) {
  79915. dataLength = width * height * 4;
  79916. var floatArray = null;
  79917. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  79918. if (bpp === 128) {
  79919. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79920. }
  79921. else if (bpp === 64) {
  79922. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79923. }
  79924. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79925. format = engine._getWebGLTextureType(info.textureType);
  79926. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  79927. }
  79928. else {
  79929. if (bpp === 128) {
  79930. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79931. }
  79932. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  79933. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79934. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79935. format = engine._getWebGLTextureType(info.textureType);
  79936. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  79937. }
  79938. else {
  79939. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79940. }
  79941. }
  79942. if (floatArray) {
  79943. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  79944. }
  79945. }
  79946. else if (info.isRGB) {
  79947. if (bpp === 24) {
  79948. dataLength = width * height * 3;
  79949. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  79950. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  79951. }
  79952. else {
  79953. dataLength = width * height * 4;
  79954. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  79955. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  79956. }
  79957. }
  79958. else if (info.isLuminance) {
  79959. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  79960. var unpaddedRowSize = width;
  79961. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  79962. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  79963. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  79964. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  79965. }
  79966. else {
  79967. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  79968. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  79969. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  79970. }
  79971. }
  79972. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  79973. width *= 0.5;
  79974. height *= 0.5;
  79975. width = Math.max(1.0, width);
  79976. height = Math.max(1.0, height);
  79977. }
  79978. if (currentFace !== undefined) {
  79979. // Loading a single face
  79980. break;
  79981. }
  79982. }
  79983. };
  79984. DDSTools.StoreLODInAlphaChannel = false;
  79985. return DDSTools;
  79986. }());
  79987. BABYLON.DDSTools = DDSTools;
  79988. })(BABYLON || (BABYLON = {}));
  79989. //# sourceMappingURL=babylon.dds.js.map
  79990. "use strict";
  79991. var BABYLON;
  79992. (function (BABYLON) {
  79993. /**
  79994. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  79995. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  79996. */
  79997. var KhronosTextureContainer = /** @class */ (function () {
  79998. /**
  79999. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  80000. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  80001. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  80002. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  80003. */
  80004. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  80005. this.arrayBuffer = arrayBuffer;
  80006. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  80007. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  80008. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  80009. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  80010. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  80011. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  80012. BABYLON.Tools.Error("texture missing KTX identifier");
  80013. return;
  80014. }
  80015. // load the reset of the header in native 32 bit int
  80016. var header = new Int32Array(this.arrayBuffer, 12, 13);
  80017. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  80018. var oppositeEndianess = header[0] === 0x01020304;
  80019. // read all the header elements in order they exist in the file, without modification (sans endainness)
  80020. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  80021. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  80022. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  80023. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  80024. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  80025. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  80026. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  80027. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  80028. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  80029. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  80030. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  80031. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  80032. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  80033. if (this.glType !== 0) {
  80034. BABYLON.Tools.Error("only compressed formats currently supported");
  80035. return;
  80036. }
  80037. else {
  80038. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  80039. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  80040. }
  80041. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  80042. BABYLON.Tools.Error("only 2D textures currently supported");
  80043. return;
  80044. }
  80045. if (this.numberOfArrayElements !== 0) {
  80046. BABYLON.Tools.Error("texture arrays not currently supported");
  80047. return;
  80048. }
  80049. if (this.numberOfFaces !== facesExpected) {
  80050. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  80051. return;
  80052. }
  80053. // we now have a completely validated file, so could use existence of loadType as success
  80054. // would need to make this more elaborate & adjust checks above to support more than one load type
  80055. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  80056. }
  80057. // not as fast hardware based, but will probably never need to use
  80058. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  80059. return ((val & 0xFF) << 24)
  80060. | ((val & 0xFF00) << 8)
  80061. | ((val >> 8) & 0xFF00)
  80062. | ((val >> 24) & 0xFF);
  80063. };
  80064. /**
  80065. * It is assumed that the texture has already been created & is currently bound
  80066. */
  80067. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  80068. switch (this.loadType) {
  80069. case KhronosTextureContainer.COMPRESSED_2D:
  80070. this._upload2DCompressedLevels(gl, loadMipmaps);
  80071. break;
  80072. case KhronosTextureContainer.TEX_2D:
  80073. case KhronosTextureContainer.COMPRESSED_3D:
  80074. case KhronosTextureContainer.TEX_3D:
  80075. }
  80076. };
  80077. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  80078. // initialize width & height for level 1
  80079. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  80080. var width = this.pixelWidth;
  80081. var height = this.pixelHeight;
  80082. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  80083. for (var level = 0; level < mipmapCount; level++) {
  80084. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  80085. for (var face = 0; face < this.numberOfFaces; face++) {
  80086. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  80087. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  80088. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  80089. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  80090. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  80091. }
  80092. width = Math.max(1.0, width * 0.5);
  80093. height = Math.max(1.0, height * 0.5);
  80094. }
  80095. };
  80096. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  80097. // load types
  80098. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  80099. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  80100. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  80101. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  80102. return KhronosTextureContainer;
  80103. }());
  80104. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  80105. })(BABYLON || (BABYLON = {}));
  80106. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  80107. "use strict";
  80108. var BABYLON;
  80109. (function (BABYLON) {
  80110. var Debug = /** @class */ (function () {
  80111. function Debug() {
  80112. }
  80113. Debug.AxesViewer = /** @class */ (function () {
  80114. function AxesViewer(scene, scaleLines) {
  80115. if (scaleLines === void 0) { scaleLines = 1; }
  80116. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80117. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80118. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80119. this.scaleLines = 1;
  80120. this.scaleLines = scaleLines;
  80121. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  80122. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  80123. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  80124. this._xmesh.renderingGroupId = 2;
  80125. this._ymesh.renderingGroupId = 2;
  80126. this._zmesh.renderingGroupId = 2;
  80127. this._xmesh.material.checkReadyOnlyOnce = true;
  80128. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  80129. this._ymesh.material.checkReadyOnlyOnce = true;
  80130. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  80131. this._zmesh.material.checkReadyOnlyOnce = true;
  80132. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  80133. this.scene = scene;
  80134. }
  80135. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  80136. var scaleLines = this.scaleLines;
  80137. if (this._xmesh) {
  80138. this._xmesh.position.copyFrom(position);
  80139. }
  80140. if (this._ymesh) {
  80141. this._ymesh.position.copyFrom(position);
  80142. }
  80143. if (this._zmesh) {
  80144. this._zmesh.position.copyFrom(position);
  80145. }
  80146. var point2 = this._xline[1];
  80147. point2.x = xaxis.x * scaleLines;
  80148. point2.y = xaxis.y * scaleLines;
  80149. point2.z = xaxis.z * scaleLines;
  80150. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  80151. point2 = this._yline[1];
  80152. point2.x = yaxis.x * scaleLines;
  80153. point2.y = yaxis.y * scaleLines;
  80154. point2.z = yaxis.z * scaleLines;
  80155. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  80156. point2 = this._zline[1];
  80157. point2.x = zaxis.x * scaleLines;
  80158. point2.y = zaxis.y * scaleLines;
  80159. point2.z = zaxis.z * scaleLines;
  80160. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  80161. };
  80162. AxesViewer.prototype.dispose = function () {
  80163. if (this._xmesh) {
  80164. this._xmesh.dispose();
  80165. }
  80166. if (this._ymesh) {
  80167. this._ymesh.dispose();
  80168. }
  80169. if (this._zmesh) {
  80170. this._zmesh.dispose();
  80171. }
  80172. this._xmesh = null;
  80173. this._ymesh = null;
  80174. this._zmesh = null;
  80175. this.scene = null;
  80176. };
  80177. return AxesViewer;
  80178. }());
  80179. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  80180. __extends(BoneAxesViewer, _super);
  80181. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  80182. if (scaleLines === void 0) { scaleLines = 1; }
  80183. var _this = _super.call(this, scene, scaleLines) || this;
  80184. _this.pos = BABYLON.Vector3.Zero();
  80185. _this.xaxis = BABYLON.Vector3.Zero();
  80186. _this.yaxis = BABYLON.Vector3.Zero();
  80187. _this.zaxis = BABYLON.Vector3.Zero();
  80188. _this.mesh = mesh;
  80189. _this.bone = bone;
  80190. return _this;
  80191. }
  80192. BoneAxesViewer.prototype.update = function () {
  80193. if (!this.mesh || !this.bone) {
  80194. return;
  80195. }
  80196. var bone = this.bone;
  80197. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  80198. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  80199. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  80200. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  80201. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  80202. };
  80203. BoneAxesViewer.prototype.dispose = function () {
  80204. if (this.mesh) {
  80205. this.mesh = null;
  80206. this.bone = null;
  80207. _super.prototype.dispose.call(this);
  80208. }
  80209. };
  80210. return BoneAxesViewer;
  80211. }(Debug.AxesViewer));
  80212. Debug.PhysicsViewer = /** @class */ (function () {
  80213. function PhysicsViewer(scene) {
  80214. this._impostors = [];
  80215. this._meshes = [];
  80216. this._numMeshes = 0;
  80217. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  80218. var physicEngine = this._scene.getPhysicsEngine();
  80219. if (physicEngine) {
  80220. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  80221. }
  80222. }
  80223. PhysicsViewer.prototype._updateDebugMeshes = function () {
  80224. var plugin = this._physicsEnginePlugin;
  80225. for (var i = 0; i < this._numMeshes; i++) {
  80226. var impostor = this._impostors[i];
  80227. if (!impostor) {
  80228. continue;
  80229. }
  80230. if (impostor.isDisposed) {
  80231. this.hideImpostor(this._impostors[i--]);
  80232. }
  80233. else {
  80234. var mesh = this._meshes[i];
  80235. if (mesh && plugin) {
  80236. plugin.syncMeshWithImpostor(mesh, impostor);
  80237. }
  80238. }
  80239. }
  80240. };
  80241. PhysicsViewer.prototype.showImpostor = function (impostor) {
  80242. if (!this._scene) {
  80243. return;
  80244. }
  80245. for (var i = 0; i < this._numMeshes; i++) {
  80246. if (this._impostors[i] == impostor) {
  80247. return;
  80248. }
  80249. }
  80250. var debugMesh = this._getDebugMesh(impostor, this._scene);
  80251. if (debugMesh) {
  80252. this._impostors[this._numMeshes] = impostor;
  80253. this._meshes[this._numMeshes] = debugMesh;
  80254. if (this._numMeshes === 0) {
  80255. this._renderFunction = this._updateDebugMeshes.bind(this);
  80256. this._scene.registerBeforeRender(this._renderFunction);
  80257. }
  80258. this._numMeshes++;
  80259. }
  80260. };
  80261. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  80262. if (!impostor || !this._scene) {
  80263. return;
  80264. }
  80265. var removed = false;
  80266. for (var i = 0; i < this._numMeshes; i++) {
  80267. if (this._impostors[i] == impostor) {
  80268. var mesh = this._meshes[i];
  80269. if (!mesh) {
  80270. continue;
  80271. }
  80272. this._scene.removeMesh(mesh);
  80273. mesh.dispose();
  80274. this._numMeshes--;
  80275. if (this._numMeshes > 0) {
  80276. this._meshes[i] = this._meshes[this._numMeshes];
  80277. this._impostors[i] = this._impostors[this._numMeshes];
  80278. this._meshes[this._numMeshes] = null;
  80279. this._impostors[this._numMeshes] = null;
  80280. }
  80281. else {
  80282. this._meshes[0] = null;
  80283. this._impostors[0] = null;
  80284. }
  80285. removed = true;
  80286. break;
  80287. }
  80288. }
  80289. if (removed && this._numMeshes === 0) {
  80290. this._scene.unregisterBeforeRender(this._renderFunction);
  80291. }
  80292. };
  80293. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  80294. if (!this._debugMaterial) {
  80295. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  80296. this._debugMaterial.wireframe = true;
  80297. }
  80298. return this._debugMaterial;
  80299. };
  80300. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  80301. if (!this._debugBoxMesh) {
  80302. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  80303. this._debugBoxMesh.renderingGroupId = 1;
  80304. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  80305. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  80306. scene.removeMesh(this._debugBoxMesh);
  80307. }
  80308. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  80309. };
  80310. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  80311. if (!this._debugSphereMesh) {
  80312. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  80313. this._debugSphereMesh.renderingGroupId = 1;
  80314. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  80315. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  80316. scene.removeMesh(this._debugSphereMesh);
  80317. }
  80318. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  80319. };
  80320. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  80321. var mesh = null;
  80322. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  80323. mesh = this._getDebugBoxMesh(scene);
  80324. impostor.getBoxSizeToRef(mesh.scaling);
  80325. }
  80326. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  80327. mesh = this._getDebugSphereMesh(scene);
  80328. var radius = impostor.getRadius();
  80329. mesh.scaling.x = radius * 2;
  80330. mesh.scaling.y = radius * 2;
  80331. mesh.scaling.z = radius * 2;
  80332. }
  80333. return mesh;
  80334. };
  80335. PhysicsViewer.prototype.dispose = function () {
  80336. for (var i = 0; i < this._numMeshes; i++) {
  80337. this.hideImpostor(this._impostors[i]);
  80338. }
  80339. if (this._debugBoxMesh) {
  80340. this._debugBoxMesh.dispose();
  80341. }
  80342. if (this._debugSphereMesh) {
  80343. this._debugSphereMesh.dispose();
  80344. }
  80345. if (this._debugMaterial) {
  80346. this._debugMaterial.dispose();
  80347. }
  80348. this._impostors.length = 0;
  80349. this._scene = null;
  80350. this._physicsEnginePlugin = null;
  80351. };
  80352. return PhysicsViewer;
  80353. }());
  80354. Debug.SkeletonViewer = /** @class */ (function () {
  80355. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  80356. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  80357. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  80358. this.skeleton = skeleton;
  80359. this.mesh = mesh;
  80360. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  80361. this.renderingGroupId = renderingGroupId;
  80362. this.color = BABYLON.Color3.White();
  80363. this._debugLines = new Array();
  80364. this._isEnabled = false;
  80365. this._scene = scene;
  80366. this.update();
  80367. this._renderFunction = this.update.bind(this);
  80368. }
  80369. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  80370. get: function () {
  80371. return this._isEnabled;
  80372. },
  80373. set: function (value) {
  80374. if (this._isEnabled === value) {
  80375. return;
  80376. }
  80377. this._isEnabled = value;
  80378. if (value) {
  80379. this._scene.registerBeforeRender(this._renderFunction);
  80380. }
  80381. else {
  80382. this._scene.unregisterBeforeRender(this._renderFunction);
  80383. }
  80384. },
  80385. enumerable: true,
  80386. configurable: true
  80387. });
  80388. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  80389. if (x === void 0) { x = 0; }
  80390. if (y === void 0) { y = 0; }
  80391. if (z === void 0) { z = 0; }
  80392. var tmat = BABYLON.Tmp.Matrix[0];
  80393. var parentBone = bone.getParent();
  80394. tmat.copyFrom(bone.getLocalMatrix());
  80395. if (x !== 0 || y !== 0 || z !== 0) {
  80396. var tmat2 = BABYLON.Tmp.Matrix[1];
  80397. BABYLON.Matrix.IdentityToRef(tmat2);
  80398. tmat2.m[12] = x;
  80399. tmat2.m[13] = y;
  80400. tmat2.m[14] = z;
  80401. tmat2.multiplyToRef(tmat, tmat);
  80402. }
  80403. if (parentBone) {
  80404. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  80405. }
  80406. tmat.multiplyToRef(meshMat, tmat);
  80407. position.x = tmat.m[12];
  80408. position.y = tmat.m[13];
  80409. position.z = tmat.m[14];
  80410. };
  80411. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  80412. var len = bones.length;
  80413. var meshPos = this.mesh.position;
  80414. for (var i = 0; i < len; i++) {
  80415. var bone = bones[i];
  80416. var points = this._debugLines[i];
  80417. if (!points) {
  80418. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80419. this._debugLines[i] = points;
  80420. }
  80421. this._getBonePosition(points[0], bone, meshMat);
  80422. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  80423. points[0].subtractInPlace(meshPos);
  80424. points[1].subtractInPlace(meshPos);
  80425. }
  80426. };
  80427. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  80428. var len = bones.length;
  80429. var boneNum = 0;
  80430. var meshPos = this.mesh.position;
  80431. for (var i = len - 1; i >= 0; i--) {
  80432. var childBone = bones[i];
  80433. var parentBone = childBone.getParent();
  80434. if (!parentBone) {
  80435. continue;
  80436. }
  80437. var points = this._debugLines[boneNum];
  80438. if (!points) {
  80439. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80440. this._debugLines[boneNum] = points;
  80441. }
  80442. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  80443. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  80444. points[0].subtractInPlace(meshPos);
  80445. points[1].subtractInPlace(meshPos);
  80446. boneNum++;
  80447. }
  80448. };
  80449. SkeletonViewer.prototype.update = function () {
  80450. if (this.autoUpdateBonesMatrices) {
  80451. this.skeleton.computeAbsoluteTransforms();
  80452. }
  80453. if (this.skeleton.bones[0].length === undefined) {
  80454. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  80455. }
  80456. else {
  80457. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  80458. }
  80459. if (!this._debugMesh) {
  80460. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  80461. this._debugMesh.renderingGroupId = this.renderingGroupId;
  80462. }
  80463. else {
  80464. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  80465. }
  80466. this._debugMesh.position.copyFrom(this.mesh.position);
  80467. this._debugMesh.color = this.color;
  80468. };
  80469. SkeletonViewer.prototype.dispose = function () {
  80470. if (this._debugMesh) {
  80471. this.isEnabled = false;
  80472. this._debugMesh.dispose();
  80473. this._debugMesh = null;
  80474. }
  80475. };
  80476. return SkeletonViewer;
  80477. }());
  80478. return Debug;
  80479. }());
  80480. BABYLON.Debug = Debug;
  80481. })(BABYLON || (BABYLON = {}));
  80482. //# sourceMappingURL=babylon.debugModules.js.map
  80483. "use strict";
  80484. var BABYLON;
  80485. (function (BABYLON) {
  80486. var RayHelper = /** @class */ (function () {
  80487. function RayHelper(ray) {
  80488. this.ray = ray;
  80489. }
  80490. RayHelper.CreateAndShow = function (ray, scene, color) {
  80491. var helper = new RayHelper(ray);
  80492. helper.show(scene, color);
  80493. return helper;
  80494. };
  80495. RayHelper.prototype.show = function (scene, color) {
  80496. if (!this._renderFunction && this.ray) {
  80497. var ray = this.ray;
  80498. this._renderFunction = this._render.bind(this);
  80499. this._scene = scene;
  80500. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  80501. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  80502. if (this._renderFunction) {
  80503. this._scene.registerBeforeRender(this._renderFunction);
  80504. }
  80505. }
  80506. if (color && this._renderLine) {
  80507. this._renderLine.color.copyFrom(color);
  80508. }
  80509. };
  80510. RayHelper.prototype.hide = function () {
  80511. if (this._renderFunction && this._scene) {
  80512. this._scene.unregisterBeforeRender(this._renderFunction);
  80513. this._scene = null;
  80514. this._renderFunction = null;
  80515. if (this._renderLine) {
  80516. this._renderLine.dispose();
  80517. this._renderLine = null;
  80518. }
  80519. this._renderPoints = [];
  80520. }
  80521. };
  80522. RayHelper.prototype._render = function () {
  80523. var ray = this.ray;
  80524. if (!ray) {
  80525. return;
  80526. }
  80527. var point = this._renderPoints[1];
  80528. var len = Math.min(ray.length, 1000000);
  80529. point.copyFrom(ray.direction);
  80530. point.scaleInPlace(len);
  80531. point.addInPlace(ray.origin);
  80532. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  80533. };
  80534. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  80535. this._attachedToMesh = mesh;
  80536. var ray = this.ray;
  80537. if (!ray) {
  80538. return;
  80539. }
  80540. if (!ray.direction) {
  80541. ray.direction = BABYLON.Vector3.Zero();
  80542. }
  80543. if (!ray.origin) {
  80544. ray.origin = BABYLON.Vector3.Zero();
  80545. }
  80546. if (length) {
  80547. ray.length = length;
  80548. }
  80549. if (!meshSpaceOrigin) {
  80550. meshSpaceOrigin = BABYLON.Vector3.Zero();
  80551. }
  80552. if (!meshSpaceDirection) {
  80553. // -1 so that this will work with Mesh.lookAt
  80554. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  80555. }
  80556. if (!this._meshSpaceDirection) {
  80557. this._meshSpaceDirection = meshSpaceDirection.clone();
  80558. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  80559. }
  80560. else {
  80561. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  80562. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  80563. }
  80564. if (!this._updateToMeshFunction) {
  80565. this._updateToMeshFunction = this._updateToMesh.bind(this);
  80566. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  80567. }
  80568. this._updateToMesh();
  80569. };
  80570. RayHelper.prototype.detachFromMesh = function () {
  80571. if (this._attachedToMesh) {
  80572. if (this._updateToMeshFunction) {
  80573. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  80574. }
  80575. this._attachedToMesh = null;
  80576. this._updateToMeshFunction = null;
  80577. }
  80578. };
  80579. RayHelper.prototype._updateToMesh = function () {
  80580. var ray = this.ray;
  80581. if (!this._attachedToMesh || !ray) {
  80582. return;
  80583. }
  80584. if (this._attachedToMesh._isDisposed) {
  80585. this.detachFromMesh();
  80586. return;
  80587. }
  80588. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  80589. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  80590. };
  80591. RayHelper.prototype.dispose = function () {
  80592. this.hide();
  80593. this.detachFromMesh();
  80594. this.ray = null;
  80595. };
  80596. return RayHelper;
  80597. }());
  80598. BABYLON.RayHelper = RayHelper;
  80599. })(BABYLON || (BABYLON = {}));
  80600. //# sourceMappingURL=babylon.rayHelper.js.map
  80601. "use strict";
  80602. var BABYLON;
  80603. (function (BABYLON) {
  80604. // load the inspector using require, if not present in the global namespace.
  80605. var DebugLayer = /** @class */ (function () {
  80606. function DebugLayer(scene) {
  80607. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  80608. this._scene = scene;
  80609. // load inspector using require, if it doesn't exist on the global namespace.
  80610. }
  80611. /** Creates the inspector window. */
  80612. DebugLayer.prototype._createInspector = function (config) {
  80613. if (config === void 0) { config = {}; }
  80614. var popup = config.popup || false;
  80615. var initialTab = config.initialTab || 0;
  80616. var parentElement = config.parentElement || null;
  80617. if (!this._inspector) {
  80618. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  80619. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  80620. } // else nothing to do,; instance is already existing
  80621. };
  80622. DebugLayer.prototype.isVisible = function () {
  80623. if (!this._inspector) {
  80624. return false;
  80625. }
  80626. return true;
  80627. };
  80628. DebugLayer.prototype.hide = function () {
  80629. if (this._inspector) {
  80630. try {
  80631. this._inspector.dispose();
  80632. }
  80633. catch (e) {
  80634. // If the inspector has been removed directly from the inspector tool
  80635. }
  80636. this._inspector = null;
  80637. }
  80638. };
  80639. DebugLayer.prototype.show = function (config) {
  80640. if (config === void 0) { config = {}; }
  80641. if (typeof this.BJSINSPECTOR == 'undefined') {
  80642. // Load inspector and add it to the DOM
  80643. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  80644. }
  80645. else {
  80646. // Otherwise creates the inspector
  80647. this._createInspector(config);
  80648. }
  80649. };
  80650. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  80651. return DebugLayer;
  80652. }());
  80653. BABYLON.DebugLayer = DebugLayer;
  80654. })(BABYLON || (BABYLON = {}));
  80655. //# sourceMappingURL=babylon.debugLayer.js.map
  80656. "use strict";
  80657. var BABYLON;
  80658. (function (BABYLON) {
  80659. var BoundingBoxRenderer = /** @class */ (function () {
  80660. function BoundingBoxRenderer(scene) {
  80661. this.frontColor = new BABYLON.Color3(1, 1, 1);
  80662. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  80663. this.showBackLines = true;
  80664. this.renderList = new BABYLON.SmartArray(32);
  80665. this._vertexBuffers = {};
  80666. this._scene = scene;
  80667. }
  80668. BoundingBoxRenderer.prototype._prepareRessources = function () {
  80669. if (this._colorShader) {
  80670. return;
  80671. }
  80672. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  80673. attributes: [BABYLON.VertexBuffer.PositionKind],
  80674. uniforms: ["world", "viewProjection", "color"]
  80675. });
  80676. var engine = this._scene.getEngine();
  80677. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  80678. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  80679. this._createIndexBuffer();
  80680. };
  80681. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  80682. var engine = this._scene.getEngine();
  80683. 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]);
  80684. };
  80685. BoundingBoxRenderer.prototype._rebuild = function () {
  80686. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80687. if (vb) {
  80688. vb._rebuild();
  80689. }
  80690. this._createIndexBuffer();
  80691. };
  80692. BoundingBoxRenderer.prototype.reset = function () {
  80693. this.renderList.reset();
  80694. };
  80695. BoundingBoxRenderer.prototype.render = function () {
  80696. if (this.renderList.length === 0) {
  80697. return;
  80698. }
  80699. this._prepareRessources();
  80700. if (!this._colorShader.isReady()) {
  80701. return;
  80702. }
  80703. var engine = this._scene.getEngine();
  80704. engine.setDepthWrite(false);
  80705. this._colorShader._preBind();
  80706. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  80707. var boundingBox = this.renderList.data[boundingBoxIndex];
  80708. var min = boundingBox.minimum;
  80709. var max = boundingBox.maximum;
  80710. var diff = max.subtract(min);
  80711. var median = min.add(diff.scale(0.5));
  80712. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  80713. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  80714. .multiply(boundingBox.getWorldMatrix());
  80715. // VBOs
  80716. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  80717. if (this.showBackLines) {
  80718. // Back
  80719. engine.setDepthFunctionToGreaterOrEqual();
  80720. this._scene.resetCachedMaterial();
  80721. this._colorShader.setColor4("color", this.backColor.toColor4());
  80722. this._colorShader.bind(worldMatrix);
  80723. // Draw order
  80724. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  80725. }
  80726. // Front
  80727. engine.setDepthFunctionToLess();
  80728. this._scene.resetCachedMaterial();
  80729. this._colorShader.setColor4("color", this.frontColor.toColor4());
  80730. this._colorShader.bind(worldMatrix);
  80731. // Draw order
  80732. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  80733. }
  80734. this._colorShader.unbind();
  80735. engine.setDepthFunctionToLessOrEqual();
  80736. engine.setDepthWrite(true);
  80737. };
  80738. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  80739. this._prepareRessources();
  80740. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  80741. return;
  80742. }
  80743. var engine = this._scene.getEngine();
  80744. engine.setDepthWrite(false);
  80745. engine.setColorWrite(false);
  80746. this._colorShader._preBind();
  80747. var boundingBox = mesh._boundingInfo.boundingBox;
  80748. var min = boundingBox.minimum;
  80749. var max = boundingBox.maximum;
  80750. var diff = max.subtract(min);
  80751. var median = min.add(diff.scale(0.5));
  80752. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  80753. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  80754. .multiply(boundingBox.getWorldMatrix());
  80755. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  80756. engine.setDepthFunctionToLess();
  80757. this._scene.resetCachedMaterial();
  80758. this._colorShader.bind(worldMatrix);
  80759. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  80760. this._colorShader.unbind();
  80761. engine.setDepthFunctionToLessOrEqual();
  80762. engine.setDepthWrite(true);
  80763. engine.setColorWrite(true);
  80764. };
  80765. BoundingBoxRenderer.prototype.dispose = function () {
  80766. if (!this._colorShader) {
  80767. return;
  80768. }
  80769. this.renderList.dispose();
  80770. this._colorShader.dispose();
  80771. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80772. if (buffer) {
  80773. buffer.dispose();
  80774. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  80775. }
  80776. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  80777. };
  80778. return BoundingBoxRenderer;
  80779. }());
  80780. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  80781. })(BABYLON || (BABYLON = {}));
  80782. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  80783. "use strict";
  80784. var BABYLON;
  80785. (function (BABYLON) {
  80786. var MorphTarget = /** @class */ (function () {
  80787. function MorphTarget(name, influence) {
  80788. if (influence === void 0) { influence = 0; }
  80789. this.name = name;
  80790. this.animations = new Array();
  80791. this._positions = null;
  80792. this._normals = null;
  80793. this._tangents = null;
  80794. this.onInfluenceChanged = new BABYLON.Observable();
  80795. this.influence = influence;
  80796. }
  80797. Object.defineProperty(MorphTarget.prototype, "influence", {
  80798. get: function () {
  80799. return this._influence;
  80800. },
  80801. set: function (influence) {
  80802. if (this._influence === influence) {
  80803. return;
  80804. }
  80805. var previous = this._influence;
  80806. this._influence = influence;
  80807. if (this.onInfluenceChanged.hasObservers) {
  80808. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  80809. }
  80810. },
  80811. enumerable: true,
  80812. configurable: true
  80813. });
  80814. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  80815. get: function () {
  80816. return !!this._positions;
  80817. },
  80818. enumerable: true,
  80819. configurable: true
  80820. });
  80821. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  80822. get: function () {
  80823. return !!this._normals;
  80824. },
  80825. enumerable: true,
  80826. configurable: true
  80827. });
  80828. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  80829. get: function () {
  80830. return !!this._tangents;
  80831. },
  80832. enumerable: true,
  80833. configurable: true
  80834. });
  80835. MorphTarget.prototype.setPositions = function (data) {
  80836. this._positions = data;
  80837. };
  80838. MorphTarget.prototype.getPositions = function () {
  80839. return this._positions;
  80840. };
  80841. MorphTarget.prototype.setNormals = function (data) {
  80842. this._normals = data;
  80843. };
  80844. MorphTarget.prototype.getNormals = function () {
  80845. return this._normals;
  80846. };
  80847. MorphTarget.prototype.setTangents = function (data) {
  80848. this._tangents = data;
  80849. };
  80850. MorphTarget.prototype.getTangents = function () {
  80851. return this._tangents;
  80852. };
  80853. /**
  80854. * Serializes the current target into a Serialization object.
  80855. * Returns the serialized object.
  80856. */
  80857. MorphTarget.prototype.serialize = function () {
  80858. var serializationObject = {};
  80859. serializationObject.name = this.name;
  80860. serializationObject.influence = this.influence;
  80861. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  80862. if (this.hasNormals) {
  80863. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  80864. }
  80865. if (this.hasTangents) {
  80866. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  80867. }
  80868. // Animations
  80869. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  80870. return serializationObject;
  80871. };
  80872. // Statics
  80873. MorphTarget.Parse = function (serializationObject) {
  80874. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  80875. result.setPositions(serializationObject.positions);
  80876. if (serializationObject.normals) {
  80877. result.setNormals(serializationObject.normals);
  80878. }
  80879. if (serializationObject.tangents) {
  80880. result.setTangents(serializationObject.tangents);
  80881. }
  80882. // Animations
  80883. if (serializationObject.animations) {
  80884. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  80885. var parsedAnimation = serializationObject.animations[animationIndex];
  80886. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  80887. }
  80888. }
  80889. return result;
  80890. };
  80891. MorphTarget.FromMesh = function (mesh, name, influence) {
  80892. if (!name) {
  80893. name = mesh.name;
  80894. }
  80895. var result = new MorphTarget(name, influence);
  80896. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  80897. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  80898. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  80899. }
  80900. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  80901. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  80902. }
  80903. return result;
  80904. };
  80905. return MorphTarget;
  80906. }());
  80907. BABYLON.MorphTarget = MorphTarget;
  80908. })(BABYLON || (BABYLON = {}));
  80909. //# sourceMappingURL=babylon.morphTarget.js.map
  80910. "use strict";
  80911. var BABYLON;
  80912. (function (BABYLON) {
  80913. var MorphTargetManager = /** @class */ (function () {
  80914. function MorphTargetManager(scene) {
  80915. if (scene === void 0) { scene = null; }
  80916. this._targets = new Array();
  80917. this._targetObservable = new Array();
  80918. this._activeTargets = new BABYLON.SmartArray(16);
  80919. this._supportsNormals = false;
  80920. this._supportsTangents = false;
  80921. this._vertexCount = 0;
  80922. this._uniqueId = 0;
  80923. this._tempInfluences = new Array();
  80924. if (!scene) {
  80925. scene = BABYLON.Engine.LastCreatedScene;
  80926. }
  80927. this._scene = scene;
  80928. if (this._scene) {
  80929. this._scene.morphTargetManagers.push(this);
  80930. this._uniqueId = this._scene.getUniqueId();
  80931. }
  80932. }
  80933. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  80934. get: function () {
  80935. return this._uniqueId;
  80936. },
  80937. enumerable: true,
  80938. configurable: true
  80939. });
  80940. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  80941. get: function () {
  80942. return this._vertexCount;
  80943. },
  80944. enumerable: true,
  80945. configurable: true
  80946. });
  80947. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  80948. get: function () {
  80949. return this._supportsNormals;
  80950. },
  80951. enumerable: true,
  80952. configurable: true
  80953. });
  80954. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  80955. get: function () {
  80956. return this._supportsTangents;
  80957. },
  80958. enumerable: true,
  80959. configurable: true
  80960. });
  80961. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  80962. get: function () {
  80963. return this._targets.length;
  80964. },
  80965. enumerable: true,
  80966. configurable: true
  80967. });
  80968. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  80969. get: function () {
  80970. return this._activeTargets.length;
  80971. },
  80972. enumerable: true,
  80973. configurable: true
  80974. });
  80975. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  80976. get: function () {
  80977. return this._influences;
  80978. },
  80979. enumerable: true,
  80980. configurable: true
  80981. });
  80982. MorphTargetManager.prototype.getActiveTarget = function (index) {
  80983. return this._activeTargets.data[index];
  80984. };
  80985. MorphTargetManager.prototype.getTarget = function (index) {
  80986. return this._targets[index];
  80987. };
  80988. MorphTargetManager.prototype.addTarget = function (target) {
  80989. var _this = this;
  80990. this._targets.push(target);
  80991. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  80992. _this._syncActiveTargets(needUpdate);
  80993. }));
  80994. this._syncActiveTargets(true);
  80995. };
  80996. MorphTargetManager.prototype.removeTarget = function (target) {
  80997. var index = this._targets.indexOf(target);
  80998. if (index >= 0) {
  80999. this._targets.splice(index, 1);
  81000. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  81001. this._syncActiveTargets(true);
  81002. }
  81003. };
  81004. /**
  81005. * Serializes the current manager into a Serialization object.
  81006. * Returns the serialized object.
  81007. */
  81008. MorphTargetManager.prototype.serialize = function () {
  81009. var serializationObject = {};
  81010. serializationObject.id = this.uniqueId;
  81011. serializationObject.targets = [];
  81012. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  81013. var target = _a[_i];
  81014. serializationObject.targets.push(target.serialize());
  81015. }
  81016. return serializationObject;
  81017. };
  81018. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  81019. var influenceCount = 0;
  81020. this._activeTargets.reset();
  81021. this._supportsNormals = true;
  81022. this._supportsTangents = true;
  81023. this._vertexCount = 0;
  81024. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  81025. var target = _a[_i];
  81026. this._activeTargets.push(target);
  81027. this._tempInfluences[influenceCount++] = target.influence;
  81028. var positions = target.getPositions();
  81029. if (positions) {
  81030. this._supportsNormals = this._supportsNormals && target.hasNormals;
  81031. this._supportsTangents = this._supportsTangents && target.hasTangents;
  81032. var vertexCount = positions.length / 3;
  81033. if (this._vertexCount === 0) {
  81034. this._vertexCount = vertexCount;
  81035. }
  81036. else if (this._vertexCount !== vertexCount) {
  81037. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  81038. return;
  81039. }
  81040. }
  81041. }
  81042. if (!this._influences || this._influences.length !== influenceCount) {
  81043. this._influences = new Float32Array(influenceCount);
  81044. }
  81045. for (var index = 0; index < influenceCount; index++) {
  81046. this._influences[index] = this._tempInfluences[index];
  81047. }
  81048. if (needUpdate && this._scene) {
  81049. // Flag meshes as dirty to resync with the active targets
  81050. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  81051. var mesh = _c[_b];
  81052. if (mesh.morphTargetManager === this) {
  81053. mesh._syncGeometryWithMorphTargetManager();
  81054. }
  81055. }
  81056. }
  81057. };
  81058. // Statics
  81059. MorphTargetManager.Parse = function (serializationObject, scene) {
  81060. var result = new MorphTargetManager(scene);
  81061. result._uniqueId = serializationObject.id;
  81062. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  81063. var targetData = _a[_i];
  81064. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  81065. }
  81066. return result;
  81067. };
  81068. return MorphTargetManager;
  81069. }());
  81070. BABYLON.MorphTargetManager = MorphTargetManager;
  81071. })(BABYLON || (BABYLON = {}));
  81072. //# sourceMappingURL=babylon.morphTargetManager.js.map
  81073. "use strict";
  81074. var BABYLON;
  81075. (function (BABYLON) {
  81076. var Octree = /** @class */ (function () {
  81077. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  81078. if (maxDepth === void 0) { maxDepth = 2; }
  81079. this.maxDepth = maxDepth;
  81080. this.dynamicContent = new Array();
  81081. this._maxBlockCapacity = maxBlockCapacity || 64;
  81082. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  81083. this._creationFunc = creationFunc;
  81084. }
  81085. // Methods
  81086. Octree.prototype.update = function (worldMin, worldMax, entries) {
  81087. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  81088. };
  81089. Octree.prototype.addMesh = function (entry) {
  81090. for (var index = 0; index < this.blocks.length; index++) {
  81091. var block = this.blocks[index];
  81092. block.addEntry(entry);
  81093. }
  81094. };
  81095. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  81096. this._selectionContent.reset();
  81097. for (var index = 0; index < this.blocks.length; index++) {
  81098. var block = this.blocks[index];
  81099. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  81100. }
  81101. if (allowDuplicate) {
  81102. this._selectionContent.concat(this.dynamicContent);
  81103. }
  81104. else {
  81105. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  81106. }
  81107. return this._selectionContent;
  81108. };
  81109. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  81110. this._selectionContent.reset();
  81111. for (var index = 0; index < this.blocks.length; index++) {
  81112. var block = this.blocks[index];
  81113. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  81114. }
  81115. if (allowDuplicate) {
  81116. this._selectionContent.concat(this.dynamicContent);
  81117. }
  81118. else {
  81119. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  81120. }
  81121. return this._selectionContent;
  81122. };
  81123. Octree.prototype.intersectsRay = function (ray) {
  81124. this._selectionContent.reset();
  81125. for (var index = 0; index < this.blocks.length; index++) {
  81126. var block = this.blocks[index];
  81127. block.intersectsRay(ray, this._selectionContent);
  81128. }
  81129. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  81130. return this._selectionContent;
  81131. };
  81132. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  81133. target.blocks = new Array();
  81134. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  81135. // Segmenting space
  81136. for (var x = 0; x < 2; x++) {
  81137. for (var y = 0; y < 2; y++) {
  81138. for (var z = 0; z < 2; z++) {
  81139. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  81140. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  81141. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  81142. block.addEntries(entries);
  81143. target.blocks.push(block);
  81144. }
  81145. }
  81146. }
  81147. };
  81148. Octree.CreationFuncForMeshes = function (entry, block) {
  81149. var boundingInfo = entry.getBoundingInfo();
  81150. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  81151. block.entries.push(entry);
  81152. }
  81153. };
  81154. Octree.CreationFuncForSubMeshes = function (entry, block) {
  81155. var boundingInfo = entry.getBoundingInfo();
  81156. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  81157. block.entries.push(entry);
  81158. }
  81159. };
  81160. return Octree;
  81161. }());
  81162. BABYLON.Octree = Octree;
  81163. })(BABYLON || (BABYLON = {}));
  81164. //# sourceMappingURL=babylon.octree.js.map
  81165. "use strict";
  81166. var BABYLON;
  81167. (function (BABYLON) {
  81168. var OctreeBlock = /** @class */ (function () {
  81169. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  81170. this.entries = new Array();
  81171. this._boundingVectors = new Array();
  81172. this._capacity = capacity;
  81173. this._depth = depth;
  81174. this._maxDepth = maxDepth;
  81175. this._creationFunc = creationFunc;
  81176. this._minPoint = minPoint;
  81177. this._maxPoint = maxPoint;
  81178. this._boundingVectors.push(minPoint.clone());
  81179. this._boundingVectors.push(maxPoint.clone());
  81180. this._boundingVectors.push(minPoint.clone());
  81181. this._boundingVectors[2].x = maxPoint.x;
  81182. this._boundingVectors.push(minPoint.clone());
  81183. this._boundingVectors[3].y = maxPoint.y;
  81184. this._boundingVectors.push(minPoint.clone());
  81185. this._boundingVectors[4].z = maxPoint.z;
  81186. this._boundingVectors.push(maxPoint.clone());
  81187. this._boundingVectors[5].z = minPoint.z;
  81188. this._boundingVectors.push(maxPoint.clone());
  81189. this._boundingVectors[6].x = minPoint.x;
  81190. this._boundingVectors.push(maxPoint.clone());
  81191. this._boundingVectors[7].y = minPoint.y;
  81192. }
  81193. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  81194. // Property
  81195. get: function () {
  81196. return this._capacity;
  81197. },
  81198. enumerable: true,
  81199. configurable: true
  81200. });
  81201. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  81202. get: function () {
  81203. return this._minPoint;
  81204. },
  81205. enumerable: true,
  81206. configurable: true
  81207. });
  81208. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  81209. get: function () {
  81210. return this._maxPoint;
  81211. },
  81212. enumerable: true,
  81213. configurable: true
  81214. });
  81215. // Methods
  81216. OctreeBlock.prototype.addEntry = function (entry) {
  81217. if (this.blocks) {
  81218. for (var index = 0; index < this.blocks.length; index++) {
  81219. var block = this.blocks[index];
  81220. block.addEntry(entry);
  81221. }
  81222. return;
  81223. }
  81224. this._creationFunc(entry, this);
  81225. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  81226. this.createInnerBlocks();
  81227. }
  81228. };
  81229. OctreeBlock.prototype.addEntries = function (entries) {
  81230. for (var index = 0; index < entries.length; index++) {
  81231. var mesh = entries[index];
  81232. this.addEntry(mesh);
  81233. }
  81234. };
  81235. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  81236. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  81237. if (this.blocks) {
  81238. for (var index = 0; index < this.blocks.length; index++) {
  81239. var block = this.blocks[index];
  81240. block.select(frustumPlanes, selection, allowDuplicate);
  81241. }
  81242. return;
  81243. }
  81244. if (allowDuplicate) {
  81245. selection.concat(this.entries);
  81246. }
  81247. else {
  81248. selection.concatWithNoDuplicate(this.entries);
  81249. }
  81250. }
  81251. };
  81252. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  81253. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  81254. if (this.blocks) {
  81255. for (var index = 0; index < this.blocks.length; index++) {
  81256. var block = this.blocks[index];
  81257. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  81258. }
  81259. return;
  81260. }
  81261. if (allowDuplicate) {
  81262. selection.concat(this.entries);
  81263. }
  81264. else {
  81265. selection.concatWithNoDuplicate(this.entries);
  81266. }
  81267. }
  81268. };
  81269. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  81270. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  81271. if (this.blocks) {
  81272. for (var index = 0; index < this.blocks.length; index++) {
  81273. var block = this.blocks[index];
  81274. block.intersectsRay(ray, selection);
  81275. }
  81276. return;
  81277. }
  81278. selection.concatWithNoDuplicate(this.entries);
  81279. }
  81280. };
  81281. OctreeBlock.prototype.createInnerBlocks = function () {
  81282. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  81283. };
  81284. return OctreeBlock;
  81285. }());
  81286. BABYLON.OctreeBlock = OctreeBlock;
  81287. })(BABYLON || (BABYLON = {}));
  81288. //# sourceMappingURL=babylon.octreeBlock.js.map
  81289. "use strict";
  81290. var BABYLON;
  81291. (function (BABYLON) {
  81292. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  81293. __extends(VRDistortionCorrectionPostProcess, _super);
  81294. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  81295. var _this = _super.call(this, name, "vrDistortionCorrection", [
  81296. 'LensCenter',
  81297. 'Scale',
  81298. 'ScaleIn',
  81299. 'HmdWarpParam'
  81300. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  81301. _this._isRightEye = isRightEye;
  81302. _this._distortionFactors = vrMetrics.distortionK;
  81303. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  81304. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  81305. _this.adaptScaleToCurrentViewport = true;
  81306. _this.onSizeChangedObservable.add(function () {
  81307. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  81308. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  81309. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  81310. });
  81311. _this.onApplyObservable.add(function (effect) {
  81312. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  81313. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  81314. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  81315. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  81316. });
  81317. return _this;
  81318. }
  81319. return VRDistortionCorrectionPostProcess;
  81320. }(BABYLON.PostProcess));
  81321. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  81322. })(BABYLON || (BABYLON = {}));
  81323. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  81324. "use strict";
  81325. var BABYLON;
  81326. (function (BABYLON) {
  81327. var AnaglyphPostProcess = /** @class */ (function (_super) {
  81328. __extends(AnaglyphPostProcess, _super);
  81329. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  81330. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  81331. _this._passedProcess = rigCameras[0]._rigPostProcess;
  81332. _this.onApplyObservable.add(function (effect) {
  81333. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  81334. });
  81335. return _this;
  81336. }
  81337. return AnaglyphPostProcess;
  81338. }(BABYLON.PostProcess));
  81339. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  81340. })(BABYLON || (BABYLON = {}));
  81341. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  81342. "use strict";
  81343. var BABYLON;
  81344. (function (BABYLON) {
  81345. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  81346. __extends(StereoscopicInterlacePostProcess, _super);
  81347. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  81348. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  81349. _this._passedProcess = rigCameras[0]._rigPostProcess;
  81350. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  81351. _this.onSizeChangedObservable.add(function () {
  81352. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  81353. });
  81354. _this.onApplyObservable.add(function (effect) {
  81355. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  81356. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  81357. });
  81358. return _this;
  81359. }
  81360. return StereoscopicInterlacePostProcess;
  81361. }(BABYLON.PostProcess));
  81362. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  81363. })(BABYLON || (BABYLON = {}));
  81364. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  81365. "use strict";
  81366. var BABYLON;
  81367. (function (BABYLON) {
  81368. /**
  81369. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  81370. * Screen rotation is taken into account.
  81371. */
  81372. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  81373. function FreeCameraDeviceOrientationInput() {
  81374. var _this = this;
  81375. this._screenOrientationAngle = 0;
  81376. this._screenQuaternion = new BABYLON.Quaternion();
  81377. this._alpha = 0;
  81378. this._beta = 0;
  81379. this._gamma = 0;
  81380. this._orientationChanged = function () {
  81381. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  81382. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  81383. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  81384. };
  81385. this._deviceOrientation = function (evt) {
  81386. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  81387. _this._beta = evt.beta !== null ? evt.beta : 0;
  81388. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  81389. };
  81390. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  81391. this._orientationChanged();
  81392. }
  81393. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  81394. get: function () {
  81395. return this._camera;
  81396. },
  81397. set: function (camera) {
  81398. this._camera = camera;
  81399. if (this._camera != null && !this._camera.rotationQuaternion) {
  81400. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  81401. }
  81402. },
  81403. enumerable: true,
  81404. configurable: true
  81405. });
  81406. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  81407. window.addEventListener("orientationchange", this._orientationChanged);
  81408. window.addEventListener("deviceorientation", this._deviceOrientation);
  81409. //In certain cases, the attach control is called AFTER orientation was changed,
  81410. //So this is needed.
  81411. this._orientationChanged();
  81412. };
  81413. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  81414. window.removeEventListener("orientationchange", this._orientationChanged);
  81415. window.removeEventListener("deviceorientation", this._deviceOrientation);
  81416. };
  81417. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  81418. //if no device orientation provided, don't update the rotation.
  81419. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  81420. if (!this._alpha)
  81421. return;
  81422. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  81423. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  81424. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  81425. //Mirror on XY Plane
  81426. this._camera.rotationQuaternion.z *= -1;
  81427. this._camera.rotationQuaternion.w *= -1;
  81428. };
  81429. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  81430. return "FreeCameraDeviceOrientationInput";
  81431. };
  81432. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  81433. return "deviceOrientation";
  81434. };
  81435. return FreeCameraDeviceOrientationInput;
  81436. }());
  81437. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  81438. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  81439. })(BABYLON || (BABYLON = {}));
  81440. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  81441. "use strict";
  81442. var BABYLON;
  81443. (function (BABYLON) {
  81444. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  81445. function ArcRotateCameraVRDeviceOrientationInput() {
  81446. this.alphaCorrection = 1;
  81447. this.betaCorrection = 1;
  81448. this.gammaCorrection = 1;
  81449. this._alpha = 0;
  81450. this._gamma = 0;
  81451. this._dirty = false;
  81452. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  81453. }
  81454. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  81455. this.camera.attachControl(element, noPreventDefault);
  81456. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  81457. };
  81458. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  81459. if (evt.alpha !== null) {
  81460. this._alpha = +evt.alpha | 0;
  81461. }
  81462. if (evt.gamma !== null) {
  81463. this._gamma = +evt.gamma | 0;
  81464. }
  81465. this._dirty = true;
  81466. };
  81467. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  81468. if (this._dirty) {
  81469. this._dirty = false;
  81470. if (this._gamma < 0) {
  81471. this._gamma = 180 + this._gamma;
  81472. }
  81473. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  81474. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  81475. }
  81476. };
  81477. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  81478. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  81479. };
  81480. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  81481. return "ArcRotateCameraVRDeviceOrientationInput";
  81482. };
  81483. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  81484. return "VRDeviceOrientation";
  81485. };
  81486. return ArcRotateCameraVRDeviceOrientationInput;
  81487. }());
  81488. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  81489. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  81490. })(BABYLON || (BABYLON = {}));
  81491. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  81492. "use strict";
  81493. var BABYLON;
  81494. (function (BABYLON) {
  81495. var VRCameraMetrics = /** @class */ (function () {
  81496. function VRCameraMetrics() {
  81497. this.compensateDistortion = true;
  81498. }
  81499. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  81500. get: function () {
  81501. return this.hResolution / (2 * this.vResolution);
  81502. },
  81503. enumerable: true,
  81504. configurable: true
  81505. });
  81506. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  81507. get: function () {
  81508. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  81509. },
  81510. enumerable: true,
  81511. configurable: true
  81512. });
  81513. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  81514. get: function () {
  81515. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  81516. var h = (4 * meters) / this.hScreenSize;
  81517. return BABYLON.Matrix.Translation(h, 0, 0);
  81518. },
  81519. enumerable: true,
  81520. configurable: true
  81521. });
  81522. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  81523. get: function () {
  81524. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  81525. var h = (4 * meters) / this.hScreenSize;
  81526. return BABYLON.Matrix.Translation(-h, 0, 0);
  81527. },
  81528. enumerable: true,
  81529. configurable: true
  81530. });
  81531. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  81532. get: function () {
  81533. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  81534. },
  81535. enumerable: true,
  81536. configurable: true
  81537. });
  81538. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  81539. get: function () {
  81540. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  81541. },
  81542. enumerable: true,
  81543. configurable: true
  81544. });
  81545. VRCameraMetrics.GetDefault = function () {
  81546. var result = new VRCameraMetrics();
  81547. result.hResolution = 1280;
  81548. result.vResolution = 800;
  81549. result.hScreenSize = 0.149759993;
  81550. result.vScreenSize = 0.0935999975;
  81551. result.vScreenCenter = 0.0467999987;
  81552. result.eyeToScreenDistance = 0.0410000011;
  81553. result.lensSeparationDistance = 0.0635000020;
  81554. result.interpupillaryDistance = 0.0640000030;
  81555. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  81556. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  81557. result.postProcessScaleFactor = 1.714605507808412;
  81558. result.lensCenterOffset = 0.151976421;
  81559. return result;
  81560. };
  81561. return VRCameraMetrics;
  81562. }());
  81563. BABYLON.VRCameraMetrics = VRCameraMetrics;
  81564. })(BABYLON || (BABYLON = {}));
  81565. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  81566. "use strict";
  81567. var BABYLON;
  81568. (function (BABYLON) {
  81569. /**
  81570. * This represents a WebVR camera.
  81571. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  81572. * @example http://doc.babylonjs.com/how_to/webvr_camera
  81573. */
  81574. var WebVRFreeCamera = /** @class */ (function (_super) {
  81575. __extends(WebVRFreeCamera, _super);
  81576. /**
  81577. * Instantiates a WebVRFreeCamera.
  81578. * @param name The name of the WebVRFreeCamera
  81579. * @param position The starting anchor position for the camera
  81580. * @param scene The scene the camera belongs to
  81581. * @param webVROptions a set of customizable options for the webVRCamera
  81582. */
  81583. function WebVRFreeCamera(name, position, scene, webVROptions) {
  81584. if (webVROptions === void 0) { webVROptions = {}; }
  81585. var _this = _super.call(this, name, position, scene) || this;
  81586. _this.webVROptions = webVROptions;
  81587. /**
  81588. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  81589. */
  81590. _this._vrDevice = null;
  81591. /**
  81592. * The rawPose of the vrDevice.
  81593. */
  81594. _this.rawPose = null;
  81595. _this._specsVersion = "1.1";
  81596. _this._attached = false;
  81597. _this._descendants = [];
  81598. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  81599. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  81600. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  81601. _this._standingMatrix = null;
  81602. /**
  81603. * Represents device position in babylon space.
  81604. */
  81605. _this.devicePosition = BABYLON.Vector3.Zero();
  81606. /**
  81607. * Represents device rotation in babylon space.
  81608. */
  81609. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  81610. /**
  81611. * The scale of the device to be used when translating from device space to babylon space.
  81612. */
  81613. _this.deviceScaleFactor = 1;
  81614. _this._deviceToWorld = BABYLON.Matrix.Identity();
  81615. _this._worldToDevice = BABYLON.Matrix.Identity();
  81616. /**
  81617. * References to the webVR controllers for the vrDevice.
  81618. */
  81619. _this.controllers = [];
  81620. /**
  81621. * Emits an event when a controller is attached.
  81622. */
  81623. _this.onControllersAttachedObservable = new BABYLON.Observable();
  81624. /**
  81625. * Emits an event when a controller's mesh has been loaded;
  81626. */
  81627. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  81628. /**
  81629. * If the rig cameras be used as parent instead of this camera.
  81630. */
  81631. _this.rigParenting = true;
  81632. _this._defaultHeight = undefined;
  81633. _this._workingVector = BABYLON.Vector3.Zero();
  81634. _this._oneVector = BABYLON.Vector3.One();
  81635. _this._workingMatrix = BABYLON.Matrix.Identity();
  81636. _this._cache.position = BABYLON.Vector3.Zero();
  81637. if (webVROptions.defaultHeight) {
  81638. _this._defaultHeight = webVROptions.defaultHeight;
  81639. _this.position.y = _this._defaultHeight;
  81640. }
  81641. _this.minZ = 0.1;
  81642. //legacy support - the compensation boolean was removed.
  81643. if (arguments.length === 5) {
  81644. _this.webVROptions = arguments[4];
  81645. }
  81646. // default webVR options
  81647. if (_this.webVROptions.trackPosition == undefined) {
  81648. _this.webVROptions.trackPosition = true;
  81649. }
  81650. if (_this.webVROptions.controllerMeshes == undefined) {
  81651. _this.webVROptions.controllerMeshes = true;
  81652. }
  81653. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  81654. _this.webVROptions.defaultLightingOnControllers = true;
  81655. }
  81656. _this.rotationQuaternion = new BABYLON.Quaternion();
  81657. if (_this.webVROptions && _this.webVROptions.positionScale) {
  81658. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  81659. }
  81660. //enable VR
  81661. var engine = _this.getEngine();
  81662. _this._onVREnabled = function (success) { if (success) {
  81663. _this.initControllers();
  81664. } };
  81665. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  81666. engine.initWebVR().add(function (event) {
  81667. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  81668. return;
  81669. }
  81670. _this._vrDevice = event.vrDisplay;
  81671. //reset the rig parameters.
  81672. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  81673. if (_this._attached) {
  81674. _this.getEngine().enableVR();
  81675. }
  81676. });
  81677. if (typeof (VRFrameData) !== "undefined")
  81678. _this._frameData = new VRFrameData();
  81679. /**
  81680. * The idea behind the following lines:
  81681. * objects that have the camera as parent should actually have the rig cameras as a parent.
  81682. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  81683. * the second will not show it correctly.
  81684. *
  81685. * To solve this - each object that has the camera as parent will be added to a protected array.
  81686. * When the rig camera renders, it will take this array and set all of those to be its children.
  81687. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  81688. * Amazing!
  81689. */
  81690. scene.onBeforeCameraRenderObservable.add(function (camera) {
  81691. if (camera.parent === _this && _this.rigParenting) {
  81692. _this._descendants = _this.getDescendants(true, function (n) {
  81693. // don't take the cameras or the controllers!
  81694. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  81695. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  81696. return !isController && !isRigCamera;
  81697. });
  81698. _this._descendants.forEach(function (node) {
  81699. node.parent = camera;
  81700. });
  81701. }
  81702. });
  81703. scene.onAfterCameraRenderObservable.add(function (camera) {
  81704. if (camera.parent === _this && _this.rigParenting) {
  81705. _this._descendants.forEach(function (node) {
  81706. node.parent = _this;
  81707. });
  81708. }
  81709. });
  81710. return _this;
  81711. }
  81712. /**
  81713. * Gets the device distance from the ground in meters.
  81714. * @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.
  81715. */
  81716. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  81717. if (this._standingMatrix) {
  81718. // Add standing matrix offset to get real offset from ground in room
  81719. this._standingMatrix.getTranslationToRef(this._workingVector);
  81720. return this._deviceRoomPosition.y + this._workingVector.y;
  81721. }
  81722. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  81723. return this._defaultHeight || 0;
  81724. };
  81725. /**
  81726. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  81727. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  81728. */
  81729. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  81730. var _this = this;
  81731. if (callback === void 0) { callback = function (bool) { }; }
  81732. // Use standing matrix if available
  81733. this.getEngine().initWebVRAsync().then(function (result) {
  81734. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  81735. callback(false);
  81736. }
  81737. else {
  81738. _this._standingMatrix = new BABYLON.Matrix();
  81739. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  81740. if (!_this.getScene().useRightHandedSystem) {
  81741. [2, 6, 8, 9, 14].forEach(function (num) {
  81742. if (_this._standingMatrix) {
  81743. _this._standingMatrix.m[num] *= -1;
  81744. }
  81745. });
  81746. }
  81747. callback(true);
  81748. }
  81749. });
  81750. };
  81751. /**
  81752. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  81753. * @returns A promise with a boolean set to if the standing matrix is supported.
  81754. */
  81755. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  81756. var _this = this;
  81757. return new Promise(function (res, rej) {
  81758. _this.useStandingMatrix(function (supported) {
  81759. res(supported);
  81760. });
  81761. });
  81762. };
  81763. /**
  81764. * Disposes the camera
  81765. */
  81766. WebVRFreeCamera.prototype.dispose = function () {
  81767. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  81768. _super.prototype.dispose.call(this);
  81769. };
  81770. /**
  81771. * Gets a vrController by name.
  81772. * @param name The name of the controller to retreive
  81773. * @returns the controller matching the name specified or null if not found
  81774. */
  81775. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  81776. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  81777. var gp = _a[_i];
  81778. if (gp.hand === name) {
  81779. return gp;
  81780. }
  81781. }
  81782. return null;
  81783. };
  81784. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  81785. /**
  81786. * The controller corrisponding to the users left hand.
  81787. */
  81788. get: function () {
  81789. if (!this._leftController) {
  81790. this._leftController = this.getControllerByName("left");
  81791. }
  81792. return this._leftController;
  81793. },
  81794. enumerable: true,
  81795. configurable: true
  81796. });
  81797. ;
  81798. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  81799. /**
  81800. * The controller corrisponding to the users right hand.
  81801. */
  81802. get: function () {
  81803. if (!this._rightController) {
  81804. this._rightController = this.getControllerByName("right");
  81805. }
  81806. return this._rightController;
  81807. },
  81808. enumerable: true,
  81809. configurable: true
  81810. });
  81811. ;
  81812. /**
  81813. * Casts a ray forward from the vrCamera's gaze.
  81814. * @param length Length of the ray (default: 100)
  81815. * @returns the ray corrisponding to the gaze
  81816. */
  81817. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  81818. if (length === void 0) { length = 100; }
  81819. if (this.leftCamera) {
  81820. // Use left eye to avoid computation to compute center on every call
  81821. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  81822. }
  81823. else {
  81824. return _super.prototype.getForwardRay.call(this, length);
  81825. }
  81826. };
  81827. /**
  81828. * Updates the camera based on device's frame data
  81829. */
  81830. WebVRFreeCamera.prototype._checkInputs = function () {
  81831. if (this._vrDevice && this._vrDevice.isPresenting) {
  81832. this._vrDevice.getFrameData(this._frameData);
  81833. this.updateFromDevice(this._frameData.pose);
  81834. }
  81835. _super.prototype._checkInputs.call(this);
  81836. };
  81837. /**
  81838. * Updates the poseControlled values based on the input device pose.
  81839. * @param poseData Pose coming from the device
  81840. */
  81841. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  81842. if (poseData && poseData.orientation) {
  81843. this.rawPose = poseData;
  81844. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  81845. if (this.getScene().useRightHandedSystem) {
  81846. this._deviceRoomRotationQuaternion.z *= -1;
  81847. this._deviceRoomRotationQuaternion.w *= -1;
  81848. }
  81849. if (this.webVROptions.trackPosition && this.rawPose.position) {
  81850. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  81851. if (this.getScene().useRightHandedSystem) {
  81852. this._deviceRoomPosition.z *= -1;
  81853. }
  81854. }
  81855. }
  81856. };
  81857. /**
  81858. * WebVR's attach control will start broadcasting frames to the device.
  81859. * Note that in certain browsers (chrome for example) this function must be called
  81860. * within a user-interaction callback. Example:
  81861. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  81862. *
  81863. * @param element html element to attach the vrDevice to
  81864. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  81865. */
  81866. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  81867. _super.prototype.attachControl.call(this, element, noPreventDefault);
  81868. this._attached = true;
  81869. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  81870. if (this._vrDevice) {
  81871. this.getEngine().enableVR();
  81872. }
  81873. };
  81874. /**
  81875. * Detaches the camera from the html element and disables VR
  81876. *
  81877. * @param element html element to detach from
  81878. */
  81879. WebVRFreeCamera.prototype.detachControl = function (element) {
  81880. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  81881. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  81882. _super.prototype.detachControl.call(this, element);
  81883. this._attached = false;
  81884. this.getEngine().disableVR();
  81885. };
  81886. /**
  81887. * @returns the name of this class
  81888. */
  81889. WebVRFreeCamera.prototype.getClassName = function () {
  81890. return "WebVRFreeCamera";
  81891. };
  81892. /**
  81893. * Calls resetPose on the vrDisplay
  81894. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  81895. */
  81896. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  81897. //uses the vrDisplay's "resetPose()".
  81898. //pitch and roll won't be affected.
  81899. this._vrDevice.resetPose();
  81900. };
  81901. /**
  81902. * Updates the rig cameras (left and right eye)
  81903. */
  81904. WebVRFreeCamera.prototype._updateRigCameras = function () {
  81905. var camLeft = this._rigCameras[0];
  81906. var camRight = this._rigCameras[1];
  81907. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  81908. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  81909. camLeft.position.copyFrom(this._deviceRoomPosition);
  81910. camRight.position.copyFrom(this._deviceRoomPosition);
  81911. };
  81912. /**
  81913. * Updates the cached values of the camera
  81914. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  81915. */
  81916. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  81917. var _this = this;
  81918. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  81919. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  81920. if (!this.updateCacheCalled) {
  81921. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  81922. this.updateCacheCalled = true;
  81923. this.update();
  81924. }
  81925. // Set working vector to the device position in room space rotated by the new rotation
  81926. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  81927. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  81928. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  81929. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  81930. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  81931. // Add translation from anchor position
  81932. this._deviceToWorld.getTranslationToRef(this._workingVector);
  81933. this._workingVector.addInPlace(this.position);
  81934. this._workingVector.subtractInPlace(this._cache.position);
  81935. this._deviceToWorld.setTranslation(this._workingVector);
  81936. // Set an inverted matrix to be used when updating the camera
  81937. this._deviceToWorld.invertToRef(this._worldToDevice);
  81938. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  81939. this.controllers.forEach(function (controller) {
  81940. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  81941. controller.update();
  81942. });
  81943. }
  81944. if (!ignoreParentClass) {
  81945. _super.prototype._updateCache.call(this);
  81946. }
  81947. this.updateCacheCalled = false;
  81948. };
  81949. /**
  81950. * Updates the current device position and rotation in the babylon world
  81951. */
  81952. WebVRFreeCamera.prototype.update = function () {
  81953. // Get current device position in babylon world
  81954. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  81955. // Get current device rotation in babylon world
  81956. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  81957. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  81958. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  81959. _super.prototype.update.call(this);
  81960. };
  81961. /**
  81962. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  81963. * @returns an identity matrix
  81964. */
  81965. WebVRFreeCamera.prototype._getViewMatrix = function () {
  81966. return BABYLON.Matrix.Identity();
  81967. };
  81968. /**
  81969. * This function is called by the two RIG cameras.
  81970. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  81971. */
  81972. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  81973. var _this = this;
  81974. // Update the parent camera prior to using a child camera to avoid desynchronization
  81975. var parentCamera = this._cameraRigParams["parentCamera"];
  81976. parentCamera._updateCache();
  81977. //WebVR 1.1
  81978. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  81979. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  81980. if (!this.getScene().useRightHandedSystem) {
  81981. [2, 6, 8, 9, 14].forEach(function (num) {
  81982. _this._webvrViewMatrix.m[num] *= -1;
  81983. });
  81984. }
  81985. // update the camera rotation matrix
  81986. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  81987. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  81988. // Computing target and final matrix
  81989. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  81990. // should the view matrix be updated with scale and position offset?
  81991. if (parentCamera.deviceScaleFactor !== 1) {
  81992. this._webvrViewMatrix.invert();
  81993. // scale the position, if set
  81994. if (parentCamera.deviceScaleFactor) {
  81995. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  81996. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  81997. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  81998. }
  81999. this._webvrViewMatrix.invert();
  82000. }
  82001. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  82002. return this._webvrViewMatrix;
  82003. };
  82004. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  82005. var _this = this;
  82006. var parentCamera = this.parent;
  82007. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  82008. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  82009. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  82010. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  82011. //babylon compatible matrix
  82012. if (!this.getScene().useRightHandedSystem) {
  82013. [8, 9, 10, 11].forEach(function (num) {
  82014. _this._projectionMatrix.m[num] *= -1;
  82015. });
  82016. }
  82017. return this._projectionMatrix;
  82018. };
  82019. /**
  82020. * Initializes the controllers and their meshes
  82021. */
  82022. WebVRFreeCamera.prototype.initControllers = function () {
  82023. var _this = this;
  82024. this.controllers = [];
  82025. var manager = this.getScene().gamepadManager;
  82026. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  82027. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  82028. var webVrController = gamepad;
  82029. if (webVrController.defaultModel) {
  82030. webVrController.defaultModel.setEnabled(false);
  82031. }
  82032. if (webVrController.hand === "right") {
  82033. _this._rightController = null;
  82034. }
  82035. if (webVrController.hand === "left") {
  82036. _this._leftController = null;
  82037. }
  82038. var controllerIndex = _this.controllers.indexOf(webVrController);
  82039. if (controllerIndex !== -1) {
  82040. _this.controllers.splice(controllerIndex, 1);
  82041. }
  82042. }
  82043. });
  82044. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  82045. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  82046. var webVrController_1 = gamepad;
  82047. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  82048. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  82049. if (_this.webVROptions.controllerMeshes) {
  82050. if (webVrController_1.defaultModel) {
  82051. webVrController_1.defaultModel.setEnabled(true);
  82052. }
  82053. else {
  82054. // Load the meshes
  82055. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  82056. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  82057. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  82058. if (_this.webVROptions.defaultLightingOnControllers) {
  82059. if (!_this._lightOnControllers) {
  82060. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  82061. }
  82062. var activateLightOnSubMeshes_1 = function (mesh, light) {
  82063. var children = mesh.getChildren();
  82064. if (children.length !== 0) {
  82065. children.forEach(function (mesh) {
  82066. light.includedOnlyMeshes.push(mesh);
  82067. activateLightOnSubMeshes_1(mesh, light);
  82068. });
  82069. }
  82070. };
  82071. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  82072. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  82073. }
  82074. });
  82075. }
  82076. }
  82077. webVrController_1.attachToPoseControlledCamera(_this);
  82078. // since this is async - sanity check. Is the controller already stored?
  82079. if (_this.controllers.indexOf(webVrController_1) === -1) {
  82080. //add to the controllers array
  82081. _this.controllers.push(webVrController_1);
  82082. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  82083. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  82084. // So we're overriding setting left & right manually to be sure
  82085. var firstViveWandDetected = false;
  82086. for (var i = 0; i < _this.controllers.length; i++) {
  82087. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  82088. if (!firstViveWandDetected) {
  82089. firstViveWandDetected = true;
  82090. _this.controllers[i].hand = "left";
  82091. }
  82092. else {
  82093. _this.controllers[i].hand = "right";
  82094. }
  82095. }
  82096. }
  82097. //did we find enough controllers? Great! let the developer know.
  82098. if (_this.controllers.length >= 2) {
  82099. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  82100. }
  82101. }
  82102. }
  82103. });
  82104. };
  82105. return WebVRFreeCamera;
  82106. }(BABYLON.FreeCamera));
  82107. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  82108. })(BABYLON || (BABYLON = {}));
  82109. //# sourceMappingURL=babylon.webVRCamera.js.map
  82110. "use strict";
  82111. var BABYLON;
  82112. (function (BABYLON) {
  82113. // We're mainly based on the logic defined into the FreeCamera code
  82114. /**
  82115. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  82116. * being tilted forward or back and left or right.
  82117. */
  82118. var DeviceOrientationCamera = /** @class */ (function (_super) {
  82119. __extends(DeviceOrientationCamera, _super);
  82120. /**
  82121. * Creates a new device orientation camera
  82122. * @param name The name of the camera
  82123. * @param position The start position camera
  82124. * @param scene The scene the camera belongs to
  82125. */
  82126. function DeviceOrientationCamera(name, position, scene) {
  82127. var _this = _super.call(this, name, position, scene) || this;
  82128. _this._quaternionCache = new BABYLON.Quaternion();
  82129. _this.inputs.addDeviceOrientation();
  82130. return _this;
  82131. }
  82132. /**
  82133. * Gets the current instance class name ("DeviceOrientationCamera").
  82134. * This helps avoiding instanceof at run time.
  82135. * @returns the class name
  82136. */
  82137. DeviceOrientationCamera.prototype.getClassName = function () {
  82138. return "DeviceOrientationCamera";
  82139. };
  82140. /**
  82141. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  82142. */
  82143. DeviceOrientationCamera.prototype._checkInputs = function () {
  82144. _super.prototype._checkInputs.call(this);
  82145. this._quaternionCache.copyFrom(this.rotationQuaternion);
  82146. if (this._initialQuaternion) {
  82147. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  82148. }
  82149. };
  82150. /**
  82151. * Reset the camera to its default orientation on the specified axis only.
  82152. * @param axis The axis to reset
  82153. */
  82154. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  82155. var _this = this;
  82156. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  82157. //can only work if this camera has a rotation quaternion already.
  82158. if (!this.rotationQuaternion)
  82159. return;
  82160. if (!this._initialQuaternion) {
  82161. this._initialQuaternion = new BABYLON.Quaternion();
  82162. }
  82163. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  82164. ['x', 'y', 'z'].forEach(function (axisName) {
  82165. if (!axis[axisName]) {
  82166. _this._initialQuaternion[axisName] = 0;
  82167. }
  82168. else {
  82169. _this._initialQuaternion[axisName] *= -1;
  82170. }
  82171. });
  82172. this._initialQuaternion.normalize();
  82173. //force rotation update
  82174. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  82175. };
  82176. return DeviceOrientationCamera;
  82177. }(BABYLON.FreeCamera));
  82178. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  82179. })(BABYLON || (BABYLON = {}));
  82180. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  82181. "use strict";
  82182. var BABYLON;
  82183. (function (BABYLON) {
  82184. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  82185. __extends(VRDeviceOrientationFreeCamera, _super);
  82186. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  82187. if (compensateDistortion === void 0) { compensateDistortion = true; }
  82188. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  82189. var _this = _super.call(this, name, position, scene) || this;
  82190. vrCameraMetrics.compensateDistortion = compensateDistortion;
  82191. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  82192. return _this;
  82193. }
  82194. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  82195. return "VRDeviceOrientationFreeCamera";
  82196. };
  82197. return VRDeviceOrientationFreeCamera;
  82198. }(BABYLON.DeviceOrientationCamera));
  82199. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  82200. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  82201. __extends(VRDeviceOrientationGamepadCamera, _super);
  82202. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  82203. if (compensateDistortion === void 0) { compensateDistortion = true; }
  82204. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  82205. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  82206. _this.inputs.addGamepad();
  82207. return _this;
  82208. }
  82209. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  82210. return "VRDeviceOrientationGamepadCamera";
  82211. };
  82212. return VRDeviceOrientationGamepadCamera;
  82213. }(VRDeviceOrientationFreeCamera));
  82214. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  82215. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  82216. __extends(VRDeviceOrientationArcRotateCamera, _super);
  82217. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  82218. if (compensateDistortion === void 0) { compensateDistortion = true; }
  82219. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  82220. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  82221. vrCameraMetrics.compensateDistortion = compensateDistortion;
  82222. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  82223. _this.inputs.addVRDeviceOrientation();
  82224. return _this;
  82225. }
  82226. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  82227. return "VRDeviceOrientationArcRotateCamera";
  82228. };
  82229. return VRDeviceOrientationArcRotateCamera;
  82230. }(BABYLON.ArcRotateCamera));
  82231. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  82232. })(BABYLON || (BABYLON = {}));
  82233. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  82234. "use strict";
  82235. var BABYLON;
  82236. (function (BABYLON) {
  82237. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  82238. __extends(AnaglyphFreeCamera, _super);
  82239. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  82240. var _this = _super.call(this, name, position, scene) || this;
  82241. _this.interaxialDistance = interaxialDistance;
  82242. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82243. return _this;
  82244. }
  82245. AnaglyphFreeCamera.prototype.getClassName = function () {
  82246. return "AnaglyphFreeCamera";
  82247. };
  82248. return AnaglyphFreeCamera;
  82249. }(BABYLON.FreeCamera));
  82250. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  82251. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  82252. __extends(AnaglyphArcRotateCamera, _super);
  82253. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  82254. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  82255. _this.interaxialDistance = interaxialDistance;
  82256. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82257. return _this;
  82258. }
  82259. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  82260. return "AnaglyphArcRotateCamera";
  82261. };
  82262. return AnaglyphArcRotateCamera;
  82263. }(BABYLON.ArcRotateCamera));
  82264. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  82265. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  82266. __extends(AnaglyphGamepadCamera, _super);
  82267. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  82268. var _this = _super.call(this, name, position, scene) || this;
  82269. _this.interaxialDistance = interaxialDistance;
  82270. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82271. return _this;
  82272. }
  82273. AnaglyphGamepadCamera.prototype.getClassName = function () {
  82274. return "AnaglyphGamepadCamera";
  82275. };
  82276. return AnaglyphGamepadCamera;
  82277. }(BABYLON.GamepadCamera));
  82278. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  82279. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  82280. __extends(AnaglyphUniversalCamera, _super);
  82281. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  82282. var _this = _super.call(this, name, position, scene) || this;
  82283. _this.interaxialDistance = interaxialDistance;
  82284. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82285. return _this;
  82286. }
  82287. AnaglyphUniversalCamera.prototype.getClassName = function () {
  82288. return "AnaglyphUniversalCamera";
  82289. };
  82290. return AnaglyphUniversalCamera;
  82291. }(BABYLON.UniversalCamera));
  82292. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  82293. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  82294. __extends(StereoscopicFreeCamera, _super);
  82295. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82296. var _this = _super.call(this, name, position, scene) || this;
  82297. _this.interaxialDistance = interaxialDistance;
  82298. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82299. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82300. return _this;
  82301. }
  82302. StereoscopicFreeCamera.prototype.getClassName = function () {
  82303. return "StereoscopicFreeCamera";
  82304. };
  82305. return StereoscopicFreeCamera;
  82306. }(BABYLON.FreeCamera));
  82307. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  82308. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  82309. __extends(StereoscopicArcRotateCamera, _super);
  82310. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  82311. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  82312. _this.interaxialDistance = interaxialDistance;
  82313. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82314. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82315. return _this;
  82316. }
  82317. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  82318. return "StereoscopicArcRotateCamera";
  82319. };
  82320. return StereoscopicArcRotateCamera;
  82321. }(BABYLON.ArcRotateCamera));
  82322. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  82323. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  82324. __extends(StereoscopicGamepadCamera, _super);
  82325. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82326. var _this = _super.call(this, name, position, scene) || this;
  82327. _this.interaxialDistance = interaxialDistance;
  82328. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82329. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82330. return _this;
  82331. }
  82332. StereoscopicGamepadCamera.prototype.getClassName = function () {
  82333. return "StereoscopicGamepadCamera";
  82334. };
  82335. return StereoscopicGamepadCamera;
  82336. }(BABYLON.GamepadCamera));
  82337. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  82338. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  82339. __extends(StereoscopicUniversalCamera, _super);
  82340. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82341. var _this = _super.call(this, name, position, scene) || this;
  82342. _this.interaxialDistance = interaxialDistance;
  82343. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82344. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82345. return _this;
  82346. }
  82347. StereoscopicUniversalCamera.prototype.getClassName = function () {
  82348. return "StereoscopicUniversalCamera";
  82349. };
  82350. return StereoscopicUniversalCamera;
  82351. }(BABYLON.UniversalCamera));
  82352. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  82353. })(BABYLON || (BABYLON = {}));
  82354. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  82355. "use strict";
  82356. var BABYLON;
  82357. (function (BABYLON) {
  82358. var VRExperienceHelperGazer = /** @class */ (function () {
  82359. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  82360. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  82361. this.scene = scene;
  82362. this._pointerDownOnMeshAsked = false;
  82363. this._isActionableMesh = false;
  82364. this._teleportationRequestInitiated = false;
  82365. this._teleportationBackRequestInitiated = false;
  82366. this._dpadPressed = true;
  82367. this._activePointer = false;
  82368. this._id = VRExperienceHelperGazer._idCounter++;
  82369. // Gaze tracker
  82370. if (!gazeTrackerToClone) {
  82371. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  82372. this._gazeTracker.bakeCurrentTransformIntoVertices();
  82373. this._gazeTracker.isPickable = false;
  82374. this._gazeTracker.isVisible = false;
  82375. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  82376. targetMat.specularColor = BABYLON.Color3.Black();
  82377. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  82378. targetMat.backFaceCulling = false;
  82379. this._gazeTracker.material = targetMat;
  82380. }
  82381. else {
  82382. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  82383. }
  82384. }
  82385. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  82386. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  82387. };
  82388. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  82389. this._pointerDownOnMeshAsked = true;
  82390. if (this._currentMeshSelected && this._currentHit) {
  82391. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  82392. }
  82393. };
  82394. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  82395. if (this._currentMeshSelected && this._currentHit) {
  82396. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  82397. }
  82398. this._pointerDownOnMeshAsked = false;
  82399. };
  82400. VRExperienceHelperGazer.prototype._activatePointer = function () {
  82401. this._activePointer = true;
  82402. };
  82403. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  82404. this._activePointer = false;
  82405. };
  82406. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  82407. };
  82408. VRExperienceHelperGazer.prototype.dispose = function () {
  82409. this._interactionsEnabled = false;
  82410. this._teleportationEnabled = false;
  82411. };
  82412. VRExperienceHelperGazer._idCounter = 0;
  82413. return VRExperienceHelperGazer;
  82414. }());
  82415. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  82416. __extends(VRExperienceHelperControllerGazer, _super);
  82417. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  82418. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  82419. _this.webVRController = webVRController;
  82420. // Laser pointer
  82421. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  82422. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  82423. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  82424. laserPointerMaterial.alpha = 0.6;
  82425. _this._laserPointer.material = laserPointerMaterial;
  82426. _this._laserPointer.rotation.x = Math.PI / 2;
  82427. _this._laserPointer.position.z = -0.5;
  82428. _this._laserPointer.isVisible = false;
  82429. if (!webVRController.mesh) {
  82430. // Create an empty mesh that is used prior to loading the high quality model
  82431. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  82432. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  82433. preloadPointerPose.rotation.x = -0.7;
  82434. preloadMesh.addChild(preloadPointerPose);
  82435. webVRController.attachToMesh(preloadMesh);
  82436. }
  82437. _this._setLaserPointerParent(webVRController.mesh);
  82438. return _this;
  82439. }
  82440. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  82441. return this.webVRController.getForwardRay(length);
  82442. };
  82443. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  82444. _super.prototype._activatePointer.call(this);
  82445. this._laserPointer.isVisible = true;
  82446. };
  82447. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  82448. _super.prototype._deactivatePointer.call(this);
  82449. this._laserPointer.isVisible = false;
  82450. };
  82451. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  82452. this._laserPointer.material.emissiveColor = color;
  82453. };
  82454. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  82455. var makeNotPick = function (root) {
  82456. root.name += " laserPointer";
  82457. root.getChildMeshes().forEach(function (c) {
  82458. makeNotPick(c);
  82459. });
  82460. };
  82461. makeNotPick(mesh);
  82462. var childMeshes = mesh.getChildMeshes();
  82463. this.webVRController._pointingPoseNode = null;
  82464. for (var i = 0; i < childMeshes.length; i++) {
  82465. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  82466. mesh = childMeshes[i];
  82467. this.webVRController._pointingPoseNode = mesh;
  82468. break;
  82469. }
  82470. }
  82471. this._laserPointer.parent = mesh;
  82472. };
  82473. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  82474. this._laserPointer.scaling.y = distance;
  82475. this._laserPointer.position.z = -distance / 2;
  82476. };
  82477. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  82478. _super.prototype.dispose.call(this);
  82479. this._laserPointer.dispose();
  82480. };
  82481. return VRExperienceHelperControllerGazer;
  82482. }(VRExperienceHelperGazer));
  82483. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  82484. __extends(VRExperienceHelperCameraGazer, _super);
  82485. function VRExperienceHelperCameraGazer(getCamera, scene) {
  82486. var _this = _super.call(this, scene) || this;
  82487. _this.getCamera = getCamera;
  82488. return _this;
  82489. }
  82490. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  82491. var camera = this.getCamera();
  82492. if (camera) {
  82493. return camera.getForwardRay(length);
  82494. }
  82495. else {
  82496. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  82497. }
  82498. };
  82499. return VRExperienceHelperCameraGazer;
  82500. }(VRExperienceHelperGazer));
  82501. /**
  82502. * Helps to quickly add VR support to an existing scene.
  82503. * See http://doc.babylonjs.com/how_to/webvr_helper
  82504. */
  82505. var VRExperienceHelper = /** @class */ (function () {
  82506. /**
  82507. * Instantiates a VRExperienceHelper.
  82508. * Helps to quickly add VR support to an existing scene.
  82509. * @param scene The scene the VRExperienceHelper belongs to.
  82510. * @param webVROptions Options to modify the vr experience helper's behavior.
  82511. */
  82512. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  82513. if (webVROptions === void 0) { webVROptions = {}; }
  82514. var _this = this;
  82515. this.webVROptions = webVROptions;
  82516. // Can the system support WebVR, even if a headset isn't plugged in?
  82517. this._webVRsupported = false;
  82518. // If WebVR is supported, is a headset plugged in and are we ready to present?
  82519. this._webVRready = false;
  82520. // Are we waiting for the requestPresent callback to complete?
  82521. this._webVRrequesting = false;
  82522. // Are we presenting to the headset right now?
  82523. this._webVRpresenting = false;
  82524. // Are we presenting in the fullscreen fallback?
  82525. this._fullscreenVRpresenting = false;
  82526. /**
  82527. * Observable raised when entering VR.
  82528. */
  82529. this.onEnteringVRObservable = new BABYLON.Observable();
  82530. /**
  82531. * Observable raised when exiting VR.
  82532. */
  82533. this.onExitingVRObservable = new BABYLON.Observable();
  82534. /**
  82535. * Observable raised when controller mesh is loaded.
  82536. */
  82537. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  82538. this._useCustomVRButton = false;
  82539. this._teleportationRequested = false;
  82540. this._teleportActive = false;
  82541. this._floorMeshesCollection = [];
  82542. this._rotationAllowed = true;
  82543. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  82544. this._rotationRightAsked = false;
  82545. this._rotationLeftAsked = false;
  82546. this._isDefaultTeleportationTarget = true;
  82547. this._teleportationFillColor = "#444444";
  82548. this._teleportationBorderColor = "#FFFFFF";
  82549. this._rotationAngle = 0;
  82550. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  82551. this._padSensibilityUp = 0.65;
  82552. this._padSensibilityDown = 0.35;
  82553. this.leftController = null;
  82554. this.rightController = null;
  82555. /**
  82556. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  82557. */
  82558. this.onNewMeshSelected = new BABYLON.Observable();
  82559. /**
  82560. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  82561. */
  82562. this.onNewMeshPicked = new BABYLON.Observable();
  82563. /**
  82564. * Observable raised before camera teleportation
  82565. */
  82566. this.onBeforeCameraTeleport = new BABYLON.Observable();
  82567. /**
  82568. * Observable raised after camera teleportation
  82569. */
  82570. this.onAfterCameraTeleport = new BABYLON.Observable();
  82571. /**
  82572. * Observable raised when current selected mesh gets unselected
  82573. */
  82574. this.onSelectedMeshUnselected = new BABYLON.Observable();
  82575. /**
  82576. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  82577. */
  82578. this.teleportationEnabled = true;
  82579. this._teleportationInitialized = false;
  82580. this._interactionsEnabled = false;
  82581. this._interactionsRequested = false;
  82582. this._displayGaze = true;
  82583. this._displayLaserPointer = true;
  82584. this._onResize = function () {
  82585. _this.moveButtonToBottomRight();
  82586. if (_this._fullscreenVRpresenting && _this._webVRready) {
  82587. _this.exitVR();
  82588. }
  82589. };
  82590. this._onFullscreenChange = function () {
  82591. if (document.fullscreen !== undefined) {
  82592. _this._fullscreenVRpresenting = document.fullscreen;
  82593. }
  82594. else if (document.mozFullScreen !== undefined) {
  82595. _this._fullscreenVRpresenting = document.mozFullScreen;
  82596. }
  82597. else if (document.webkitIsFullScreen !== undefined) {
  82598. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  82599. }
  82600. else if (document.msIsFullScreen !== undefined) {
  82601. _this._fullscreenVRpresenting = document.msIsFullScreen;
  82602. }
  82603. if (!_this._fullscreenVRpresenting && _this._canvas) {
  82604. _this.exitVR();
  82605. if (!_this._useCustomVRButton) {
  82606. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  82607. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  82608. }
  82609. }
  82610. };
  82611. this.beforeRender = function () {
  82612. if (_this.leftController && _this.leftController._activePointer) {
  82613. _this._castRayAndSelectObject(_this.leftController);
  82614. }
  82615. if (_this.rightController && _this.rightController._activePointer) {
  82616. _this._castRayAndSelectObject(_this.rightController);
  82617. }
  82618. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  82619. _this._castRayAndSelectObject(_this._cameraGazer);
  82620. }
  82621. else {
  82622. _this._cameraGazer._gazeTracker.isVisible = false;
  82623. }
  82624. };
  82625. this._onNewGamepadConnected = function (gamepad) {
  82626. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  82627. if (gamepad.leftStick) {
  82628. gamepad.onleftstickchanged(function (stickValues) {
  82629. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  82630. // Listening to classic/xbox gamepad only if no VR controller is active
  82631. if ((!_this.leftController && !_this.rightController) ||
  82632. ((_this.leftController && !_this.leftController._activePointer) &&
  82633. (_this.rightController && !_this.rightController._activePointer))) {
  82634. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  82635. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  82636. }
  82637. }
  82638. });
  82639. }
  82640. if (gamepad.rightStick) {
  82641. gamepad.onrightstickchanged(function (stickValues) {
  82642. if (_this._teleportationInitialized) {
  82643. _this._checkRotate(stickValues, _this._cameraGazer);
  82644. }
  82645. });
  82646. }
  82647. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  82648. gamepad.onbuttondown(function (buttonPressed) {
  82649. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  82650. _this._cameraGazer._selectionPointerDown();
  82651. }
  82652. });
  82653. gamepad.onbuttonup(function (buttonPressed) {
  82654. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  82655. _this._cameraGazer._selectionPointerUp();
  82656. }
  82657. });
  82658. }
  82659. }
  82660. else {
  82661. var webVRController = gamepad;
  82662. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  82663. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  82664. _this.rightController = controller;
  82665. }
  82666. else {
  82667. _this.leftController = controller;
  82668. }
  82669. _this._tryEnableInteractionOnController(controller);
  82670. }
  82671. };
  82672. // 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
  82673. this._tryEnableInteractionOnController = function (controller) {
  82674. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  82675. _this._enableInteractionOnController(controller);
  82676. }
  82677. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  82678. _this._enableTeleportationOnController(controller);
  82679. }
  82680. };
  82681. this._onNewGamepadDisconnected = function (gamepad) {
  82682. if (gamepad instanceof BABYLON.WebVRController) {
  82683. if (gamepad.hand === "left" && _this.leftController != null) {
  82684. _this.leftController.dispose();
  82685. _this.leftController = null;
  82686. }
  82687. if (gamepad.hand === "right" && _this.rightController != null) {
  82688. _this.rightController.dispose();
  82689. _this.rightController = null;
  82690. }
  82691. }
  82692. };
  82693. this._workingVector = BABYLON.Vector3.Zero();
  82694. this._workingQuaternion = BABYLON.Quaternion.Identity();
  82695. this._workingMatrix = BABYLON.Matrix.Identity();
  82696. this._scene = scene;
  82697. this._canvas = scene.getEngine().getRenderingCanvas();
  82698. // Parse options
  82699. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  82700. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  82701. }
  82702. if (webVROptions.createDeviceOrientationCamera === undefined) {
  82703. webVROptions.createDeviceOrientationCamera = true;
  82704. }
  82705. if (webVROptions.defaultHeight === undefined) {
  82706. webVROptions.defaultHeight = 1.7;
  82707. }
  82708. if (webVROptions.useCustomVRButton) {
  82709. this._useCustomVRButton = true;
  82710. if (webVROptions.customVRButton) {
  82711. this._btnVR = webVROptions.customVRButton;
  82712. }
  82713. }
  82714. if (webVROptions.rayLength) {
  82715. this._rayLength = webVROptions.rayLength;
  82716. }
  82717. this._defaultHeight = webVROptions.defaultHeight;
  82718. if (webVROptions.positionScale) {
  82719. this._rayLength *= webVROptions.positionScale;
  82720. this._defaultHeight *= webVROptions.positionScale;
  82721. }
  82722. // Set position
  82723. if (this._scene.activeCamera) {
  82724. this._position = this._scene.activeCamera.position.clone();
  82725. }
  82726. else {
  82727. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  82728. }
  82729. // Set non-vr camera
  82730. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  82731. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  82732. // Copy data from existing camera
  82733. if (this._scene.activeCamera) {
  82734. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  82735. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  82736. // Set rotation from previous camera
  82737. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  82738. var targetCamera = this._scene.activeCamera;
  82739. if (targetCamera.rotationQuaternion) {
  82740. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  82741. }
  82742. else {
  82743. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  82744. }
  82745. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  82746. }
  82747. }
  82748. this._scene.activeCamera = this._deviceOrientationCamera;
  82749. if (this._canvas) {
  82750. this._scene.activeCamera.attachControl(this._canvas);
  82751. }
  82752. }
  82753. else {
  82754. this._existingCamera = this._scene.activeCamera;
  82755. }
  82756. // Create VR cameras
  82757. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  82758. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  82759. }
  82760. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  82761. this._webVRCamera.useStandingMatrix();
  82762. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  82763. // Create default button
  82764. if (!this._useCustomVRButton) {
  82765. this._btnVR = document.createElement("BUTTON");
  82766. this._btnVR.className = "babylonVRicon";
  82767. this._btnVR.id = "babylonVRiconbtn";
  82768. this._btnVR.title = "Click to switch to VR";
  82769. 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) }";
  82770. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  82771. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  82772. // css += ".babylonVRicon.vrdisplaysupported { }";
  82773. // css += ".babylonVRicon.vrdisplayready { }";
  82774. // css += ".babylonVRicon.vrdisplayrequesting { }";
  82775. var style = document.createElement('style');
  82776. style.appendChild(document.createTextNode(css));
  82777. document.getElementsByTagName('head')[0].appendChild(style);
  82778. this.moveButtonToBottomRight();
  82779. }
  82780. // VR button click event
  82781. if (this._btnVR) {
  82782. this._btnVR.addEventListener("click", function () {
  82783. if (!_this.isInVRMode) {
  82784. _this.enterVR();
  82785. }
  82786. else {
  82787. _this.exitVR();
  82788. }
  82789. });
  82790. }
  82791. // Window events
  82792. window.addEventListener("resize", this._onResize);
  82793. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  82794. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  82795. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  82796. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  82797. // Display vr button when headset is connected
  82798. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  82799. this.displayVRButton();
  82800. }
  82801. else {
  82802. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  82803. if (e.vrDisplay) {
  82804. _this.displayVRButton();
  82805. }
  82806. });
  82807. }
  82808. // Exiting VR mode using 'ESC' key on desktop
  82809. this._onKeyDown = function (event) {
  82810. if (event.keyCode === 27 && _this.isInVRMode) {
  82811. _this.exitVR();
  82812. }
  82813. };
  82814. document.addEventListener("keydown", this._onKeyDown);
  82815. // Exiting VR mode double tapping the touch screen
  82816. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  82817. if (_this.isInVRMode) {
  82818. _this.exitVR();
  82819. if (_this._fullscreenVRpresenting) {
  82820. _this._scene.getEngine().switchFullscreen(true);
  82821. }
  82822. }
  82823. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  82824. // Listen for WebVR display changes
  82825. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  82826. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  82827. this._onVRRequestPresentStart = function () {
  82828. _this._webVRrequesting = true;
  82829. _this.updateButtonVisibility();
  82830. };
  82831. this._onVRRequestPresentComplete = function (success) {
  82832. _this._webVRrequesting = false;
  82833. _this.updateButtonVisibility();
  82834. };
  82835. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  82836. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  82837. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  82838. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  82839. scene.onDisposeObservable.add(function () {
  82840. _this.dispose();
  82841. });
  82842. // Gamepad connection events
  82843. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  82844. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  82845. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  82846. this.updateButtonVisibility();
  82847. //create easing functions
  82848. this._circleEase = new BABYLON.CircleEase();
  82849. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  82850. }
  82851. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  82852. /** Return this.onEnteringVRObservable
  82853. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  82854. */
  82855. get: function () {
  82856. return this.onEnteringVRObservable;
  82857. },
  82858. enumerable: true,
  82859. configurable: true
  82860. });
  82861. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  82862. /** Return this.onExitingVRObservable
  82863. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  82864. */
  82865. get: function () {
  82866. return this.onExitingVRObservable;
  82867. },
  82868. enumerable: true,
  82869. configurable: true
  82870. });
  82871. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  82872. /** Return this.onControllerMeshLoadedObservable
  82873. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  82874. */
  82875. get: function () {
  82876. return this.onControllerMeshLoadedObservable;
  82877. },
  82878. enumerable: true,
  82879. configurable: true
  82880. });
  82881. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  82882. /**
  82883. * The mesh used to display where the user is going to teleport.
  82884. */
  82885. get: function () {
  82886. return this._teleportationTarget;
  82887. },
  82888. /**
  82889. * Sets the mesh to be used to display where the user is going to teleport.
  82890. */
  82891. set: function (value) {
  82892. if (value) {
  82893. value.name = "teleportationTarget";
  82894. this._isDefaultTeleportationTarget = false;
  82895. this._teleportationTarget = value;
  82896. }
  82897. },
  82898. enumerable: true,
  82899. configurable: true
  82900. });
  82901. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  82902. /**
  82903. * The mesh used to display where the user is selecting,
  82904. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  82905. * See http://doc.babylonjs.com/resources/baking_transformations
  82906. */
  82907. get: function () {
  82908. return this._cameraGazer._gazeTracker;
  82909. },
  82910. set: function (value) {
  82911. if (value) {
  82912. this._cameraGazer._gazeTracker = value;
  82913. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  82914. this._cameraGazer._gazeTracker.isPickable = false;
  82915. this._cameraGazer._gazeTracker.isVisible = false;
  82916. this._cameraGazer._gazeTracker.name = "gazeTracker";
  82917. if (this.leftController) {
  82918. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  82919. }
  82920. if (this.rightController) {
  82921. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  82922. }
  82923. }
  82924. },
  82925. enumerable: true,
  82926. configurable: true
  82927. });
  82928. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  82929. /**
  82930. * If the ray of the gaze should be displayed.
  82931. */
  82932. get: function () {
  82933. return this._displayGaze;
  82934. },
  82935. /**
  82936. * Sets if the ray of the gaze should be displayed.
  82937. */
  82938. set: function (value) {
  82939. this._displayGaze = value;
  82940. if (!value) {
  82941. this._cameraGazer._gazeTracker.isVisible = false;
  82942. if (this.leftController) {
  82943. this.leftController._gazeTracker.isVisible = false;
  82944. }
  82945. if (this.rightController) {
  82946. this.rightController._gazeTracker.isVisible = false;
  82947. }
  82948. }
  82949. },
  82950. enumerable: true,
  82951. configurable: true
  82952. });
  82953. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  82954. /**
  82955. * If the ray of the LaserPointer should be displayed.
  82956. */
  82957. get: function () {
  82958. return this._displayLaserPointer;
  82959. },
  82960. /**
  82961. * Sets if the ray of the LaserPointer should be displayed.
  82962. */
  82963. set: function (value) {
  82964. this._displayLaserPointer = value;
  82965. if (!value) {
  82966. if (this.rightController) {
  82967. this.rightController._deactivatePointer();
  82968. this.rightController._gazeTracker.isVisible = false;
  82969. }
  82970. if (this.leftController) {
  82971. this.leftController._deactivatePointer();
  82972. this.leftController._gazeTracker.isVisible = false;
  82973. }
  82974. }
  82975. else {
  82976. if (this.rightController) {
  82977. this.rightController._activatePointer();
  82978. }
  82979. else if (this.leftController) {
  82980. this.leftController._activatePointer();
  82981. }
  82982. }
  82983. },
  82984. enumerable: true,
  82985. configurable: true
  82986. });
  82987. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  82988. /**
  82989. * The deviceOrientationCamera used as the camera when not in VR.
  82990. */
  82991. get: function () {
  82992. return this._deviceOrientationCamera;
  82993. },
  82994. enumerable: true,
  82995. configurable: true
  82996. });
  82997. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  82998. /**
  82999. * Based on the current WebVR support, returns the current VR camera used.
  83000. */
  83001. get: function () {
  83002. if (this._webVRready) {
  83003. return this._webVRCamera;
  83004. }
  83005. else {
  83006. return this._scene.activeCamera;
  83007. }
  83008. },
  83009. enumerable: true,
  83010. configurable: true
  83011. });
  83012. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  83013. /**
  83014. * The webVRCamera which is used when in VR.
  83015. */
  83016. get: function () {
  83017. return this._webVRCamera;
  83018. },
  83019. enumerable: true,
  83020. configurable: true
  83021. });
  83022. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  83023. /**
  83024. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  83025. */
  83026. get: function () {
  83027. return this._vrDeviceOrientationCamera;
  83028. },
  83029. enumerable: true,
  83030. configurable: true
  83031. });
  83032. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  83033. get: function () {
  83034. var result = this._cameraGazer._teleportationRequestInitiated
  83035. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  83036. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  83037. return result;
  83038. },
  83039. enumerable: true,
  83040. configurable: true
  83041. });
  83042. // Raised when one of the controller has loaded successfully its associated default mesh
  83043. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  83044. if (this.leftController && this.leftController.webVRController == webVRController) {
  83045. if (webVRController.mesh) {
  83046. this.leftController._setLaserPointerParent(webVRController.mesh);
  83047. }
  83048. }
  83049. if (this.rightController && this.rightController.webVRController == webVRController) {
  83050. if (webVRController.mesh) {
  83051. this.rightController._setLaserPointerParent(webVRController.mesh);
  83052. }
  83053. }
  83054. try {
  83055. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  83056. }
  83057. catch (err) {
  83058. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  83059. }
  83060. };
  83061. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  83062. /**
  83063. * Gets a value indicating if we are currently in VR mode.
  83064. */
  83065. get: function () {
  83066. return this._webVRpresenting || this._fullscreenVRpresenting;
  83067. },
  83068. enumerable: true,
  83069. configurable: true
  83070. });
  83071. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  83072. var vrDisplay = this._scene.getEngine().getVRDevice();
  83073. if (vrDisplay) {
  83074. var wasPresenting = this._webVRpresenting;
  83075. // A VR display is connected
  83076. this._webVRpresenting = vrDisplay.isPresenting;
  83077. if (wasPresenting && !this._webVRpresenting)
  83078. this.exitVR();
  83079. }
  83080. else {
  83081. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  83082. }
  83083. this.updateButtonVisibility();
  83084. };
  83085. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  83086. this._webVRsupported = eventArgs.vrSupported;
  83087. this._webVRready = !!eventArgs.vrDisplay;
  83088. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  83089. this.updateButtonVisibility();
  83090. };
  83091. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  83092. if (this._canvas && !this._useCustomVRButton) {
  83093. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  83094. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  83095. }
  83096. };
  83097. VRExperienceHelper.prototype.displayVRButton = function () {
  83098. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  83099. document.body.appendChild(this._btnVR);
  83100. this._btnVRDisplayed = true;
  83101. }
  83102. };
  83103. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  83104. if (!this._btnVR || this._useCustomVRButton) {
  83105. return;
  83106. }
  83107. this._btnVR.className = "babylonVRicon";
  83108. if (this.isInVRMode) {
  83109. this._btnVR.className += " vrdisplaypresenting";
  83110. }
  83111. else {
  83112. if (this._webVRready)
  83113. this._btnVR.className += " vrdisplayready";
  83114. if (this._webVRsupported)
  83115. this._btnVR.className += " vrdisplaysupported";
  83116. if (this._webVRrequesting)
  83117. this._btnVR.className += " vrdisplayrequesting";
  83118. }
  83119. };
  83120. /**
  83121. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  83122. * Otherwise, will use the fullscreen API.
  83123. */
  83124. VRExperienceHelper.prototype.enterVR = function () {
  83125. if (this.onEnteringVRObservable) {
  83126. try {
  83127. this.onEnteringVRObservable.notifyObservers(this);
  83128. }
  83129. catch (err) {
  83130. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  83131. }
  83132. }
  83133. if (this._scene.activeCamera) {
  83134. this._position = this._scene.activeCamera.position.clone();
  83135. // make sure that we return to the last active camera
  83136. this._existingCamera = this._scene.activeCamera;
  83137. }
  83138. if (this._webVRrequesting)
  83139. return;
  83140. // If WebVR is supported and a headset is connected
  83141. if (this._webVRready) {
  83142. if (!this._webVRpresenting) {
  83143. this._webVRCamera.position = this._position;
  83144. this._scene.activeCamera = this._webVRCamera;
  83145. }
  83146. }
  83147. else if (this._vrDeviceOrientationCamera) {
  83148. this._vrDeviceOrientationCamera.position = this._position;
  83149. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  83150. this._scene.getEngine().switchFullscreen(true);
  83151. this.updateButtonVisibility();
  83152. }
  83153. if (this._scene.activeCamera && this._canvas) {
  83154. this._scene.activeCamera.attachControl(this._canvas);
  83155. }
  83156. if (this._interactionsEnabled) {
  83157. this._scene.registerBeforeRender(this.beforeRender);
  83158. }
  83159. };
  83160. /**
  83161. * Attempt to exit VR, or fullscreen.
  83162. */
  83163. VRExperienceHelper.prototype.exitVR = function () {
  83164. if (this.onExitingVRObservable) {
  83165. try {
  83166. this.onExitingVRObservable.notifyObservers(this);
  83167. }
  83168. catch (err) {
  83169. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  83170. }
  83171. }
  83172. if (this._webVRpresenting) {
  83173. this._scene.getEngine().disableVR();
  83174. }
  83175. if (this._scene.activeCamera) {
  83176. this._position = this._scene.activeCamera.position.clone();
  83177. }
  83178. if (this._deviceOrientationCamera) {
  83179. this._deviceOrientationCamera.position = this._position;
  83180. this._scene.activeCamera = this._deviceOrientationCamera;
  83181. if (this._canvas) {
  83182. this._scene.activeCamera.attachControl(this._canvas);
  83183. }
  83184. }
  83185. else if (this._existingCamera) {
  83186. this._existingCamera.position = this._position;
  83187. this._scene.activeCamera = this._existingCamera;
  83188. }
  83189. this.updateButtonVisibility();
  83190. if (this._interactionsEnabled) {
  83191. this._scene.unregisterBeforeRender(this.beforeRender);
  83192. }
  83193. };
  83194. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  83195. /**
  83196. * The position of the vr experience helper.
  83197. */
  83198. get: function () {
  83199. return this._position;
  83200. },
  83201. /**
  83202. * Sets the position of the vr experience helper.
  83203. */
  83204. set: function (value) {
  83205. this._position = value;
  83206. if (this._scene.activeCamera) {
  83207. this._scene.activeCamera.position = value;
  83208. }
  83209. },
  83210. enumerable: true,
  83211. configurable: true
  83212. });
  83213. /**
  83214. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  83215. */
  83216. VRExperienceHelper.prototype.enableInteractions = function () {
  83217. var _this = this;
  83218. if (!this._interactionsEnabled) {
  83219. this._interactionsRequested = true;
  83220. if (this.leftController) {
  83221. this._enableInteractionOnController(this.leftController);
  83222. }
  83223. if (this.rightController) {
  83224. this._enableInteractionOnController(this.rightController);
  83225. }
  83226. this.raySelectionPredicate = function (mesh) {
  83227. return mesh.isVisible;
  83228. };
  83229. this.meshSelectionPredicate = function (mesh) {
  83230. return true;
  83231. };
  83232. this._raySelectionPredicate = function (mesh) {
  83233. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  83234. && mesh.name.indexOf("teleportationTarget") === -1
  83235. && mesh.name.indexOf("torusTeleportation") === -1
  83236. && mesh.name.indexOf("laserPointer") === -1)) {
  83237. return _this.raySelectionPredicate(mesh);
  83238. }
  83239. return false;
  83240. };
  83241. this._interactionsEnabled = true;
  83242. }
  83243. };
  83244. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  83245. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  83246. if (this._floorMeshesCollection[i].id === mesh.id) {
  83247. return true;
  83248. }
  83249. }
  83250. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  83251. return true;
  83252. }
  83253. return false;
  83254. };
  83255. /**
  83256. * Adds a floor mesh to be used for teleportation.
  83257. * @param floorMesh the mesh to be used for teleportation.
  83258. */
  83259. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  83260. if (!this._floorMeshesCollection) {
  83261. return;
  83262. }
  83263. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  83264. return;
  83265. }
  83266. this._floorMeshesCollection.push(floorMesh);
  83267. };
  83268. /**
  83269. * Removes a floor mesh from being used for teleportation.
  83270. * @param floorMesh the mesh to be removed.
  83271. */
  83272. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  83273. if (!this._floorMeshesCollection) {
  83274. return;
  83275. }
  83276. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  83277. if (meshIndex !== -1) {
  83278. this._floorMeshesCollection.splice(meshIndex, 1);
  83279. }
  83280. };
  83281. /**
  83282. * Enables interactions and teleportation using the VR controllers and gaze.
  83283. * @param vrTeleportationOptions options to modify teleportation behavior.
  83284. */
  83285. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  83286. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  83287. if (!this._teleportationInitialized) {
  83288. this._teleportationRequested = true;
  83289. this.enableInteractions();
  83290. if (vrTeleportationOptions.floorMeshName) {
  83291. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  83292. }
  83293. if (vrTeleportationOptions.floorMeshes) {
  83294. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  83295. }
  83296. if (this.leftController != null) {
  83297. this._enableTeleportationOnController(this.leftController);
  83298. }
  83299. if (this.rightController != null) {
  83300. this._enableTeleportationOnController(this.rightController);
  83301. }
  83302. // Creates an image processing post process for the vignette not relying
  83303. // on the main scene configuration for image processing to reduce setup and spaces
  83304. // (gamma/linear) conflicts.
  83305. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  83306. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  83307. imageProcessingConfiguration.vignetteEnabled = true;
  83308. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  83309. this._webVRCamera.detachPostProcess(this._postProcessMove);
  83310. this._teleportationInitialized = true;
  83311. if (this._isDefaultTeleportationTarget) {
  83312. this._createTeleportationCircles();
  83313. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  83314. }
  83315. }
  83316. };
  83317. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  83318. var _this = this;
  83319. var controllerMesh = controller.webVRController.mesh;
  83320. if (controllerMesh) {
  83321. controller._interactionsEnabled = true;
  83322. controller._activatePointer();
  83323. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  83324. // Enabling / disabling laserPointer
  83325. if (_this._displayLaserPointer && stateObject.value === 1) {
  83326. if (controller._activePointer) {
  83327. controller._deactivatePointer();
  83328. }
  83329. else {
  83330. controller._activatePointer();
  83331. }
  83332. if (_this.displayGaze) {
  83333. controller._gazeTracker.isVisible = controller._activePointer;
  83334. }
  83335. }
  83336. });
  83337. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  83338. if (!controller._pointerDownOnMeshAsked) {
  83339. if (stateObject.value > _this._padSensibilityUp) {
  83340. controller._selectionPointerDown();
  83341. }
  83342. }
  83343. else if (stateObject.value < _this._padSensibilityDown) {
  83344. controller._selectionPointerUp();
  83345. }
  83346. });
  83347. }
  83348. };
  83349. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  83350. // Dont teleport if another gaze already requested teleportation
  83351. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  83352. return;
  83353. }
  83354. if (!gazer._teleportationRequestInitiated) {
  83355. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  83356. gazer._activatePointer();
  83357. gazer._teleportationRequestInitiated = true;
  83358. }
  83359. }
  83360. else {
  83361. // Listening to the proper controller values changes to confirm teleportation
  83362. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  83363. if (this._teleportActive) {
  83364. this._teleportCamera(this._haloCenter);
  83365. }
  83366. gazer._teleportationRequestInitiated = false;
  83367. }
  83368. }
  83369. };
  83370. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  83371. // Only rotate when user is not currently selecting a teleportation location
  83372. if (gazer._teleportationRequestInitiated) {
  83373. return;
  83374. }
  83375. if (!this._rotationLeftAsked) {
  83376. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  83377. this._rotationLeftAsked = true;
  83378. if (this._rotationAllowed) {
  83379. this._rotateCamera(false);
  83380. }
  83381. }
  83382. }
  83383. else {
  83384. if (stateObject.x > -this._padSensibilityDown) {
  83385. this._rotationLeftAsked = false;
  83386. }
  83387. }
  83388. if (!this._rotationRightAsked) {
  83389. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  83390. this._rotationRightAsked = true;
  83391. if (this._rotationAllowed) {
  83392. this._rotateCamera(true);
  83393. }
  83394. }
  83395. }
  83396. else {
  83397. if (stateObject.x < this._padSensibilityDown) {
  83398. this._rotationRightAsked = false;
  83399. }
  83400. }
  83401. };
  83402. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  83403. // Only teleport backwards when user is not currently selecting a teleportation location
  83404. if (gazer._teleportationRequestInitiated) {
  83405. return;
  83406. }
  83407. // Teleport backwards
  83408. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  83409. if (!gazer._teleportationBackRequestInitiated) {
  83410. if (!this.currentVRCamera) {
  83411. return;
  83412. }
  83413. // Get rotation and position of the current camera
  83414. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  83415. var position = this.currentVRCamera.position;
  83416. // If the camera has device position, use that instead
  83417. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  83418. rotation = this.currentVRCamera.deviceRotationQuaternion;
  83419. position = this.currentVRCamera.devicePosition;
  83420. }
  83421. // Get matrix with only the y rotation of the device rotation
  83422. rotation.toEulerAnglesToRef(this._workingVector);
  83423. this._workingVector.z = 0;
  83424. this._workingVector.x = 0;
  83425. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  83426. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  83427. // Rotate backwards ray by device rotation to cast at the ground behind the user
  83428. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  83429. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  83430. var ray = new BABYLON.Ray(position, this._workingVector);
  83431. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  83432. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  83433. this._teleportCamera(hit.pickedPoint);
  83434. }
  83435. gazer._teleportationBackRequestInitiated = true;
  83436. }
  83437. }
  83438. else {
  83439. gazer._teleportationBackRequestInitiated = false;
  83440. }
  83441. };
  83442. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  83443. var _this = this;
  83444. var controllerMesh = controller.webVRController.mesh;
  83445. if (controllerMesh) {
  83446. if (!controller._interactionsEnabled) {
  83447. this._enableInteractionOnController(controller);
  83448. }
  83449. controller._interactionsEnabled = true;
  83450. controller._teleportationEnabled = true;
  83451. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  83452. controller._dpadPressed = false;
  83453. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  83454. controller._dpadPressed = stateObject.pressed;
  83455. if (!controller._dpadPressed) {
  83456. _this._rotationLeftAsked = false;
  83457. _this._rotationRightAsked = false;
  83458. controller._teleportationBackRequestInitiated = false;
  83459. }
  83460. });
  83461. }
  83462. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  83463. if (_this.teleportationEnabled) {
  83464. _this._checkTeleportBackwards(stateObject, controller);
  83465. _this._checkTeleportWithRay(stateObject, controller);
  83466. }
  83467. _this._checkRotate(stateObject, controller);
  83468. });
  83469. }
  83470. };
  83471. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  83472. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  83473. this._teleportationTarget.isPickable = false;
  83474. var length = 512;
  83475. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  83476. dynamicTexture.hasAlpha = true;
  83477. var context = dynamicTexture.getContext();
  83478. var centerX = length / 2;
  83479. var centerY = length / 2;
  83480. var radius = 200;
  83481. context.beginPath();
  83482. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  83483. context.fillStyle = this._teleportationFillColor;
  83484. context.fill();
  83485. context.lineWidth = 10;
  83486. context.strokeStyle = this._teleportationBorderColor;
  83487. context.stroke();
  83488. context.closePath();
  83489. dynamicTexture.update();
  83490. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  83491. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  83492. this._teleportationTarget.material = teleportationCircleMaterial;
  83493. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  83494. torus.isPickable = false;
  83495. torus.parent = this._teleportationTarget;
  83496. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  83497. var keys = [];
  83498. keys.push({
  83499. frame: 0,
  83500. value: 0
  83501. });
  83502. keys.push({
  83503. frame: 30,
  83504. value: 0.4
  83505. });
  83506. keys.push({
  83507. frame: 60,
  83508. value: 0
  83509. });
  83510. animationInnerCircle.setKeys(keys);
  83511. var easingFunction = new BABYLON.SineEase();
  83512. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  83513. animationInnerCircle.setEasingFunction(easingFunction);
  83514. torus.animations = [];
  83515. torus.animations.push(animationInnerCircle);
  83516. this._scene.beginAnimation(torus, 0, 60, true);
  83517. this._hideTeleportationTarget();
  83518. };
  83519. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  83520. this._teleportActive = true;
  83521. if (this._teleportationInitialized) {
  83522. this._teleportationTarget.isVisible = true;
  83523. if (this._isDefaultTeleportationTarget) {
  83524. this._teleportationTarget.getChildren()[0].isVisible = true;
  83525. }
  83526. }
  83527. };
  83528. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  83529. this._teleportActive = false;
  83530. if (this._teleportationInitialized) {
  83531. this._teleportationTarget.isVisible = false;
  83532. if (this._isDefaultTeleportationTarget) {
  83533. this._teleportationTarget.getChildren()[0].isVisible = false;
  83534. }
  83535. }
  83536. };
  83537. VRExperienceHelper.prototype._rotateCamera = function (right) {
  83538. var _this = this;
  83539. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  83540. return;
  83541. }
  83542. if (right) {
  83543. this._rotationAngle++;
  83544. }
  83545. else {
  83546. this._rotationAngle--;
  83547. }
  83548. this.currentVRCamera.animations = [];
  83549. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  83550. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83551. var animationRotationKeys = [];
  83552. animationRotationKeys.push({
  83553. frame: 0,
  83554. value: this.currentVRCamera.rotationQuaternion
  83555. });
  83556. animationRotationKeys.push({
  83557. frame: 6,
  83558. value: target
  83559. });
  83560. animationRotation.setKeys(animationRotationKeys);
  83561. animationRotation.setEasingFunction(this._circleEase);
  83562. this.currentVRCamera.animations.push(animationRotation);
  83563. this._postProcessMove.animations = [];
  83564. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83565. var vignetteWeightKeys = [];
  83566. vignetteWeightKeys.push({
  83567. frame: 0,
  83568. value: 0
  83569. });
  83570. vignetteWeightKeys.push({
  83571. frame: 3,
  83572. value: 4
  83573. });
  83574. vignetteWeightKeys.push({
  83575. frame: 6,
  83576. value: 0
  83577. });
  83578. animationPP.setKeys(vignetteWeightKeys);
  83579. animationPP.setEasingFunction(this._circleEase);
  83580. this._postProcessMove.animations.push(animationPP);
  83581. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83582. var vignetteStretchKeys = [];
  83583. vignetteStretchKeys.push({
  83584. frame: 0,
  83585. value: 0
  83586. });
  83587. vignetteStretchKeys.push({
  83588. frame: 3,
  83589. value: 10
  83590. });
  83591. vignetteStretchKeys.push({
  83592. frame: 6,
  83593. value: 0
  83594. });
  83595. animationPP2.setKeys(vignetteStretchKeys);
  83596. animationPP2.setEasingFunction(this._circleEase);
  83597. this._postProcessMove.animations.push(animationPP2);
  83598. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  83599. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  83600. this._postProcessMove.samples = 4;
  83601. this._webVRCamera.attachPostProcess(this._postProcessMove);
  83602. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  83603. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  83604. });
  83605. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  83606. };
  83607. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  83608. if (hit.pickedPoint) {
  83609. if (gazer._teleportationRequestInitiated) {
  83610. this._displayTeleportationTarget();
  83611. this._haloCenter.copyFrom(hit.pickedPoint);
  83612. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  83613. }
  83614. var pickNormal = hit.getNormal(true, false);
  83615. if (pickNormal) {
  83616. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  83617. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  83618. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  83619. }
  83620. this._teleportationTarget.position.y += 0.1;
  83621. }
  83622. };
  83623. VRExperienceHelper.prototype._teleportCamera = function (location) {
  83624. var _this = this;
  83625. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  83626. return;
  83627. }
  83628. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  83629. // offset of the headset from the anchor.
  83630. if (this.webVRCamera.leftCamera) {
  83631. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  83632. this._workingVector.subtractInPlace(this.webVRCamera.position);
  83633. location.subtractToRef(this._workingVector, this._workingVector);
  83634. }
  83635. else {
  83636. this._workingVector.copyFrom(location);
  83637. }
  83638. // Add height to account for user's height offset
  83639. if (this.isInVRMode) {
  83640. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  83641. }
  83642. else {
  83643. this._workingVector.y += this._defaultHeight;
  83644. }
  83645. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  83646. // Create animation from the camera's position to the new location
  83647. this.currentVRCamera.animations = [];
  83648. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83649. var animationCameraTeleportationKeys = [{
  83650. frame: 0,
  83651. value: this.currentVRCamera.position
  83652. },
  83653. {
  83654. frame: 11,
  83655. value: this._workingVector
  83656. }
  83657. ];
  83658. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  83659. animationCameraTeleportation.setEasingFunction(this._circleEase);
  83660. this.currentVRCamera.animations.push(animationCameraTeleportation);
  83661. this._postProcessMove.animations = [];
  83662. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83663. var vignetteWeightKeys = [];
  83664. vignetteWeightKeys.push({
  83665. frame: 0,
  83666. value: 0
  83667. });
  83668. vignetteWeightKeys.push({
  83669. frame: 5,
  83670. value: 8
  83671. });
  83672. vignetteWeightKeys.push({
  83673. frame: 11,
  83674. value: 0
  83675. });
  83676. animationPP.setKeys(vignetteWeightKeys);
  83677. this._postProcessMove.animations.push(animationPP);
  83678. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83679. var vignetteStretchKeys = [];
  83680. vignetteStretchKeys.push({
  83681. frame: 0,
  83682. value: 0
  83683. });
  83684. vignetteStretchKeys.push({
  83685. frame: 5,
  83686. value: 10
  83687. });
  83688. vignetteStretchKeys.push({
  83689. frame: 11,
  83690. value: 0
  83691. });
  83692. animationPP2.setKeys(vignetteStretchKeys);
  83693. this._postProcessMove.animations.push(animationPP2);
  83694. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  83695. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  83696. this._webVRCamera.attachPostProcess(this._postProcessMove);
  83697. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  83698. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  83699. });
  83700. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  83701. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  83702. });
  83703. this._hideTeleportationTarget();
  83704. };
  83705. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  83706. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  83707. return;
  83708. }
  83709. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  83710. // Moving the gazeTracker on the mesh face targetted
  83711. if (hit && hit.pickedPoint) {
  83712. if (this._displayGaze) {
  83713. var multiplier = 1;
  83714. gazer._gazeTracker.isVisible = true;
  83715. if (gazer._isActionableMesh) {
  83716. multiplier = 3;
  83717. }
  83718. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  83719. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  83720. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  83721. var pickNormal = hit.getNormal();
  83722. // To avoid z-fighting
  83723. var deltaFighting = 0.002;
  83724. if (pickNormal) {
  83725. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  83726. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  83727. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  83728. }
  83729. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  83730. if (gazer._gazeTracker.position.x < 0) {
  83731. gazer._gazeTracker.position.x += deltaFighting;
  83732. }
  83733. else {
  83734. gazer._gazeTracker.position.x -= deltaFighting;
  83735. }
  83736. if (gazer._gazeTracker.position.y < 0) {
  83737. gazer._gazeTracker.position.y += deltaFighting;
  83738. }
  83739. else {
  83740. gazer._gazeTracker.position.y -= deltaFighting;
  83741. }
  83742. if (gazer._gazeTracker.position.z < 0) {
  83743. gazer._gazeTracker.position.z += deltaFighting;
  83744. }
  83745. else {
  83746. gazer._gazeTracker.position.z -= deltaFighting;
  83747. }
  83748. }
  83749. // Changing the size of the laser pointer based on the distance from the targetted point
  83750. gazer._updatePointerDistance(hit.distance);
  83751. }
  83752. else {
  83753. gazer._gazeTracker.isVisible = false;
  83754. }
  83755. if (hit && hit.pickedMesh) {
  83756. gazer._currentHit = hit;
  83757. if (gazer._pointerDownOnMeshAsked) {
  83758. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  83759. }
  83760. // The object selected is the floor, we're in a teleportation scenario
  83761. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  83762. // Moving the teleportation area to this targetted point
  83763. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  83764. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  83765. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  83766. }
  83767. gazer._currentMeshSelected = null;
  83768. if (gazer._teleportationRequestInitiated) {
  83769. this._moveTeleportationSelectorTo(hit, gazer);
  83770. }
  83771. return;
  83772. }
  83773. // If not, we're in a selection scenario
  83774. //this._teleportationAllowed = false;
  83775. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  83776. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  83777. this.onNewMeshPicked.notifyObservers(hit);
  83778. gazer._currentMeshSelected = hit.pickedMesh;
  83779. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  83780. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  83781. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  83782. gazer._isActionableMesh = true;
  83783. }
  83784. else {
  83785. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83786. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83787. gazer._isActionableMesh = false;
  83788. }
  83789. try {
  83790. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  83791. }
  83792. catch (err) {
  83793. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  83794. }
  83795. }
  83796. else {
  83797. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  83798. gazer._currentMeshSelected = null;
  83799. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83800. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83801. }
  83802. }
  83803. }
  83804. else {
  83805. gazer._currentHit = null;
  83806. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  83807. gazer._currentMeshSelected = null;
  83808. //this._teleportationAllowed = false;
  83809. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83810. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83811. }
  83812. };
  83813. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  83814. if (mesh) {
  83815. this.onSelectedMeshUnselected.notifyObservers(mesh);
  83816. }
  83817. };
  83818. /**
  83819. * Sets the color of the laser ray from the vr controllers.
  83820. * @param color new color for the ray.
  83821. */
  83822. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  83823. if (this.leftController) {
  83824. this.leftController._setLaserPointerColor(color);
  83825. }
  83826. if (this.rightController) {
  83827. this.rightController._setLaserPointerColor(color);
  83828. }
  83829. };
  83830. /**
  83831. * Sets the color of the ray from the vr headsets gaze.
  83832. * @param color new color for the ray.
  83833. */
  83834. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  83835. if (!this._cameraGazer._gazeTracker.material) {
  83836. return;
  83837. }
  83838. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  83839. if (this.leftController) {
  83840. this.leftController._gazeTracker.material.emissiveColor = color;
  83841. }
  83842. if (this.rightController) {
  83843. this.rightController._gazeTracker.material.emissiveColor = color;
  83844. }
  83845. };
  83846. /**
  83847. * Exits VR and disposes of the vr experience helper
  83848. */
  83849. VRExperienceHelper.prototype.dispose = function () {
  83850. if (this.isInVRMode) {
  83851. this.exitVR();
  83852. }
  83853. if (this._postProcessMove) {
  83854. this._postProcessMove.dispose();
  83855. }
  83856. if (this._webVRCamera) {
  83857. this._webVRCamera.dispose();
  83858. }
  83859. if (this._vrDeviceOrientationCamera) {
  83860. this._vrDeviceOrientationCamera.dispose();
  83861. }
  83862. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  83863. document.body.removeChild(this._btnVR);
  83864. }
  83865. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  83866. this._deviceOrientationCamera.dispose();
  83867. }
  83868. if (this._cameraGazer) {
  83869. this._cameraGazer.dispose();
  83870. }
  83871. if (this.leftController) {
  83872. this.leftController.dispose();
  83873. }
  83874. if (this.rightController) {
  83875. this.rightController.dispose();
  83876. }
  83877. if (this._teleportationTarget) {
  83878. this._teleportationTarget.dispose();
  83879. }
  83880. this._floorMeshesCollection = [];
  83881. document.removeEventListener("keydown", this._onKeyDown);
  83882. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  83883. window.removeEventListener("resize", this._onResize);
  83884. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  83885. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  83886. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  83887. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  83888. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  83889. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  83890. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  83891. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  83892. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  83893. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  83894. this._scene.unregisterBeforeRender(this.beforeRender);
  83895. };
  83896. /**
  83897. * Gets the name of the VRExperienceHelper class
  83898. * @returns "VRExperienceHelper"
  83899. */
  83900. VRExperienceHelper.prototype.getClassName = function () {
  83901. return "VRExperienceHelper";
  83902. };
  83903. return VRExperienceHelper;
  83904. }());
  83905. BABYLON.VRExperienceHelper = VRExperienceHelper;
  83906. })(BABYLON || (BABYLON = {}));
  83907. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  83908. "use strict";
  83909. // Mainly based on these 2 articles :
  83910. // 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
  83911. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  83912. var BABYLON;
  83913. (function (BABYLON) {
  83914. var JoystickAxis;
  83915. (function (JoystickAxis) {
  83916. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  83917. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  83918. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  83919. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  83920. var VirtualJoystick = /** @class */ (function () {
  83921. function VirtualJoystick(leftJoystick) {
  83922. var _this = this;
  83923. if (leftJoystick) {
  83924. this._leftJoystick = true;
  83925. }
  83926. else {
  83927. this._leftJoystick = false;
  83928. }
  83929. VirtualJoystick._globalJoystickIndex++;
  83930. // By default left & right arrow keys are moving the X
  83931. // and up & down keys are moving the Y
  83932. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  83933. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  83934. this.reverseLeftRight = false;
  83935. this.reverseUpDown = false;
  83936. // collections of pointers
  83937. this._touches = new BABYLON.StringDictionary();
  83938. this.deltaPosition = BABYLON.Vector3.Zero();
  83939. this._joystickSensibility = 25;
  83940. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  83941. this._onResize = function (evt) {
  83942. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  83943. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  83944. if (VirtualJoystick.vjCanvas) {
  83945. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  83946. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  83947. }
  83948. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  83949. };
  83950. // injecting a canvas element on top of the canvas 3D game
  83951. if (!VirtualJoystick.vjCanvas) {
  83952. window.addEventListener("resize", this._onResize, false);
  83953. VirtualJoystick.vjCanvas = document.createElement("canvas");
  83954. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  83955. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  83956. VirtualJoystick.vjCanvas.width = window.innerWidth;
  83957. VirtualJoystick.vjCanvas.height = window.innerHeight;
  83958. VirtualJoystick.vjCanvas.style.width = "100%";
  83959. VirtualJoystick.vjCanvas.style.height = "100%";
  83960. VirtualJoystick.vjCanvas.style.position = "absolute";
  83961. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  83962. VirtualJoystick.vjCanvas.style.top = "0px";
  83963. VirtualJoystick.vjCanvas.style.left = "0px";
  83964. VirtualJoystick.vjCanvas.style.zIndex = "5";
  83965. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  83966. // Support for jQuery PEP polyfill
  83967. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  83968. var context = VirtualJoystick.vjCanvas.getContext('2d');
  83969. if (!context) {
  83970. throw new Error("Unable to create canvas for virtual joystick");
  83971. }
  83972. VirtualJoystick.vjCanvasContext = context;
  83973. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  83974. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  83975. document.body.appendChild(VirtualJoystick.vjCanvas);
  83976. }
  83977. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  83978. this.pressed = false;
  83979. // default joystick color
  83980. this._joystickColor = "cyan";
  83981. this._joystickPointerID = -1;
  83982. // current joystick position
  83983. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  83984. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  83985. // origin joystick position
  83986. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  83987. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  83988. this._onPointerDownHandlerRef = function (evt) {
  83989. _this._onPointerDown(evt);
  83990. };
  83991. this._onPointerMoveHandlerRef = function (evt) {
  83992. _this._onPointerMove(evt);
  83993. };
  83994. this._onPointerUpHandlerRef = function (evt) {
  83995. _this._onPointerUp(evt);
  83996. };
  83997. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  83998. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  83999. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  84000. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  84001. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  84002. evt.preventDefault(); // Disables system menu
  84003. }, false);
  84004. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  84005. }
  84006. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  84007. this._joystickSensibility = newJoystickSensibility;
  84008. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  84009. };
  84010. VirtualJoystick.prototype._onPointerDown = function (e) {
  84011. var positionOnScreenCondition;
  84012. e.preventDefault();
  84013. if (this._leftJoystick === true) {
  84014. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  84015. }
  84016. else {
  84017. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  84018. }
  84019. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  84020. // First contact will be dedicated to the virtual joystick
  84021. this._joystickPointerID = e.pointerId;
  84022. this._joystickPointerStartPos.x = e.clientX;
  84023. this._joystickPointerStartPos.y = e.clientY;
  84024. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  84025. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  84026. this._deltaJoystickVector.x = 0;
  84027. this._deltaJoystickVector.y = 0;
  84028. this.pressed = true;
  84029. this._touches.add(e.pointerId.toString(), e);
  84030. }
  84031. else {
  84032. // You can only trigger the action buttons with a joystick declared
  84033. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  84034. this._action();
  84035. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  84036. }
  84037. }
  84038. };
  84039. VirtualJoystick.prototype._onPointerMove = function (e) {
  84040. // If the current pointer is the one associated to the joystick (first touch contact)
  84041. if (this._joystickPointerID == e.pointerId) {
  84042. this._joystickPointerPos.x = e.clientX;
  84043. this._joystickPointerPos.y = e.clientY;
  84044. this._deltaJoystickVector = this._joystickPointerPos.clone();
  84045. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  84046. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  84047. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  84048. switch (this._axisTargetedByLeftAndRight) {
  84049. case JoystickAxis.X:
  84050. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  84051. break;
  84052. case JoystickAxis.Y:
  84053. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  84054. break;
  84055. case JoystickAxis.Z:
  84056. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  84057. break;
  84058. }
  84059. var directionUpDown = this.reverseUpDown ? 1 : -1;
  84060. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  84061. switch (this._axisTargetedByUpAndDown) {
  84062. case JoystickAxis.X:
  84063. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  84064. break;
  84065. case JoystickAxis.Y:
  84066. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  84067. break;
  84068. case JoystickAxis.Z:
  84069. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  84070. break;
  84071. }
  84072. }
  84073. else {
  84074. var data = this._touches.get(e.pointerId.toString());
  84075. if (data) {
  84076. data.x = e.clientX;
  84077. data.y = e.clientY;
  84078. }
  84079. }
  84080. };
  84081. VirtualJoystick.prototype._onPointerUp = function (e) {
  84082. if (this._joystickPointerID == e.pointerId) {
  84083. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  84084. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  84085. this._joystickPointerID = -1;
  84086. this.pressed = false;
  84087. }
  84088. else {
  84089. var touch = this._touches.get(e.pointerId.toString());
  84090. if (touch) {
  84091. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  84092. }
  84093. }
  84094. this._deltaJoystickVector.x = 0;
  84095. this._deltaJoystickVector.y = 0;
  84096. this._touches.remove(e.pointerId.toString());
  84097. };
  84098. /**
  84099. * Change the color of the virtual joystick
  84100. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  84101. */
  84102. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  84103. this._joystickColor = newColor;
  84104. };
  84105. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  84106. this._action = action;
  84107. };
  84108. // Define which axis you'd like to control for left & right
  84109. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  84110. switch (axis) {
  84111. case JoystickAxis.X:
  84112. case JoystickAxis.Y:
  84113. case JoystickAxis.Z:
  84114. this._axisTargetedByLeftAndRight = axis;
  84115. break;
  84116. default:
  84117. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  84118. break;
  84119. }
  84120. };
  84121. // Define which axis you'd like to control for up & down
  84122. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  84123. switch (axis) {
  84124. case JoystickAxis.X:
  84125. case JoystickAxis.Y:
  84126. case JoystickAxis.Z:
  84127. this._axisTargetedByUpAndDown = axis;
  84128. break;
  84129. default:
  84130. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  84131. break;
  84132. }
  84133. };
  84134. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  84135. var _this = this;
  84136. if (this.pressed) {
  84137. this._touches.forEach(function (key, touch) {
  84138. if (touch.pointerId === _this._joystickPointerID) {
  84139. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  84140. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  84141. VirtualJoystick.vjCanvasContext.beginPath();
  84142. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  84143. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  84144. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  84145. VirtualJoystick.vjCanvasContext.stroke();
  84146. VirtualJoystick.vjCanvasContext.closePath();
  84147. VirtualJoystick.vjCanvasContext.beginPath();
  84148. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  84149. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  84150. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  84151. VirtualJoystick.vjCanvasContext.stroke();
  84152. VirtualJoystick.vjCanvasContext.closePath();
  84153. VirtualJoystick.vjCanvasContext.beginPath();
  84154. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  84155. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  84156. VirtualJoystick.vjCanvasContext.stroke();
  84157. VirtualJoystick.vjCanvasContext.closePath();
  84158. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  84159. }
  84160. else {
  84161. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  84162. VirtualJoystick.vjCanvasContext.beginPath();
  84163. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  84164. VirtualJoystick.vjCanvasContext.beginPath();
  84165. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  84166. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  84167. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  84168. VirtualJoystick.vjCanvasContext.stroke();
  84169. VirtualJoystick.vjCanvasContext.closePath();
  84170. touch.prevX = touch.x;
  84171. touch.prevY = touch.y;
  84172. }
  84173. ;
  84174. });
  84175. }
  84176. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  84177. };
  84178. VirtualJoystick.prototype.releaseCanvas = function () {
  84179. if (VirtualJoystick.vjCanvas) {
  84180. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  84181. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  84182. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  84183. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  84184. window.removeEventListener("resize", this._onResize);
  84185. document.body.removeChild(VirtualJoystick.vjCanvas);
  84186. VirtualJoystick.vjCanvas = null;
  84187. }
  84188. };
  84189. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  84190. VirtualJoystick._globalJoystickIndex = 0;
  84191. return VirtualJoystick;
  84192. }());
  84193. BABYLON.VirtualJoystick = VirtualJoystick;
  84194. })(BABYLON || (BABYLON = {}));
  84195. //# sourceMappingURL=babylon.virtualJoystick.js.map
  84196. "use strict";
  84197. var BABYLON;
  84198. (function (BABYLON) {
  84199. // We're mainly based on the logic defined into the FreeCamera code
  84200. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  84201. __extends(VirtualJoysticksCamera, _super);
  84202. function VirtualJoysticksCamera(name, position, scene) {
  84203. var _this = _super.call(this, name, position, scene) || this;
  84204. _this.inputs.addVirtualJoystick();
  84205. return _this;
  84206. }
  84207. VirtualJoysticksCamera.prototype.getClassName = function () {
  84208. return "VirtualJoysticksCamera";
  84209. };
  84210. return VirtualJoysticksCamera;
  84211. }(BABYLON.FreeCamera));
  84212. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  84213. })(BABYLON || (BABYLON = {}));
  84214. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  84215. "use strict";
  84216. var BABYLON;
  84217. (function (BABYLON) {
  84218. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  84219. function FreeCameraVirtualJoystickInput() {
  84220. }
  84221. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  84222. return this._leftjoystick;
  84223. };
  84224. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  84225. return this._rightjoystick;
  84226. };
  84227. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  84228. if (this._leftjoystick) {
  84229. var camera = this.camera;
  84230. var speed = camera._computeLocalCameraSpeed() * 50;
  84231. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  84232. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  84233. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  84234. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  84235. if (!this._leftjoystick.pressed) {
  84236. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  84237. }
  84238. if (!this._rightjoystick.pressed) {
  84239. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  84240. }
  84241. }
  84242. };
  84243. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  84244. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  84245. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  84246. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  84247. this._leftjoystick.setJoystickSensibility(0.15);
  84248. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  84249. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  84250. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  84251. this._rightjoystick.reverseUpDown = true;
  84252. this._rightjoystick.setJoystickSensibility(0.05);
  84253. this._rightjoystick.setJoystickColor("yellow");
  84254. };
  84255. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  84256. this._leftjoystick.releaseCanvas();
  84257. this._rightjoystick.releaseCanvas();
  84258. };
  84259. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  84260. return "FreeCameraVirtualJoystickInput";
  84261. };
  84262. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  84263. return "virtualJoystick";
  84264. };
  84265. return FreeCameraVirtualJoystickInput;
  84266. }());
  84267. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  84268. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  84269. })(BABYLON || (BABYLON = {}));
  84270. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  84271. "use strict";
  84272. var BABYLON;
  84273. (function (BABYLON) {
  84274. var SimplificationSettings = /** @class */ (function () {
  84275. function SimplificationSettings(quality, distance, optimizeMesh) {
  84276. this.quality = quality;
  84277. this.distance = distance;
  84278. this.optimizeMesh = optimizeMesh;
  84279. }
  84280. return SimplificationSettings;
  84281. }());
  84282. BABYLON.SimplificationSettings = SimplificationSettings;
  84283. var SimplificationQueue = /** @class */ (function () {
  84284. function SimplificationQueue() {
  84285. this.running = false;
  84286. this._simplificationArray = [];
  84287. }
  84288. SimplificationQueue.prototype.addTask = function (task) {
  84289. this._simplificationArray.push(task);
  84290. };
  84291. SimplificationQueue.prototype.executeNext = function () {
  84292. var task = this._simplificationArray.pop();
  84293. if (task) {
  84294. this.running = true;
  84295. this.runSimplification(task);
  84296. }
  84297. else {
  84298. this.running = false;
  84299. }
  84300. };
  84301. SimplificationQueue.prototype.runSimplification = function (task) {
  84302. var _this = this;
  84303. if (task.parallelProcessing) {
  84304. //parallel simplifier
  84305. task.settings.forEach(function (setting) {
  84306. var simplifier = _this.getSimplifier(task);
  84307. simplifier.simplify(setting, function (newMesh) {
  84308. task.mesh.addLODLevel(setting.distance, newMesh);
  84309. newMesh.isVisible = true;
  84310. //check if it is the last
  84311. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  84312. //all done, run the success callback.
  84313. task.successCallback();
  84314. }
  84315. _this.executeNext();
  84316. });
  84317. });
  84318. }
  84319. else {
  84320. //single simplifier.
  84321. var simplifier = this.getSimplifier(task);
  84322. var runDecimation = function (setting, callback) {
  84323. simplifier.simplify(setting, function (newMesh) {
  84324. task.mesh.addLODLevel(setting.distance, newMesh);
  84325. newMesh.isVisible = true;
  84326. //run the next quality level
  84327. callback();
  84328. });
  84329. };
  84330. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  84331. runDecimation(task.settings[loop.index], function () {
  84332. loop.executeNext();
  84333. });
  84334. }, function () {
  84335. //execution ended, run the success callback.
  84336. if (task.successCallback) {
  84337. task.successCallback();
  84338. }
  84339. _this.executeNext();
  84340. });
  84341. }
  84342. };
  84343. SimplificationQueue.prototype.getSimplifier = function (task) {
  84344. switch (task.simplificationType) {
  84345. case SimplificationType.QUADRATIC:
  84346. default:
  84347. return new QuadraticErrorSimplification(task.mesh);
  84348. }
  84349. };
  84350. return SimplificationQueue;
  84351. }());
  84352. BABYLON.SimplificationQueue = SimplificationQueue;
  84353. /**
  84354. * The implemented types of simplification.
  84355. * At the moment only Quadratic Error Decimation is implemented.
  84356. */
  84357. var SimplificationType;
  84358. (function (SimplificationType) {
  84359. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  84360. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  84361. var DecimationTriangle = /** @class */ (function () {
  84362. function DecimationTriangle(vertices) {
  84363. this.vertices = vertices;
  84364. this.error = new Array(4);
  84365. this.deleted = false;
  84366. this.isDirty = false;
  84367. this.deletePending = false;
  84368. this.borderFactor = 0;
  84369. }
  84370. return DecimationTriangle;
  84371. }());
  84372. BABYLON.DecimationTriangle = DecimationTriangle;
  84373. var DecimationVertex = /** @class */ (function () {
  84374. function DecimationVertex(position, id) {
  84375. this.position = position;
  84376. this.id = id;
  84377. this.isBorder = true;
  84378. this.q = new QuadraticMatrix();
  84379. this.triangleCount = 0;
  84380. this.triangleStart = 0;
  84381. this.originalOffsets = [];
  84382. }
  84383. DecimationVertex.prototype.updatePosition = function (newPosition) {
  84384. this.position.copyFrom(newPosition);
  84385. };
  84386. return DecimationVertex;
  84387. }());
  84388. BABYLON.DecimationVertex = DecimationVertex;
  84389. var QuadraticMatrix = /** @class */ (function () {
  84390. function QuadraticMatrix(data) {
  84391. this.data = new Array(10);
  84392. for (var i = 0; i < 10; ++i) {
  84393. if (data && data[i]) {
  84394. this.data[i] = data[i];
  84395. }
  84396. else {
  84397. this.data[i] = 0;
  84398. }
  84399. }
  84400. }
  84401. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  84402. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  84403. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  84404. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  84405. return det;
  84406. };
  84407. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  84408. for (var i = 0; i < 10; ++i) {
  84409. this.data[i] += matrix.data[i];
  84410. }
  84411. };
  84412. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  84413. for (var i = 0; i < 10; ++i) {
  84414. this.data[i] += data[i];
  84415. }
  84416. };
  84417. QuadraticMatrix.prototype.add = function (matrix) {
  84418. var m = new QuadraticMatrix();
  84419. for (var i = 0; i < 10; ++i) {
  84420. m.data[i] = this.data[i] + matrix.data[i];
  84421. }
  84422. return m;
  84423. };
  84424. QuadraticMatrix.FromData = function (a, b, c, d) {
  84425. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  84426. };
  84427. //returning an array to avoid garbage collection
  84428. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  84429. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  84430. };
  84431. return QuadraticMatrix;
  84432. }());
  84433. BABYLON.QuadraticMatrix = QuadraticMatrix;
  84434. var Reference = /** @class */ (function () {
  84435. function Reference(vertexId, triangleId) {
  84436. this.vertexId = vertexId;
  84437. this.triangleId = triangleId;
  84438. }
  84439. return Reference;
  84440. }());
  84441. BABYLON.Reference = Reference;
  84442. /**
  84443. * An implementation of the Quadratic Error simplification algorithm.
  84444. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  84445. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  84446. * @author RaananW
  84447. */
  84448. var QuadraticErrorSimplification = /** @class */ (function () {
  84449. function QuadraticErrorSimplification(_mesh) {
  84450. this._mesh = _mesh;
  84451. this.syncIterations = 5000;
  84452. this.aggressiveness = 7;
  84453. this.decimationIterations = 100;
  84454. this.boundingBoxEpsilon = BABYLON.Epsilon;
  84455. }
  84456. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  84457. var _this = this;
  84458. this.initDecimatedMesh();
  84459. //iterating through the submeshes array, one after the other.
  84460. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  84461. _this.initWithMesh(loop.index, function () {
  84462. _this.runDecimation(settings, loop.index, function () {
  84463. loop.executeNext();
  84464. });
  84465. }, settings.optimizeMesh);
  84466. }, function () {
  84467. setTimeout(function () {
  84468. successCallback(_this._reconstructedMesh);
  84469. }, 0);
  84470. });
  84471. };
  84472. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  84473. var _this = this;
  84474. var targetCount = ~~(this.triangles.length * settings.quality);
  84475. var deletedTriangles = 0;
  84476. var triangleCount = this.triangles.length;
  84477. var iterationFunction = function (iteration, callback) {
  84478. setTimeout(function () {
  84479. if (iteration % 5 === 0) {
  84480. _this.updateMesh(iteration === 0);
  84481. }
  84482. for (var i = 0; i < _this.triangles.length; ++i) {
  84483. _this.triangles[i].isDirty = false;
  84484. }
  84485. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  84486. var trianglesIterator = function (i) {
  84487. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  84488. var t = _this.triangles[tIdx];
  84489. if (!t)
  84490. return;
  84491. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  84492. return;
  84493. }
  84494. for (var j = 0; j < 3; ++j) {
  84495. if (t.error[j] < threshold) {
  84496. var deleted0 = [];
  84497. var deleted1 = [];
  84498. var v0 = t.vertices[j];
  84499. var v1 = t.vertices[(j + 1) % 3];
  84500. if (v0.isBorder || v1.isBorder)
  84501. continue;
  84502. var p = BABYLON.Vector3.Zero();
  84503. var n = BABYLON.Vector3.Zero();
  84504. var uv = BABYLON.Vector2.Zero();
  84505. var color = new BABYLON.Color4(0, 0, 0, 1);
  84506. _this.calculateError(v0, v1, p, n, uv, color);
  84507. var delTr = new Array();
  84508. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  84509. continue;
  84510. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  84511. continue;
  84512. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  84513. continue;
  84514. var uniqueArray = new Array();
  84515. delTr.forEach(function (deletedT) {
  84516. if (uniqueArray.indexOf(deletedT) === -1) {
  84517. deletedT.deletePending = true;
  84518. uniqueArray.push(deletedT);
  84519. }
  84520. });
  84521. if (uniqueArray.length % 2 !== 0) {
  84522. continue;
  84523. }
  84524. v0.q = v1.q.add(v0.q);
  84525. v0.updatePosition(p);
  84526. var tStart = _this.references.length;
  84527. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  84528. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  84529. var tCount = _this.references.length - tStart;
  84530. if (tCount <= v0.triangleCount) {
  84531. if (tCount) {
  84532. for (var c = 0; c < tCount; c++) {
  84533. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  84534. }
  84535. }
  84536. }
  84537. else {
  84538. v0.triangleStart = tStart;
  84539. }
  84540. v0.triangleCount = tCount;
  84541. break;
  84542. }
  84543. }
  84544. };
  84545. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  84546. }, 0);
  84547. };
  84548. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  84549. if (triangleCount - deletedTriangles <= targetCount)
  84550. loop.breakLoop();
  84551. else {
  84552. iterationFunction(loop.index, function () {
  84553. loop.executeNext();
  84554. });
  84555. }
  84556. }, function () {
  84557. setTimeout(function () {
  84558. //reconstruct this part of the mesh
  84559. _this.reconstructMesh(submeshIndex);
  84560. successCallback();
  84561. }, 0);
  84562. });
  84563. };
  84564. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  84565. var _this = this;
  84566. this.vertices = [];
  84567. this.triangles = [];
  84568. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  84569. var indices = this._mesh.getIndices();
  84570. var submesh = this._mesh.subMeshes[submeshIndex];
  84571. var findInVertices = function (positionToSearch) {
  84572. if (optimizeMesh) {
  84573. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  84574. if (_this.vertices[ii].position.equals(positionToSearch)) {
  84575. return _this.vertices[ii];
  84576. }
  84577. }
  84578. }
  84579. return null;
  84580. };
  84581. var vertexReferences = [];
  84582. var vertexInit = function (i) {
  84583. if (!positionData) {
  84584. return;
  84585. }
  84586. var offset = i + submesh.verticesStart;
  84587. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  84588. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  84589. vertex.originalOffsets.push(offset);
  84590. if (vertex.id === _this.vertices.length) {
  84591. _this.vertices.push(vertex);
  84592. }
  84593. vertexReferences.push(vertex.id);
  84594. };
  84595. //var totalVertices = mesh.getTotalVertices();
  84596. var totalVertices = submesh.verticesCount;
  84597. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  84598. var indicesInit = function (i) {
  84599. if (!indices) {
  84600. return;
  84601. }
  84602. var offset = (submesh.indexStart / 3) + i;
  84603. var pos = (offset * 3);
  84604. var i0 = indices[pos + 0];
  84605. var i1 = indices[pos + 1];
  84606. var i2 = indices[pos + 2];
  84607. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  84608. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  84609. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  84610. var triangle = new DecimationTriangle([v0, v1, v2]);
  84611. triangle.originalOffset = pos;
  84612. _this.triangles.push(triangle);
  84613. };
  84614. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  84615. _this.init(callback);
  84616. });
  84617. });
  84618. };
  84619. QuadraticErrorSimplification.prototype.init = function (callback) {
  84620. var _this = this;
  84621. var triangleInit1 = function (i) {
  84622. var t = _this.triangles[i];
  84623. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  84624. for (var j = 0; j < 3; j++) {
  84625. 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))));
  84626. }
  84627. };
  84628. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  84629. var triangleInit2 = function (i) {
  84630. var t = _this.triangles[i];
  84631. for (var j = 0; j < 3; ++j) {
  84632. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  84633. }
  84634. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  84635. };
  84636. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  84637. callback();
  84638. });
  84639. });
  84640. };
  84641. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  84642. var newTriangles = [];
  84643. var i;
  84644. for (i = 0; i < this.vertices.length; ++i) {
  84645. this.vertices[i].triangleCount = 0;
  84646. }
  84647. var t;
  84648. var j;
  84649. for (i = 0; i < this.triangles.length; ++i) {
  84650. if (!this.triangles[i].deleted) {
  84651. t = this.triangles[i];
  84652. for (j = 0; j < 3; ++j) {
  84653. t.vertices[j].triangleCount = 1;
  84654. }
  84655. newTriangles.push(t);
  84656. }
  84657. }
  84658. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  84659. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  84660. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  84661. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  84662. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  84663. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  84664. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  84665. var vertexCount = 0;
  84666. for (i = 0; i < this.vertices.length; ++i) {
  84667. var vertex = this.vertices[i];
  84668. vertex.id = vertexCount;
  84669. if (vertex.triangleCount) {
  84670. vertex.originalOffsets.forEach(function (originalOffset) {
  84671. if (!normalData) {
  84672. return;
  84673. }
  84674. newPositionData.push(vertex.position.x);
  84675. newPositionData.push(vertex.position.y);
  84676. newPositionData.push(vertex.position.z);
  84677. newNormalData.push(normalData[originalOffset * 3]);
  84678. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  84679. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  84680. if (uvs && uvs.length) {
  84681. newUVsData.push(uvs[(originalOffset * 2)]);
  84682. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  84683. }
  84684. else if (colorsData && colorsData.length) {
  84685. newColorsData.push(colorsData[(originalOffset * 4)]);
  84686. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  84687. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  84688. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  84689. }
  84690. ++vertexCount;
  84691. });
  84692. }
  84693. }
  84694. var startingIndex = this._reconstructedMesh.getTotalIndices();
  84695. var startingVertex = this._reconstructedMesh.getTotalVertices();
  84696. var submeshesArray = this._reconstructedMesh.subMeshes;
  84697. this._reconstructedMesh.subMeshes = [];
  84698. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  84699. var originalIndices = this._mesh.getIndices();
  84700. for (i = 0; i < newTriangles.length; ++i) {
  84701. t = newTriangles[i]; //now get the new referencing point for each vertex
  84702. [0, 1, 2].forEach(function (idx) {
  84703. var id = originalIndices[t.originalOffset + idx];
  84704. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  84705. if (offset < 0)
  84706. offset = 0;
  84707. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  84708. });
  84709. }
  84710. //overwriting the old vertex buffers and indices.
  84711. this._reconstructedMesh.setIndices(newIndicesArray);
  84712. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  84713. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  84714. if (newUVsData.length > 0)
  84715. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  84716. if (newColorsData.length > 0)
  84717. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  84718. //create submesh
  84719. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  84720. if (submeshIndex > 0) {
  84721. this._reconstructedMesh.subMeshes = [];
  84722. submeshesArray.forEach(function (submesh) {
  84723. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  84724. });
  84725. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  84726. }
  84727. };
  84728. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  84729. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  84730. this._reconstructedMesh.material = this._mesh.material;
  84731. this._reconstructedMesh.parent = this._mesh.parent;
  84732. this._reconstructedMesh.isVisible = false;
  84733. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  84734. };
  84735. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  84736. for (var i = 0; i < vertex1.triangleCount; ++i) {
  84737. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  84738. if (t.deleted)
  84739. continue;
  84740. var s = this.references[vertex1.triangleStart + i].vertexId;
  84741. var v1 = t.vertices[(s + 1) % 3];
  84742. var v2 = t.vertices[(s + 2) % 3];
  84743. if ((v1 === vertex2 || v2 === vertex2)) {
  84744. deletedArray[i] = true;
  84745. delTr.push(t);
  84746. continue;
  84747. }
  84748. var d1 = v1.position.subtract(point);
  84749. d1 = d1.normalize();
  84750. var d2 = v2.position.subtract(point);
  84751. d2 = d2.normalize();
  84752. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  84753. return true;
  84754. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  84755. deletedArray[i] = false;
  84756. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  84757. return true;
  84758. }
  84759. return false;
  84760. };
  84761. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  84762. var newDeleted = deletedTriangles;
  84763. for (var i = 0; i < vertex.triangleCount; ++i) {
  84764. var ref = this.references[vertex.triangleStart + i];
  84765. var t = this.triangles[ref.triangleId];
  84766. if (t.deleted)
  84767. continue;
  84768. if (deletedArray[i] && t.deletePending) {
  84769. t.deleted = true;
  84770. newDeleted++;
  84771. continue;
  84772. }
  84773. t.vertices[ref.vertexId] = origVertex;
  84774. t.isDirty = true;
  84775. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  84776. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  84777. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  84778. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  84779. this.references.push(ref);
  84780. }
  84781. return newDeleted;
  84782. };
  84783. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  84784. for (var i = 0; i < this.vertices.length; ++i) {
  84785. var vCount = [];
  84786. var vId = [];
  84787. var v = this.vertices[i];
  84788. var j;
  84789. for (j = 0; j < v.triangleCount; ++j) {
  84790. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  84791. for (var ii = 0; ii < 3; ii++) {
  84792. var ofs = 0;
  84793. var vv = triangle.vertices[ii];
  84794. while (ofs < vCount.length) {
  84795. if (vId[ofs] === vv.id)
  84796. break;
  84797. ++ofs;
  84798. }
  84799. if (ofs === vCount.length) {
  84800. vCount.push(1);
  84801. vId.push(vv.id);
  84802. }
  84803. else {
  84804. vCount[ofs]++;
  84805. }
  84806. }
  84807. }
  84808. for (j = 0; j < vCount.length; ++j) {
  84809. if (vCount[j] === 1) {
  84810. this.vertices[vId[j]].isBorder = true;
  84811. }
  84812. else {
  84813. this.vertices[vId[j]].isBorder = false;
  84814. }
  84815. }
  84816. }
  84817. };
  84818. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  84819. if (identifyBorders === void 0) { identifyBorders = false; }
  84820. var i;
  84821. if (!identifyBorders) {
  84822. var newTrianglesVector = [];
  84823. for (i = 0; i < this.triangles.length; ++i) {
  84824. if (!this.triangles[i].deleted) {
  84825. newTrianglesVector.push(this.triangles[i]);
  84826. }
  84827. }
  84828. this.triangles = newTrianglesVector;
  84829. }
  84830. for (i = 0; i < this.vertices.length; ++i) {
  84831. this.vertices[i].triangleCount = 0;
  84832. this.vertices[i].triangleStart = 0;
  84833. }
  84834. var t;
  84835. var j;
  84836. var v;
  84837. for (i = 0; i < this.triangles.length; ++i) {
  84838. t = this.triangles[i];
  84839. for (j = 0; j < 3; ++j) {
  84840. v = t.vertices[j];
  84841. v.triangleCount++;
  84842. }
  84843. }
  84844. var tStart = 0;
  84845. for (i = 0; i < this.vertices.length; ++i) {
  84846. this.vertices[i].triangleStart = tStart;
  84847. tStart += this.vertices[i].triangleCount;
  84848. this.vertices[i].triangleCount = 0;
  84849. }
  84850. var newReferences = new Array(this.triangles.length * 3);
  84851. for (i = 0; i < this.triangles.length; ++i) {
  84852. t = this.triangles[i];
  84853. for (j = 0; j < 3; ++j) {
  84854. v = t.vertices[j];
  84855. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  84856. v.triangleCount++;
  84857. }
  84858. }
  84859. this.references = newReferences;
  84860. if (identifyBorders) {
  84861. this.identifyBorder();
  84862. }
  84863. };
  84864. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  84865. var x = point.x;
  84866. var y = point.y;
  84867. var z = point.z;
  84868. 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
  84869. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  84870. };
  84871. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  84872. var q = vertex1.q.add(vertex2.q);
  84873. var border = vertex1.isBorder && vertex2.isBorder;
  84874. var error = 0;
  84875. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  84876. if (qDet !== 0 && !border) {
  84877. if (!pointResult) {
  84878. pointResult = BABYLON.Vector3.Zero();
  84879. }
  84880. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  84881. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  84882. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  84883. error = this.vertexError(q, pointResult);
  84884. }
  84885. else {
  84886. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  84887. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  84888. var error1 = this.vertexError(q, vertex1.position);
  84889. var error2 = this.vertexError(q, vertex2.position);
  84890. var error3 = this.vertexError(q, p3);
  84891. error = Math.min(error1, error2, error3);
  84892. if (error === error1) {
  84893. if (pointResult) {
  84894. pointResult.copyFrom(vertex1.position);
  84895. }
  84896. }
  84897. else if (error === error2) {
  84898. if (pointResult) {
  84899. pointResult.copyFrom(vertex2.position);
  84900. }
  84901. }
  84902. else {
  84903. if (pointResult) {
  84904. pointResult.copyFrom(p3);
  84905. }
  84906. }
  84907. }
  84908. return error;
  84909. };
  84910. return QuadraticErrorSimplification;
  84911. }());
  84912. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  84913. })(BABYLON || (BABYLON = {}));
  84914. //# sourceMappingURL=babylon.meshSimplification.js.map
  84915. "use strict";
  84916. var BABYLON;
  84917. (function (BABYLON) {
  84918. var MeshLODLevel = /** @class */ (function () {
  84919. function MeshLODLevel(distance, mesh) {
  84920. this.distance = distance;
  84921. this.mesh = mesh;
  84922. }
  84923. return MeshLODLevel;
  84924. }());
  84925. BABYLON.MeshLODLevel = MeshLODLevel;
  84926. })(BABYLON || (BABYLON = {}));
  84927. //# sourceMappingURL=babylon.meshLODLevel.js.map
  84928. "use strict";
  84929. var BABYLON;
  84930. (function (BABYLON) {
  84931. /**
  84932. * Defines the root class used to create scene optimization to use with SceneOptimizer
  84933. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84934. */
  84935. var SceneOptimization = /** @class */ (function () {
  84936. /**
  84937. * Creates the SceneOptimization object
  84938. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84939. * @param desc defines the description associated with the optimization
  84940. */
  84941. function SceneOptimization(
  84942. /**
  84943. * Defines the priority of this optimization (0 by default which means first in the list)
  84944. */
  84945. priority) {
  84946. if (priority === void 0) { priority = 0; }
  84947. this.priority = priority;
  84948. }
  84949. /**
  84950. * Gets a string describing the action executed by the current optimization
  84951. * @returns description string
  84952. */
  84953. SceneOptimization.prototype.getDescription = function () {
  84954. return "";
  84955. };
  84956. /**
  84957. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84958. * @param scene defines the current scene where to apply this optimization
  84959. * @param optimizer defines the current optimizer
  84960. * @returns true if everything that can be done was applied
  84961. */
  84962. SceneOptimization.prototype.apply = function (scene, optimizer) {
  84963. return true;
  84964. };
  84965. ;
  84966. return SceneOptimization;
  84967. }());
  84968. BABYLON.SceneOptimization = SceneOptimization;
  84969. /**
  84970. * Defines an optimization used to reduce the size of render target textures
  84971. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84972. */
  84973. var TextureOptimization = /** @class */ (function (_super) {
  84974. __extends(TextureOptimization, _super);
  84975. /**
  84976. * Creates the TextureOptimization object
  84977. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84978. * @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
  84979. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  84980. */
  84981. function TextureOptimization(
  84982. /**
  84983. * Defines the priority of this optimization (0 by default which means first in the list)
  84984. */
  84985. priority,
  84986. /**
  84987. * 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
  84988. */
  84989. maximumSize,
  84990. /**
  84991. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  84992. */
  84993. step) {
  84994. if (priority === void 0) { priority = 0; }
  84995. if (maximumSize === void 0) { maximumSize = 1024; }
  84996. if (step === void 0) { step = 0.5; }
  84997. var _this = _super.call(this, priority) || this;
  84998. _this.priority = priority;
  84999. _this.maximumSize = maximumSize;
  85000. _this.step = step;
  85001. return _this;
  85002. }
  85003. /**
  85004. * Gets a string describing the action executed by the current optimization
  85005. * @returns description string
  85006. */
  85007. TextureOptimization.prototype.getDescription = function () {
  85008. return "Reducing render target texture size to " + this.maximumSize;
  85009. };
  85010. /**
  85011. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85012. * @param scene defines the current scene where to apply this optimization
  85013. * @param optimizer defines the current optimizer
  85014. * @returns true if everything that can be done was applied
  85015. */
  85016. TextureOptimization.prototype.apply = function (scene, optimizer) {
  85017. var allDone = true;
  85018. for (var index = 0; index < scene.textures.length; index++) {
  85019. var texture = scene.textures[index];
  85020. if (!texture.canRescale || texture.getContext) {
  85021. continue;
  85022. }
  85023. var currentSize = texture.getSize();
  85024. var maxDimension = Math.max(currentSize.width, currentSize.height);
  85025. if (maxDimension > this.maximumSize) {
  85026. texture.scale(this.step);
  85027. allDone = false;
  85028. }
  85029. }
  85030. return allDone;
  85031. };
  85032. return TextureOptimization;
  85033. }(SceneOptimization));
  85034. BABYLON.TextureOptimization = TextureOptimization;
  85035. /**
  85036. * Defines an optimization used to increase or decrease the rendering resolution
  85037. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85038. */
  85039. var HardwareScalingOptimization = /** @class */ (function (_super) {
  85040. __extends(HardwareScalingOptimization, _super);
  85041. /**
  85042. * Creates the HardwareScalingOptimization object
  85043. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85044. * @param maximumScale defines the maximum scale to use (2 by default)
  85045. * @param step defines the step to use between two passes (0.5 by default)
  85046. */
  85047. function HardwareScalingOptimization(
  85048. /**
  85049. * Defines the priority of this optimization (0 by default which means first in the list)
  85050. */
  85051. priority,
  85052. /**
  85053. * Defines the maximum scale to use (2 by default)
  85054. */
  85055. maximumScale,
  85056. /**
  85057. * Defines the step to use between two passes (0.5 by default)
  85058. */
  85059. step) {
  85060. if (priority === void 0) { priority = 0; }
  85061. if (maximumScale === void 0) { maximumScale = 2; }
  85062. if (step === void 0) { step = 0.25; }
  85063. var _this = _super.call(this, priority) || this;
  85064. _this.priority = priority;
  85065. _this.maximumScale = maximumScale;
  85066. _this.step = step;
  85067. _this._currentScale = -1;
  85068. _this._directionOffset = 1;
  85069. return _this;
  85070. }
  85071. /**
  85072. * Gets a string describing the action executed by the current optimization
  85073. * @return description string
  85074. */
  85075. HardwareScalingOptimization.prototype.getDescription = function () {
  85076. return "Setting hardware scaling level to " + this._currentScale;
  85077. };
  85078. /**
  85079. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85080. * @param scene defines the current scene where to apply this optimization
  85081. * @param optimizer defines the current optimizer
  85082. * @returns true if everything that can be done was applied
  85083. */
  85084. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  85085. if (this._currentScale === -1) {
  85086. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  85087. if (this._currentScale > this.maximumScale) {
  85088. this._directionOffset = -1;
  85089. }
  85090. }
  85091. this._currentScale += this._directionOffset * this.step;
  85092. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  85093. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  85094. };
  85095. ;
  85096. return HardwareScalingOptimization;
  85097. }(SceneOptimization));
  85098. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  85099. /**
  85100. * Defines an optimization used to remove shadows
  85101. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85102. */
  85103. var ShadowsOptimization = /** @class */ (function (_super) {
  85104. __extends(ShadowsOptimization, _super);
  85105. function ShadowsOptimization() {
  85106. return _super !== null && _super.apply(this, arguments) || this;
  85107. }
  85108. /**
  85109. * Gets a string describing the action executed by the current optimization
  85110. * @return description string
  85111. */
  85112. ShadowsOptimization.prototype.getDescription = function () {
  85113. return "Turning shadows on/off";
  85114. };
  85115. /**
  85116. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85117. * @param scene defines the current scene where to apply this optimization
  85118. * @param optimizer defines the current optimizer
  85119. * @returns true if everything that can be done was applied
  85120. */
  85121. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  85122. scene.shadowsEnabled = optimizer.isInImprovementMode;
  85123. return true;
  85124. };
  85125. ;
  85126. return ShadowsOptimization;
  85127. }(SceneOptimization));
  85128. BABYLON.ShadowsOptimization = ShadowsOptimization;
  85129. /**
  85130. * Defines an optimization used to turn post-processes off
  85131. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85132. */
  85133. var PostProcessesOptimization = /** @class */ (function (_super) {
  85134. __extends(PostProcessesOptimization, _super);
  85135. function PostProcessesOptimization() {
  85136. return _super !== null && _super.apply(this, arguments) || this;
  85137. }
  85138. /**
  85139. * Gets a string describing the action executed by the current optimization
  85140. * @return description string
  85141. */
  85142. PostProcessesOptimization.prototype.getDescription = function () {
  85143. return "Turning post-processes on/off";
  85144. };
  85145. /**
  85146. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85147. * @param scene defines the current scene where to apply this optimization
  85148. * @param optimizer defines the current optimizer
  85149. * @returns true if everything that can be done was applied
  85150. */
  85151. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  85152. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  85153. return true;
  85154. };
  85155. ;
  85156. return PostProcessesOptimization;
  85157. }(SceneOptimization));
  85158. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  85159. /**
  85160. * Defines an optimization used to turn lens flares off
  85161. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85162. */
  85163. var LensFlaresOptimization = /** @class */ (function (_super) {
  85164. __extends(LensFlaresOptimization, _super);
  85165. function LensFlaresOptimization() {
  85166. return _super !== null && _super.apply(this, arguments) || this;
  85167. }
  85168. /**
  85169. * Gets a string describing the action executed by the current optimization
  85170. * @return description string
  85171. */
  85172. LensFlaresOptimization.prototype.getDescription = function () {
  85173. return "Turning lens flares on/off";
  85174. };
  85175. /**
  85176. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85177. * @param scene defines the current scene where to apply this optimization
  85178. * @param optimizer defines the current optimizer
  85179. * @returns true if everything that can be done was applied
  85180. */
  85181. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  85182. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  85183. return true;
  85184. };
  85185. ;
  85186. return LensFlaresOptimization;
  85187. }(SceneOptimization));
  85188. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  85189. /**
  85190. * Defines an optimization based on user defined callback.
  85191. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85192. */
  85193. var CustomOptimization = /** @class */ (function (_super) {
  85194. __extends(CustomOptimization, _super);
  85195. function CustomOptimization() {
  85196. return _super !== null && _super.apply(this, arguments) || this;
  85197. }
  85198. /**
  85199. * Gets a string describing the action executed by the current optimization
  85200. * @returns description string
  85201. */
  85202. CustomOptimization.prototype.getDescription = function () {
  85203. if (this.onGetDescription) {
  85204. return this.onGetDescription();
  85205. }
  85206. return "Running user defined callback";
  85207. };
  85208. /**
  85209. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85210. * @param scene defines the current scene where to apply this optimization
  85211. * @param optimizer defines the current optimizer
  85212. * @returns true if everything that can be done was applied
  85213. */
  85214. CustomOptimization.prototype.apply = function (scene, optimizer) {
  85215. if (this.onApply) {
  85216. return this.onApply(scene, optimizer);
  85217. }
  85218. return true;
  85219. };
  85220. ;
  85221. return CustomOptimization;
  85222. }(SceneOptimization));
  85223. BABYLON.CustomOptimization = CustomOptimization;
  85224. /**
  85225. * Defines an optimization used to turn particles off
  85226. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85227. */
  85228. var ParticlesOptimization = /** @class */ (function (_super) {
  85229. __extends(ParticlesOptimization, _super);
  85230. function ParticlesOptimization() {
  85231. return _super !== null && _super.apply(this, arguments) || this;
  85232. }
  85233. /**
  85234. * Gets a string describing the action executed by the current optimization
  85235. * @return description string
  85236. */
  85237. ParticlesOptimization.prototype.getDescription = function () {
  85238. return "Turning particles on/off";
  85239. };
  85240. /**
  85241. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85242. * @param scene defines the current scene where to apply this optimization
  85243. * @param optimizer defines the current optimizer
  85244. * @returns true if everything that can be done was applied
  85245. */
  85246. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  85247. scene.particlesEnabled = optimizer.isInImprovementMode;
  85248. return true;
  85249. };
  85250. ;
  85251. return ParticlesOptimization;
  85252. }(SceneOptimization));
  85253. BABYLON.ParticlesOptimization = ParticlesOptimization;
  85254. /**
  85255. * Defines an optimization used to turn render targets off
  85256. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85257. */
  85258. var RenderTargetsOptimization = /** @class */ (function (_super) {
  85259. __extends(RenderTargetsOptimization, _super);
  85260. function RenderTargetsOptimization() {
  85261. return _super !== null && _super.apply(this, arguments) || this;
  85262. }
  85263. /**
  85264. * Gets a string describing the action executed by the current optimization
  85265. * @return description string
  85266. */
  85267. RenderTargetsOptimization.prototype.getDescription = function () {
  85268. return "Turning render targets off";
  85269. };
  85270. /**
  85271. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85272. * @param scene defines the current scene where to apply this optimization
  85273. * @param optimizer defines the current optimizer
  85274. * @returns true if everything that can be done was applied
  85275. */
  85276. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  85277. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  85278. return true;
  85279. };
  85280. ;
  85281. return RenderTargetsOptimization;
  85282. }(SceneOptimization));
  85283. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  85284. /**
  85285. * Defines an optimization used to merge meshes with compatible materials
  85286. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85287. */
  85288. var MergeMeshesOptimization = /** @class */ (function (_super) {
  85289. __extends(MergeMeshesOptimization, _super);
  85290. function MergeMeshesOptimization() {
  85291. var _this = _super !== null && _super.apply(this, arguments) || this;
  85292. _this._canBeMerged = function (abstractMesh) {
  85293. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  85294. return false;
  85295. }
  85296. var mesh = abstractMesh;
  85297. if (!mesh.isVisible || !mesh.isEnabled()) {
  85298. return false;
  85299. }
  85300. if (mesh.instances.length > 0) {
  85301. return false;
  85302. }
  85303. if (mesh.skeleton || mesh.hasLODLevels) {
  85304. return false;
  85305. }
  85306. if (mesh.parent) {
  85307. return false;
  85308. }
  85309. return true;
  85310. };
  85311. return _this;
  85312. }
  85313. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  85314. /**
  85315. * Gets or sets a boolean which defines if optimization octree has to be updated
  85316. */
  85317. get: function () {
  85318. return MergeMeshesOptimization._UpdateSelectionTree;
  85319. },
  85320. /**
  85321. * Gets or sets a boolean which defines if optimization octree has to be updated
  85322. */
  85323. set: function (value) {
  85324. MergeMeshesOptimization._UpdateSelectionTree = value;
  85325. },
  85326. enumerable: true,
  85327. configurable: true
  85328. });
  85329. /**
  85330. * Gets a string describing the action executed by the current optimization
  85331. * @return description string
  85332. */
  85333. MergeMeshesOptimization.prototype.getDescription = function () {
  85334. return "Merging similar meshes together";
  85335. };
  85336. /**
  85337. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85338. * @param scene defines the current scene where to apply this optimization
  85339. * @param optimizer defines the current optimizer
  85340. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  85341. * @returns true if everything that can be done was applied
  85342. */
  85343. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  85344. var globalPool = scene.meshes.slice(0);
  85345. var globalLength = globalPool.length;
  85346. for (var index = 0; index < globalLength; index++) {
  85347. var currentPool = new Array();
  85348. var current = globalPool[index];
  85349. // Checks
  85350. if (!this._canBeMerged(current)) {
  85351. continue;
  85352. }
  85353. currentPool.push(current);
  85354. // Find compatible meshes
  85355. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  85356. var otherMesh = globalPool[subIndex];
  85357. if (!this._canBeMerged(otherMesh)) {
  85358. continue;
  85359. }
  85360. if (otherMesh.material !== current.material) {
  85361. continue;
  85362. }
  85363. if (otherMesh.checkCollisions !== current.checkCollisions) {
  85364. continue;
  85365. }
  85366. currentPool.push(otherMesh);
  85367. globalLength--;
  85368. globalPool.splice(subIndex, 1);
  85369. subIndex--;
  85370. }
  85371. if (currentPool.length < 2) {
  85372. continue;
  85373. }
  85374. // Merge meshes
  85375. BABYLON.Mesh.MergeMeshes(currentPool);
  85376. }
  85377. if (updateSelectionTree != undefined) {
  85378. if (updateSelectionTree) {
  85379. scene.createOrUpdateSelectionOctree();
  85380. }
  85381. }
  85382. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  85383. scene.createOrUpdateSelectionOctree();
  85384. }
  85385. return true;
  85386. };
  85387. ;
  85388. MergeMeshesOptimization._UpdateSelectionTree = false;
  85389. return MergeMeshesOptimization;
  85390. }(SceneOptimization));
  85391. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  85392. /**
  85393. * Defines a list of options used by SceneOptimizer
  85394. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85395. */
  85396. var SceneOptimizerOptions = /** @class */ (function () {
  85397. /**
  85398. * Creates a new list of options used by SceneOptimizer
  85399. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  85400. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  85401. */
  85402. function SceneOptimizerOptions(
  85403. /**
  85404. * Defines the target frame rate to reach (60 by default)
  85405. */
  85406. targetFrameRate,
  85407. /**
  85408. * Defines the interval between two checkes (2000ms by default)
  85409. */
  85410. trackerDuration) {
  85411. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  85412. if (trackerDuration === void 0) { trackerDuration = 2000; }
  85413. this.targetFrameRate = targetFrameRate;
  85414. this.trackerDuration = trackerDuration;
  85415. /**
  85416. * Gets the list of optimizations to apply
  85417. */
  85418. this.optimizations = new Array();
  85419. }
  85420. /**
  85421. * Add a new optimization
  85422. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  85423. * @returns the current SceneOptimizerOptions
  85424. */
  85425. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  85426. this.optimizations.push(optimization);
  85427. return this;
  85428. };
  85429. /**
  85430. * Add a new custom optimization
  85431. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  85432. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  85433. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85434. * @returns the current SceneOptimizerOptions
  85435. */
  85436. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  85437. if (priority === void 0) { priority = 0; }
  85438. var optimization = new CustomOptimization(priority);
  85439. optimization.onApply = onApply;
  85440. optimization.onGetDescription = onGetDescription;
  85441. this.optimizations.push(optimization);
  85442. return this;
  85443. };
  85444. /**
  85445. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  85446. * @param targetFrameRate defines the target frame rate (60 by default)
  85447. * @returns a SceneOptimizerOptions object
  85448. */
  85449. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  85450. var result = new SceneOptimizerOptions(targetFrameRate);
  85451. var priority = 0;
  85452. result.addOptimization(new MergeMeshesOptimization(priority));
  85453. result.addOptimization(new ShadowsOptimization(priority));
  85454. result.addOptimization(new LensFlaresOptimization(priority));
  85455. // Next priority
  85456. priority++;
  85457. result.addOptimization(new PostProcessesOptimization(priority));
  85458. result.addOptimization(new ParticlesOptimization(priority));
  85459. // Next priority
  85460. priority++;
  85461. result.addOptimization(new TextureOptimization(priority, 1024));
  85462. return result;
  85463. };
  85464. /**
  85465. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  85466. * @param targetFrameRate defines the target frame rate (60 by default)
  85467. * @returns a SceneOptimizerOptions object
  85468. */
  85469. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  85470. var result = new SceneOptimizerOptions(targetFrameRate);
  85471. var priority = 0;
  85472. result.addOptimization(new MergeMeshesOptimization(priority));
  85473. result.addOptimization(new ShadowsOptimization(priority));
  85474. result.addOptimization(new LensFlaresOptimization(priority));
  85475. // Next priority
  85476. priority++;
  85477. result.addOptimization(new PostProcessesOptimization(priority));
  85478. result.addOptimization(new ParticlesOptimization(priority));
  85479. // Next priority
  85480. priority++;
  85481. result.addOptimization(new TextureOptimization(priority, 512));
  85482. // Next priority
  85483. priority++;
  85484. result.addOptimization(new RenderTargetsOptimization(priority));
  85485. // Next priority
  85486. priority++;
  85487. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  85488. return result;
  85489. };
  85490. /**
  85491. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  85492. * @param targetFrameRate defines the target frame rate (60 by default)
  85493. * @returns a SceneOptimizerOptions object
  85494. */
  85495. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  85496. var result = new SceneOptimizerOptions(targetFrameRate);
  85497. var priority = 0;
  85498. result.addOptimization(new MergeMeshesOptimization(priority));
  85499. result.addOptimization(new ShadowsOptimization(priority));
  85500. result.addOptimization(new LensFlaresOptimization(priority));
  85501. // Next priority
  85502. priority++;
  85503. result.addOptimization(new PostProcessesOptimization(priority));
  85504. result.addOptimization(new ParticlesOptimization(priority));
  85505. // Next priority
  85506. priority++;
  85507. result.addOptimization(new TextureOptimization(priority, 256));
  85508. // Next priority
  85509. priority++;
  85510. result.addOptimization(new RenderTargetsOptimization(priority));
  85511. // Next priority
  85512. priority++;
  85513. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  85514. return result;
  85515. };
  85516. return SceneOptimizerOptions;
  85517. }());
  85518. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  85519. /**
  85520. * Class used to run optimizations in order to reach a target frame rate
  85521. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85522. */
  85523. var SceneOptimizer = /** @class */ (function () {
  85524. /**
  85525. * Creates a new SceneOptimizer
  85526. * @param scene defines the scene to work on
  85527. * @param options defines the options to use with the SceneOptimizer
  85528. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  85529. * @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)
  85530. */
  85531. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  85532. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  85533. if (improvementMode === void 0) { improvementMode = false; }
  85534. var _this = this;
  85535. this._isRunning = false;
  85536. this._currentPriorityLevel = 0;
  85537. this._targetFrameRate = 60;
  85538. this._trackerDuration = 2000;
  85539. this._currentFrameRate = 0;
  85540. this._improvementMode = false;
  85541. /**
  85542. * Defines an observable called when the optimizer reaches the target frame rate
  85543. */
  85544. this.onSuccessObservable = new BABYLON.Observable();
  85545. /**
  85546. * Defines an observable called when the optimizer enables an optimization
  85547. */
  85548. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  85549. /**
  85550. * Defines an observable called when the optimizer is not able to reach the target frame rate
  85551. */
  85552. this.onFailureObservable = new BABYLON.Observable();
  85553. if (!options) {
  85554. this._options = new SceneOptimizerOptions();
  85555. }
  85556. else {
  85557. this._options = options;
  85558. }
  85559. if (this._options.targetFrameRate) {
  85560. this._targetFrameRate = this._options.targetFrameRate;
  85561. }
  85562. if (this._options.trackerDuration) {
  85563. this._trackerDuration = this._options.trackerDuration;
  85564. }
  85565. if (autoGeneratePriorities) {
  85566. var priority = 0;
  85567. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  85568. var optim = _a[_i];
  85569. optim.priority = priority++;
  85570. }
  85571. }
  85572. this._improvementMode = improvementMode;
  85573. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85574. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  85575. _this._sceneDisposeObserver = null;
  85576. _this.dispose();
  85577. });
  85578. }
  85579. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  85580. /**
  85581. * Gets a boolean indicating if the optimizer is in improvement mode
  85582. */
  85583. get: function () {
  85584. return this._improvementMode;
  85585. },
  85586. enumerable: true,
  85587. configurable: true
  85588. });
  85589. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  85590. /**
  85591. * Gets the current priority level (0 at start)
  85592. */
  85593. get: function () {
  85594. return this._currentPriorityLevel;
  85595. },
  85596. enumerable: true,
  85597. configurable: true
  85598. });
  85599. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  85600. /**
  85601. * Gets the current frame rate checked by the SceneOptimizer
  85602. */
  85603. get: function () {
  85604. return this._currentFrameRate;
  85605. },
  85606. enumerable: true,
  85607. configurable: true
  85608. });
  85609. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  85610. /**
  85611. * Gets or sets the current target frame rate (60 by default)
  85612. */
  85613. get: function () {
  85614. return this._targetFrameRate;
  85615. },
  85616. /**
  85617. * Gets or sets the current target frame rate (60 by default)
  85618. */
  85619. set: function (value) {
  85620. this._targetFrameRate = value;
  85621. },
  85622. enumerable: true,
  85623. configurable: true
  85624. });
  85625. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  85626. /**
  85627. * Gets or sets the current interval between two checks (every 2000ms by default)
  85628. */
  85629. get: function () {
  85630. return this._trackerDuration;
  85631. },
  85632. /**
  85633. * Gets or sets the current interval between two checks (every 2000ms by default)
  85634. */
  85635. set: function (value) {
  85636. this._trackerDuration = value;
  85637. },
  85638. enumerable: true,
  85639. configurable: true
  85640. });
  85641. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  85642. /**
  85643. * Gets the list of active optimizations
  85644. */
  85645. get: function () {
  85646. return this._options.optimizations;
  85647. },
  85648. enumerable: true,
  85649. configurable: true
  85650. });
  85651. /**
  85652. * Stops the current optimizer
  85653. */
  85654. SceneOptimizer.prototype.stop = function () {
  85655. this._isRunning = false;
  85656. };
  85657. /**
  85658. * Reset the optimizer to initial step (current priority level = 0)
  85659. */
  85660. SceneOptimizer.prototype.reset = function () {
  85661. this._currentPriorityLevel = 0;
  85662. };
  85663. /**
  85664. * Start the optimizer. By default it will try to reach a specific framerate
  85665. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  85666. */
  85667. SceneOptimizer.prototype.start = function () {
  85668. var _this = this;
  85669. if (this._isRunning) {
  85670. return;
  85671. }
  85672. this._isRunning = true;
  85673. // Let's wait for the scene to be ready before running our check
  85674. this._scene.executeWhenReady(function () {
  85675. setTimeout(function () {
  85676. _this._checkCurrentState();
  85677. }, _this._trackerDuration);
  85678. });
  85679. };
  85680. SceneOptimizer.prototype._checkCurrentState = function () {
  85681. var _this = this;
  85682. if (!this._isRunning) {
  85683. return;
  85684. }
  85685. var scene = this._scene;
  85686. var options = this._options;
  85687. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  85688. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  85689. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  85690. this._isRunning = false;
  85691. this.onSuccessObservable.notifyObservers(this);
  85692. return;
  85693. }
  85694. // Apply current level of optimizations
  85695. var allDone = true;
  85696. var noOptimizationApplied = true;
  85697. for (var index = 0; index < options.optimizations.length; index++) {
  85698. var optimization = options.optimizations[index];
  85699. if (optimization.priority === this._currentPriorityLevel) {
  85700. noOptimizationApplied = false;
  85701. allDone = allDone && optimization.apply(scene, this);
  85702. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  85703. }
  85704. }
  85705. // If no optimization was applied, this is a failure :(
  85706. if (noOptimizationApplied) {
  85707. this._isRunning = false;
  85708. this.onFailureObservable.notifyObservers(this);
  85709. return;
  85710. }
  85711. // If all optimizations were done, move to next level
  85712. if (allDone) {
  85713. this._currentPriorityLevel++;
  85714. }
  85715. // Let's the system running for a specific amount of time before checking FPS
  85716. scene.executeWhenReady(function () {
  85717. setTimeout(function () {
  85718. _this._checkCurrentState();
  85719. }, _this._trackerDuration);
  85720. });
  85721. };
  85722. /**
  85723. * Release all resources
  85724. */
  85725. SceneOptimizer.prototype.dispose = function () {
  85726. this.stop();
  85727. this.onSuccessObservable.clear();
  85728. this.onFailureObservable.clear();
  85729. this.onNewOptimizationAppliedObservable.clear();
  85730. if (this._sceneDisposeObserver) {
  85731. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  85732. }
  85733. };
  85734. /**
  85735. * Helper function to create a SceneOptimizer with one single line of code
  85736. * @param scene defines the scene to work on
  85737. * @param options defines the options to use with the SceneOptimizer
  85738. * @param onSuccess defines a callback to call on success
  85739. * @param onFailure defines a callback to call on failure
  85740. * @returns the new SceneOptimizer object
  85741. */
  85742. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  85743. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  85744. if (onSuccess) {
  85745. optimizer.onSuccessObservable.add(function () {
  85746. onSuccess();
  85747. });
  85748. }
  85749. if (onFailure) {
  85750. optimizer.onFailureObservable.add(function () {
  85751. onFailure();
  85752. });
  85753. }
  85754. optimizer.start();
  85755. return optimizer;
  85756. };
  85757. return SceneOptimizer;
  85758. }());
  85759. BABYLON.SceneOptimizer = SceneOptimizer;
  85760. })(BABYLON || (BABYLON = {}));
  85761. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  85762. "use strict";
  85763. var BABYLON;
  85764. (function (BABYLON) {
  85765. var OutlineRenderer = /** @class */ (function () {
  85766. function OutlineRenderer(scene) {
  85767. this.zOffset = 1;
  85768. this._scene = scene;
  85769. }
  85770. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  85771. var _this = this;
  85772. if (useOverlay === void 0) { useOverlay = false; }
  85773. var scene = this._scene;
  85774. var engine = this._scene.getEngine();
  85775. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  85776. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  85777. return;
  85778. }
  85779. var mesh = subMesh.getRenderingMesh();
  85780. var material = subMesh.getMaterial();
  85781. if (!material || !scene.activeCamera) {
  85782. return;
  85783. }
  85784. engine.enableEffect(this._effect);
  85785. // Logarithmic depth
  85786. if (material.useLogarithmicDepth) {
  85787. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  85788. }
  85789. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  85790. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  85791. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  85792. // Bones
  85793. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  85794. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  85795. }
  85796. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  85797. // Alpha test
  85798. if (material && material.needAlphaTesting()) {
  85799. var alphaTexture = material.getAlphaTestTexture();
  85800. if (alphaTexture) {
  85801. this._effect.setTexture("diffuseSampler", alphaTexture);
  85802. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  85803. }
  85804. }
  85805. engine.setZOffset(-this.zOffset);
  85806. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  85807. engine.setZOffset(0);
  85808. };
  85809. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  85810. var defines = [];
  85811. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  85812. var mesh = subMesh.getMesh();
  85813. var material = subMesh.getMaterial();
  85814. if (material) {
  85815. // Alpha test
  85816. if (material.needAlphaTesting()) {
  85817. defines.push("#define ALPHATEST");
  85818. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  85819. attribs.push(BABYLON.VertexBuffer.UVKind);
  85820. defines.push("#define UV1");
  85821. }
  85822. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  85823. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  85824. defines.push("#define UV2");
  85825. }
  85826. }
  85827. //Logarithmic depth
  85828. if (material.useLogarithmicDepth) {
  85829. defines.push("#define LOGARITHMICDEPTH");
  85830. }
  85831. }
  85832. // Bones
  85833. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  85834. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  85835. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  85836. if (mesh.numBoneInfluencers > 4) {
  85837. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  85838. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  85839. }
  85840. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  85841. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  85842. }
  85843. else {
  85844. defines.push("#define NUM_BONE_INFLUENCERS 0");
  85845. }
  85846. // Instances
  85847. if (useInstances) {
  85848. defines.push("#define INSTANCES");
  85849. attribs.push("world0");
  85850. attribs.push("world1");
  85851. attribs.push("world2");
  85852. attribs.push("world3");
  85853. }
  85854. // Get correct effect
  85855. var join = defines.join("\n");
  85856. if (this._cachedDefines !== join) {
  85857. this._cachedDefines = join;
  85858. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  85859. }
  85860. return this._effect.isReady();
  85861. };
  85862. return OutlineRenderer;
  85863. }());
  85864. BABYLON.OutlineRenderer = OutlineRenderer;
  85865. })(BABYLON || (BABYLON = {}));
  85866. //# sourceMappingURL=babylon.outlineRenderer.js.map
  85867. "use strict";
  85868. var BABYLON;
  85869. (function (BABYLON) {
  85870. var FaceAdjacencies = /** @class */ (function () {
  85871. function FaceAdjacencies() {
  85872. this.edges = new Array();
  85873. this.edgesConnectedCount = 0;
  85874. }
  85875. return FaceAdjacencies;
  85876. }());
  85877. var EdgesRenderer = /** @class */ (function () {
  85878. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  85879. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  85880. if (epsilon === void 0) { epsilon = 0.95; }
  85881. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  85882. this.edgesWidthScalerForOrthographic = 1000.0;
  85883. this.edgesWidthScalerForPerspective = 50.0;
  85884. this._linesPositions = new Array();
  85885. this._linesNormals = new Array();
  85886. this._linesIndices = new Array();
  85887. this._buffers = {};
  85888. this._checkVerticesInsteadOfIndices = false;
  85889. this._source = source;
  85890. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  85891. this._epsilon = epsilon;
  85892. this._prepareRessources();
  85893. this._generateEdgesLines();
  85894. }
  85895. EdgesRenderer.prototype._prepareRessources = function () {
  85896. if (this._lineShader) {
  85897. return;
  85898. }
  85899. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  85900. attributes: ["position", "normal"],
  85901. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  85902. });
  85903. this._lineShader.disableDepthWrite = true;
  85904. this._lineShader.backFaceCulling = false;
  85905. };
  85906. EdgesRenderer.prototype._rebuild = function () {
  85907. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  85908. if (buffer) {
  85909. buffer._rebuild();
  85910. }
  85911. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  85912. if (buffer) {
  85913. buffer._rebuild();
  85914. }
  85915. var scene = this._source.getScene();
  85916. var engine = scene.getEngine();
  85917. this._ib = engine.createIndexBuffer(this._linesIndices);
  85918. };
  85919. EdgesRenderer.prototype.dispose = function () {
  85920. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  85921. if (buffer) {
  85922. buffer.dispose();
  85923. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  85924. }
  85925. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  85926. if (buffer) {
  85927. buffer.dispose();
  85928. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  85929. }
  85930. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  85931. this._lineShader.dispose();
  85932. };
  85933. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  85934. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  85935. return 0;
  85936. }
  85937. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  85938. return 1;
  85939. }
  85940. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  85941. return 2;
  85942. }
  85943. return -1;
  85944. };
  85945. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  85946. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  85947. return 0;
  85948. }
  85949. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  85950. return 1;
  85951. }
  85952. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  85953. return 2;
  85954. }
  85955. return -1;
  85956. };
  85957. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  85958. var needToCreateLine;
  85959. if (edge === undefined) {
  85960. needToCreateLine = true;
  85961. }
  85962. else {
  85963. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  85964. needToCreateLine = dotProduct < this._epsilon;
  85965. }
  85966. if (needToCreateLine) {
  85967. var offset = this._linesPositions.length / 3;
  85968. var normal = p0.subtract(p1);
  85969. normal.normalize();
  85970. // Positions
  85971. this._linesPositions.push(p0.x);
  85972. this._linesPositions.push(p0.y);
  85973. this._linesPositions.push(p0.z);
  85974. this._linesPositions.push(p0.x);
  85975. this._linesPositions.push(p0.y);
  85976. this._linesPositions.push(p0.z);
  85977. this._linesPositions.push(p1.x);
  85978. this._linesPositions.push(p1.y);
  85979. this._linesPositions.push(p1.z);
  85980. this._linesPositions.push(p1.x);
  85981. this._linesPositions.push(p1.y);
  85982. this._linesPositions.push(p1.z);
  85983. // Normals
  85984. this._linesNormals.push(p1.x);
  85985. this._linesNormals.push(p1.y);
  85986. this._linesNormals.push(p1.z);
  85987. this._linesNormals.push(-1);
  85988. this._linesNormals.push(p1.x);
  85989. this._linesNormals.push(p1.y);
  85990. this._linesNormals.push(p1.z);
  85991. this._linesNormals.push(1);
  85992. this._linesNormals.push(p0.x);
  85993. this._linesNormals.push(p0.y);
  85994. this._linesNormals.push(p0.z);
  85995. this._linesNormals.push(-1);
  85996. this._linesNormals.push(p0.x);
  85997. this._linesNormals.push(p0.y);
  85998. this._linesNormals.push(p0.z);
  85999. this._linesNormals.push(1);
  86000. // Indices
  86001. this._linesIndices.push(offset);
  86002. this._linesIndices.push(offset + 1);
  86003. this._linesIndices.push(offset + 2);
  86004. this._linesIndices.push(offset);
  86005. this._linesIndices.push(offset + 2);
  86006. this._linesIndices.push(offset + 3);
  86007. }
  86008. };
  86009. EdgesRenderer.prototype._generateEdgesLines = function () {
  86010. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  86011. var indices = this._source.getIndices();
  86012. if (!indices || !positions) {
  86013. return;
  86014. }
  86015. // First let's find adjacencies
  86016. var adjacencies = new Array();
  86017. var faceNormals = new Array();
  86018. var index;
  86019. var faceAdjacencies;
  86020. // Prepare faces
  86021. for (index = 0; index < indices.length; index += 3) {
  86022. faceAdjacencies = new FaceAdjacencies();
  86023. var p0Index = indices[index];
  86024. var p1Index = indices[index + 1];
  86025. var p2Index = indices[index + 2];
  86026. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  86027. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  86028. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  86029. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  86030. faceNormal.normalize();
  86031. faceNormals.push(faceNormal);
  86032. adjacencies.push(faceAdjacencies);
  86033. }
  86034. // Scan
  86035. for (index = 0; index < adjacencies.length; index++) {
  86036. faceAdjacencies = adjacencies[index];
  86037. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  86038. var otherFaceAdjacencies = adjacencies[otherIndex];
  86039. if (faceAdjacencies.edgesConnectedCount === 3) {
  86040. break;
  86041. }
  86042. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  86043. continue;
  86044. }
  86045. var otherP0 = indices[otherIndex * 3];
  86046. var otherP1 = indices[otherIndex * 3 + 1];
  86047. var otherP2 = indices[otherIndex * 3 + 2];
  86048. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  86049. var otherEdgeIndex = 0;
  86050. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  86051. continue;
  86052. }
  86053. switch (edgeIndex) {
  86054. case 0:
  86055. if (this._checkVerticesInsteadOfIndices) {
  86056. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  86057. }
  86058. else {
  86059. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  86060. }
  86061. break;
  86062. case 1:
  86063. if (this._checkVerticesInsteadOfIndices) {
  86064. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  86065. }
  86066. else {
  86067. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  86068. }
  86069. break;
  86070. case 2:
  86071. if (this._checkVerticesInsteadOfIndices) {
  86072. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  86073. }
  86074. else {
  86075. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  86076. }
  86077. break;
  86078. }
  86079. if (otherEdgeIndex === -1) {
  86080. continue;
  86081. }
  86082. faceAdjacencies.edges[edgeIndex] = otherIndex;
  86083. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  86084. faceAdjacencies.edgesConnectedCount++;
  86085. otherFaceAdjacencies.edgesConnectedCount++;
  86086. if (faceAdjacencies.edgesConnectedCount === 3) {
  86087. break;
  86088. }
  86089. }
  86090. }
  86091. }
  86092. // Create lines
  86093. for (index = 0; index < adjacencies.length; index++) {
  86094. // 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
  86095. var current = adjacencies[index];
  86096. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  86097. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  86098. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  86099. }
  86100. // Merge into a single mesh
  86101. var engine = this._source.getScene().getEngine();
  86102. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  86103. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  86104. this._ib = engine.createIndexBuffer(this._linesIndices);
  86105. this._indicesCount = this._linesIndices.length;
  86106. };
  86107. EdgesRenderer.prototype.render = function () {
  86108. var scene = this._source.getScene();
  86109. if (!this._lineShader.isReady() || !scene.activeCamera) {
  86110. return;
  86111. }
  86112. var engine = scene.getEngine();
  86113. this._lineShader._preBind();
  86114. // VBOs
  86115. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  86116. scene.resetCachedMaterial();
  86117. this._lineShader.setColor4("color", this._source.edgesColor);
  86118. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  86119. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  86120. }
  86121. else {
  86122. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  86123. }
  86124. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  86125. this._lineShader.bind(this._source.getWorldMatrix());
  86126. // Draw order
  86127. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  86128. this._lineShader.unbind();
  86129. engine.setDepthWrite(true);
  86130. };
  86131. return EdgesRenderer;
  86132. }());
  86133. BABYLON.EdgesRenderer = EdgesRenderer;
  86134. })(BABYLON || (BABYLON = {}));
  86135. //# sourceMappingURL=babylon.edgesRenderer.js.map
  86136. "use strict";
  86137. var __assign = (this && this.__assign) || Object.assign || function(t) {
  86138. for (var s, i = 1, n = arguments.length; i < n; i++) {
  86139. s = arguments[i];
  86140. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  86141. t[p] = s[p];
  86142. }
  86143. return t;
  86144. };
  86145. var BABYLON;
  86146. (function (BABYLON) {
  86147. /**
  86148. * The effect layer Helps adding post process effect blended with the main pass.
  86149. *
  86150. * This can be for instance use to generate glow or higlight effects on the scene.
  86151. *
  86152. * The effect layer class can not be used directly and is intented to inherited from to be
  86153. * customized per effects.
  86154. */
  86155. var EffectLayer = /** @class */ (function () {
  86156. /**
  86157. * Instantiates a new effect Layer and references it in the scene.
  86158. * @param name The name of the layer
  86159. * @param scene The scene to use the layer in
  86160. */
  86161. function EffectLayer(
  86162. /** The Friendly of the effect in the scene */
  86163. name, scene) {
  86164. this.name = name;
  86165. this._vertexBuffers = {};
  86166. this._maxSize = 0;
  86167. this._mainTextureDesiredSize = { width: 0, height: 0 };
  86168. this._shouldRender = true;
  86169. this._postProcesses = [];
  86170. this._textures = [];
  86171. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  86172. /**
  86173. * The clear color of the texture used to generate the glow map.
  86174. */
  86175. this.neutralColor = new BABYLON.Color4();
  86176. /**
  86177. * Specifies wether the highlight layer is enabled or not.
  86178. */
  86179. this.isEnabled = true;
  86180. /**
  86181. * An event triggered when the effect layer has been disposed.
  86182. */
  86183. this.onDisposeObservable = new BABYLON.Observable();
  86184. /**
  86185. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  86186. */
  86187. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  86188. /**
  86189. * An event triggered when the generated texture is being merged in the scene.
  86190. */
  86191. this.onBeforeComposeObservable = new BABYLON.Observable();
  86192. /**
  86193. * An event triggered when the generated texture has been merged in the scene.
  86194. */
  86195. this.onAfterComposeObservable = new BABYLON.Observable();
  86196. /**
  86197. * An event triggered when the efffect layer changes its size.
  86198. */
  86199. this.onSizeChangedObservable = new BABYLON.Observable();
  86200. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86201. this._engine = scene.getEngine();
  86202. this._maxSize = this._engine.getCaps().maxTextureSize;
  86203. this._scene.effectLayers.push(this);
  86204. // Generate Buffers
  86205. this._generateIndexBuffer();
  86206. this._genrateVertexBuffer();
  86207. }
  86208. Object.defineProperty(EffectLayer.prototype, "camera", {
  86209. /**
  86210. * Gets the camera attached to the layer.
  86211. */
  86212. get: function () {
  86213. return this._effectLayerOptions.camera;
  86214. },
  86215. enumerable: true,
  86216. configurable: true
  86217. });
  86218. /**
  86219. * Initializes the effect layer with the required options.
  86220. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  86221. */
  86222. EffectLayer.prototype._init = function (options) {
  86223. // Adapt options
  86224. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  86225. this._setMainTextureSize();
  86226. this._createMainTexture();
  86227. this._createTextureAndPostProcesses();
  86228. this._mergeEffect = this._createMergeEffect();
  86229. };
  86230. /**
  86231. * Generates the index buffer of the full screen quad blending to the main canvas.
  86232. */
  86233. EffectLayer.prototype._generateIndexBuffer = function () {
  86234. // Indices
  86235. var indices = [];
  86236. indices.push(0);
  86237. indices.push(1);
  86238. indices.push(2);
  86239. indices.push(0);
  86240. indices.push(2);
  86241. indices.push(3);
  86242. this._indexBuffer = this._engine.createIndexBuffer(indices);
  86243. };
  86244. /**
  86245. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  86246. */
  86247. EffectLayer.prototype._genrateVertexBuffer = function () {
  86248. // VBO
  86249. var vertices = [];
  86250. vertices.push(1, 1);
  86251. vertices.push(-1, 1);
  86252. vertices.push(-1, -1);
  86253. vertices.push(1, -1);
  86254. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  86255. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  86256. };
  86257. /**
  86258. * Sets the main texture desired size which is the closest power of two
  86259. * of the engine canvas size.
  86260. */
  86261. EffectLayer.prototype._setMainTextureSize = function () {
  86262. if (this._effectLayerOptions.mainTextureFixedSize) {
  86263. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  86264. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  86265. }
  86266. else {
  86267. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  86268. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  86269. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  86270. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  86271. }
  86272. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  86273. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  86274. };
  86275. /**
  86276. * Creates the main texture for the effect layer.
  86277. */
  86278. EffectLayer.prototype._createMainTexture = function () {
  86279. var _this = this;
  86280. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  86281. width: this._mainTextureDesiredSize.width,
  86282. height: this._mainTextureDesiredSize.height
  86283. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  86284. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  86285. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86286. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86287. this._mainTexture.anisotropicFilteringLevel = 1;
  86288. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86289. this._mainTexture.renderParticles = false;
  86290. this._mainTexture.renderList = null;
  86291. this._mainTexture.ignoreCameraViewport = true;
  86292. // Custom render function
  86293. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  86294. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  86295. var index;
  86296. var engine = _this._scene.getEngine();
  86297. if (depthOnlySubMeshes.length) {
  86298. engine.setColorWrite(false);
  86299. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  86300. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  86301. }
  86302. engine.setColorWrite(true);
  86303. }
  86304. for (index = 0; index < opaqueSubMeshes.length; index++) {
  86305. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  86306. }
  86307. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  86308. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  86309. }
  86310. for (index = 0; index < transparentSubMeshes.length; index++) {
  86311. _this._renderSubMesh(transparentSubMeshes.data[index]);
  86312. }
  86313. };
  86314. this._mainTexture.onClearObservable.add(function (engine) {
  86315. engine.clear(_this.neutralColor, true, true, true);
  86316. });
  86317. };
  86318. /**
  86319. * Checks for the readiness of the element composing the layer.
  86320. * @param subMesh the mesh to check for
  86321. * @param useInstances specify wether or not to use instances to render the mesh
  86322. * @param emissiveTexture the associated emissive texture used to generate the glow
  86323. * @return true if ready otherwise, false
  86324. */
  86325. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  86326. var material = subMesh.getMaterial();
  86327. if (!material) {
  86328. return false;
  86329. }
  86330. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  86331. return false;
  86332. }
  86333. var defines = [];
  86334. var attribs = [BABYLON.VertexBuffer.PositionKind];
  86335. var mesh = subMesh.getMesh();
  86336. var uv1 = false;
  86337. var uv2 = false;
  86338. // Alpha test
  86339. if (material && material.needAlphaTesting()) {
  86340. var alphaTexture = material.getAlphaTestTexture();
  86341. if (alphaTexture) {
  86342. defines.push("#define ALPHATEST");
  86343. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  86344. alphaTexture.coordinatesIndex === 1) {
  86345. defines.push("#define DIFFUSEUV2");
  86346. uv2 = true;
  86347. }
  86348. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  86349. defines.push("#define DIFFUSEUV1");
  86350. uv1 = true;
  86351. }
  86352. }
  86353. }
  86354. // Emissive
  86355. if (emissiveTexture) {
  86356. defines.push("#define EMISSIVE");
  86357. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  86358. emissiveTexture.coordinatesIndex === 1) {
  86359. defines.push("#define EMISSIVEUV2");
  86360. uv2 = true;
  86361. }
  86362. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  86363. defines.push("#define EMISSIVEUV1");
  86364. uv1 = true;
  86365. }
  86366. }
  86367. if (uv1) {
  86368. attribs.push(BABYLON.VertexBuffer.UVKind);
  86369. defines.push("#define UV1");
  86370. }
  86371. if (uv2) {
  86372. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  86373. defines.push("#define UV2");
  86374. }
  86375. // Bones
  86376. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  86377. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  86378. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  86379. if (mesh.numBoneInfluencers > 4) {
  86380. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  86381. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  86382. }
  86383. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  86384. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  86385. }
  86386. else {
  86387. defines.push("#define NUM_BONE_INFLUENCERS 0");
  86388. }
  86389. // Morph targets
  86390. var manager = mesh.morphTargetManager;
  86391. var morphInfluencers = 0;
  86392. if (manager) {
  86393. if (manager.numInfluencers > 0) {
  86394. defines.push("#define MORPHTARGETS");
  86395. morphInfluencers = manager.numInfluencers;
  86396. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  86397. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  86398. }
  86399. }
  86400. // Instances
  86401. if (useInstances) {
  86402. defines.push("#define INSTANCES");
  86403. attribs.push("world0");
  86404. attribs.push("world1");
  86405. attribs.push("world2");
  86406. attribs.push("world3");
  86407. }
  86408. // Get correct effect
  86409. var join = defines.join("\n");
  86410. if (this._cachedDefines !== join) {
  86411. this._cachedDefines = join;
  86412. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  86413. }
  86414. return this._effectLayerMapGenerationEffect.isReady();
  86415. };
  86416. /**
  86417. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  86418. */
  86419. EffectLayer.prototype.render = function () {
  86420. var currentEffect = this._mergeEffect;
  86421. // Check
  86422. if (!currentEffect.isReady())
  86423. return;
  86424. for (var i = 0; i < this._postProcesses.length; i++) {
  86425. if (!this._postProcesses[i].isReady()) {
  86426. return;
  86427. }
  86428. }
  86429. var engine = this._scene.getEngine();
  86430. this.onBeforeComposeObservable.notifyObservers(this);
  86431. // Render
  86432. engine.enableEffect(currentEffect);
  86433. engine.setState(false);
  86434. // VBOs
  86435. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  86436. // Cache
  86437. var previousAlphaMode = engine.getAlphaMode();
  86438. // Go Blend.
  86439. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  86440. // Blends the map on the main canvas.
  86441. this._internalRender(currentEffect);
  86442. // Restore Alpha
  86443. engine.setAlphaMode(previousAlphaMode);
  86444. this.onAfterComposeObservable.notifyObservers(this);
  86445. // Handle size changes.
  86446. var size = this._mainTexture.getSize();
  86447. this._setMainTextureSize();
  86448. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  86449. // Recreate RTT and post processes on size change.
  86450. this.onSizeChangedObservable.notifyObservers(this);
  86451. this._disposeTextureAndPostProcesses();
  86452. this._createMainTexture();
  86453. this._createTextureAndPostProcesses();
  86454. }
  86455. };
  86456. /**
  86457. * Determine if a given mesh will be used in the current effect.
  86458. * @param mesh mesh to test
  86459. * @returns true if the mesh will be used
  86460. */
  86461. EffectLayer.prototype.hasMesh = function (mesh) {
  86462. return true;
  86463. };
  86464. /**
  86465. * Returns true if the layer contains information to display, otherwise false.
  86466. * @returns true if the glow layer should be rendered
  86467. */
  86468. EffectLayer.prototype.shouldRender = function () {
  86469. return this.isEnabled && this._shouldRender;
  86470. };
  86471. /**
  86472. * Returns true if the mesh should render, otherwise false.
  86473. * @param mesh The mesh to render
  86474. * @returns true if it should render otherwise false
  86475. */
  86476. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  86477. return true;
  86478. };
  86479. /**
  86480. * Returns true if the mesh should render, otherwise false.
  86481. * @param mesh The mesh to render
  86482. * @returns true if it should render otherwise false
  86483. */
  86484. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  86485. return true;
  86486. };
  86487. /**
  86488. * Renders the submesh passed in parameter to the generation map.
  86489. */
  86490. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  86491. var _this = this;
  86492. if (!this.shouldRender()) {
  86493. return;
  86494. }
  86495. var material = subMesh.getMaterial();
  86496. var mesh = subMesh.getRenderingMesh();
  86497. var scene = this._scene;
  86498. var engine = scene.getEngine();
  86499. if (!material) {
  86500. return;
  86501. }
  86502. // Do not block in blend mode.
  86503. if (material.needAlphaBlendingForMesh(mesh)) {
  86504. return;
  86505. }
  86506. // Culling
  86507. engine.setState(material.backFaceCulling);
  86508. // Managing instances
  86509. var batch = mesh._getInstancesRenderList(subMesh._id);
  86510. if (batch.mustReturn) {
  86511. return;
  86512. }
  86513. // Early Exit per mesh
  86514. if (!this._shouldRenderMesh(mesh)) {
  86515. return;
  86516. }
  86517. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  86518. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  86519. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  86520. engine.enableEffect(this._effectLayerMapGenerationEffect);
  86521. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  86522. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  86523. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  86524. // Alpha test
  86525. if (material && material.needAlphaTesting()) {
  86526. var alphaTexture = material.getAlphaTestTexture();
  86527. if (alphaTexture) {
  86528. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  86529. var textureMatrix = alphaTexture.getTextureMatrix();
  86530. if (textureMatrix) {
  86531. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  86532. }
  86533. }
  86534. }
  86535. // Glow emissive only
  86536. if (this._emissiveTextureAndColor.texture) {
  86537. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  86538. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  86539. }
  86540. // Bones
  86541. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  86542. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  86543. }
  86544. // Morph targets
  86545. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  86546. // Draw
  86547. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  86548. }
  86549. else {
  86550. // Need to reset refresh rate of the shadowMap
  86551. this._mainTexture.resetRefreshCounter();
  86552. }
  86553. };
  86554. /**
  86555. * Rebuild the required buffers.
  86556. * @ignore Internal use only.
  86557. */
  86558. EffectLayer.prototype._rebuild = function () {
  86559. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86560. if (vb) {
  86561. vb._rebuild();
  86562. }
  86563. this._generateIndexBuffer();
  86564. };
  86565. /**
  86566. * Dispose only the render target textures and post process.
  86567. */
  86568. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  86569. this._mainTexture.dispose();
  86570. for (var i = 0; i < this._postProcesses.length; i++) {
  86571. if (this._postProcesses[i]) {
  86572. this._postProcesses[i].dispose();
  86573. }
  86574. }
  86575. this._postProcesses = [];
  86576. for (var i = 0; i < this._textures.length; i++) {
  86577. if (this._textures[i]) {
  86578. this._textures[i].dispose();
  86579. }
  86580. }
  86581. this._textures = [];
  86582. };
  86583. /**
  86584. * Dispose the highlight layer and free resources.
  86585. */
  86586. EffectLayer.prototype.dispose = function () {
  86587. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86588. if (vertexBuffer) {
  86589. vertexBuffer.dispose();
  86590. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86591. }
  86592. if (this._indexBuffer) {
  86593. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86594. this._indexBuffer = null;
  86595. }
  86596. // Clean textures and post processes
  86597. this._disposeTextureAndPostProcesses();
  86598. // Remove from scene
  86599. var index = this._scene.effectLayers.indexOf(this, 0);
  86600. if (index > -1) {
  86601. this._scene.effectLayers.splice(index, 1);
  86602. }
  86603. // Callback
  86604. this.onDisposeObservable.notifyObservers(this);
  86605. this.onDisposeObservable.clear();
  86606. this.onBeforeRenderMainTextureObservable.clear();
  86607. this.onBeforeComposeObservable.clear();
  86608. this.onAfterComposeObservable.clear();
  86609. this.onSizeChangedObservable.clear();
  86610. };
  86611. return EffectLayer;
  86612. }());
  86613. BABYLON.EffectLayer = EffectLayer;
  86614. })(BABYLON || (BABYLON = {}));
  86615. //# sourceMappingURL=babylon.effectLayer.js.map
  86616. "use strict";
  86617. var BABYLON;
  86618. (function (BABYLON) {
  86619. /**
  86620. * Special Glow Blur post process only blurring the alpha channel
  86621. * It enforces keeping the most luminous color in the color channel.
  86622. */
  86623. var GlowBlurPostProcess = /** @class */ (function (_super) {
  86624. __extends(GlowBlurPostProcess, _super);
  86625. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  86626. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  86627. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  86628. _this.direction = direction;
  86629. _this.kernel = kernel;
  86630. _this.onApplyObservable.add(function (effect) {
  86631. effect.setFloat2("screenSize", _this.width, _this.height);
  86632. effect.setVector2("direction", _this.direction);
  86633. effect.setFloat("blurWidth", _this.kernel);
  86634. });
  86635. return _this;
  86636. }
  86637. return GlowBlurPostProcess;
  86638. }(BABYLON.PostProcess));
  86639. /**
  86640. * The highlight layer Helps adding a glow effect around a mesh.
  86641. *
  86642. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  86643. * glowy meshes to your scene.
  86644. *
  86645. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  86646. */
  86647. var HighlightLayer = /** @class */ (function (_super) {
  86648. __extends(HighlightLayer, _super);
  86649. /**
  86650. * Instantiates a new highlight Layer and references it to the scene..
  86651. * @param name The name of the layer
  86652. * @param scene The scene to use the layer in
  86653. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  86654. */
  86655. function HighlightLayer(name, scene, options) {
  86656. var _this = _super.call(this, name, scene) || this;
  86657. _this.name = name;
  86658. /**
  86659. * Specifies whether or not the inner glow is ACTIVE in the layer.
  86660. */
  86661. _this.innerGlow = true;
  86662. /**
  86663. * Specifies whether or not the outer glow is ACTIVE in the layer.
  86664. */
  86665. _this.outerGlow = true;
  86666. /**
  86667. * An event triggered when the highlight layer is being blurred.
  86668. */
  86669. _this.onBeforeBlurObservable = new BABYLON.Observable();
  86670. /**
  86671. * An event triggered when the highlight layer has been blurred.
  86672. */
  86673. _this.onAfterBlurObservable = new BABYLON.Observable();
  86674. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  86675. _this._meshes = {};
  86676. _this._excludedMeshes = {};
  86677. _this.neutralColor = HighlightLayer.NeutralColor;
  86678. // Warn on stencil
  86679. if (!_this._engine.isStencilEnable) {
  86680. 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 }");
  86681. }
  86682. // Adapt options
  86683. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  86684. // Initialize the layer
  86685. _this._init({
  86686. alphaBlendingMode: _this._options.alphaBlendingMode,
  86687. camera: _this._options.camera,
  86688. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  86689. mainTextureRatio: _this._options.mainTextureRatio
  86690. });
  86691. // Do not render as long as no meshes have been added
  86692. _this._shouldRender = false;
  86693. return _this;
  86694. }
  86695. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  86696. /**
  86697. * Gets the horizontal size of the blur.
  86698. */
  86699. get: function () {
  86700. return this._horizontalBlurPostprocess.kernel;
  86701. },
  86702. /**
  86703. * Specifies the horizontal size of the blur.
  86704. */
  86705. set: function (value) {
  86706. this._horizontalBlurPostprocess.kernel = value;
  86707. },
  86708. enumerable: true,
  86709. configurable: true
  86710. });
  86711. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  86712. /**
  86713. * Gets the vertical size of the blur.
  86714. */
  86715. get: function () {
  86716. return this._verticalBlurPostprocess.kernel;
  86717. },
  86718. /**
  86719. * Specifies the vertical size of the blur.
  86720. */
  86721. set: function (value) {
  86722. this._verticalBlurPostprocess.kernel = value;
  86723. },
  86724. enumerable: true,
  86725. configurable: true
  86726. });
  86727. /**
  86728. * Get the effect name of the layer.
  86729. * @return The effect name
  86730. */
  86731. HighlightLayer.prototype.getEffectName = function () {
  86732. return HighlightLayer.EffectName;
  86733. };
  86734. /**
  86735. * Create the merge effect. This is the shader use to blit the information back
  86736. * to the main canvas at the end of the scene rendering.
  86737. */
  86738. HighlightLayer.prototype._createMergeEffect = function () {
  86739. // Effect
  86740. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  86741. };
  86742. /**
  86743. * Creates the render target textures and post processes used in the highlight layer.
  86744. */
  86745. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  86746. var _this = this;
  86747. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  86748. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  86749. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  86750. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  86751. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  86752. width: blurTextureWidth,
  86753. height: blurTextureHeight
  86754. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86755. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86756. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86757. this._blurTexture.anisotropicFilteringLevel = 16;
  86758. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  86759. this._blurTexture.renderParticles = false;
  86760. this._blurTexture.ignoreCameraViewport = true;
  86761. this._textures = [this._blurTexture];
  86762. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  86763. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  86764. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  86765. effect.setTexture("textureSampler", _this._mainTexture);
  86766. });
  86767. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  86768. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  86769. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  86770. });
  86771. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  86772. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  86773. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  86774. });
  86775. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  86776. }
  86777. else {
  86778. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  86779. width: blurTextureWidth,
  86780. height: blurTextureHeight
  86781. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86782. this._horizontalBlurPostprocess.width = blurTextureWidth;
  86783. this._horizontalBlurPostprocess.height = blurTextureHeight;
  86784. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  86785. effect.setTexture("textureSampler", _this._mainTexture);
  86786. });
  86787. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  86788. width: blurTextureWidth,
  86789. height: blurTextureHeight
  86790. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86791. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  86792. }
  86793. this._mainTexture.onAfterUnbindObservable.add(function () {
  86794. _this.onBeforeBlurObservable.notifyObservers(_this);
  86795. var internalTexture = _this._blurTexture.getInternalTexture();
  86796. if (internalTexture) {
  86797. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  86798. }
  86799. _this.onAfterBlurObservable.notifyObservers(_this);
  86800. });
  86801. // Prevent autoClear.
  86802. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  86803. };
  86804. /**
  86805. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  86806. */
  86807. HighlightLayer.prototype.needStencil = function () {
  86808. return true;
  86809. };
  86810. /**
  86811. * Checks for the readiness of the element composing the layer.
  86812. * @param subMesh the mesh to check for
  86813. * @param useInstances specify wether or not to use instances to render the mesh
  86814. * @param emissiveTexture the associated emissive texture used to generate the glow
  86815. * @return true if ready otherwise, false
  86816. */
  86817. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  86818. var material = subMesh.getMaterial();
  86819. var mesh = subMesh.getRenderingMesh();
  86820. if (!material || !mesh || !this._meshes) {
  86821. return false;
  86822. }
  86823. var emissiveTexture = null;
  86824. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  86825. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  86826. emissiveTexture = material.emissiveTexture;
  86827. }
  86828. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  86829. };
  86830. /**
  86831. * Implementation specific of rendering the generating effect on the main canvas.
  86832. * @param effect The effect used to render through
  86833. */
  86834. HighlightLayer.prototype._internalRender = function (effect) {
  86835. // Texture
  86836. effect.setTexture("textureSampler", this._blurTexture);
  86837. // Cache
  86838. var engine = this._engine;
  86839. var previousStencilBuffer = engine.getStencilBuffer();
  86840. var previousStencilFunction = engine.getStencilFunction();
  86841. var previousStencilMask = engine.getStencilMask();
  86842. var previousStencilOperationPass = engine.getStencilOperationPass();
  86843. var previousStencilOperationFail = engine.getStencilOperationFail();
  86844. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  86845. var previousStencilReference = engine.getStencilFunctionReference();
  86846. // Stencil operations
  86847. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  86848. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  86849. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  86850. // Draw order
  86851. engine.setStencilMask(0x00);
  86852. engine.setStencilBuffer(true);
  86853. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  86854. // 2 passes inner outer
  86855. if (this.outerGlow) {
  86856. effect.setFloat("offset", 0);
  86857. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  86858. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86859. }
  86860. if (this.innerGlow) {
  86861. effect.setFloat("offset", 1);
  86862. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  86863. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86864. }
  86865. // Restore Cache
  86866. engine.setStencilFunction(previousStencilFunction);
  86867. engine.setStencilMask(previousStencilMask);
  86868. engine.setStencilBuffer(previousStencilBuffer);
  86869. engine.setStencilOperationPass(previousStencilOperationPass);
  86870. engine.setStencilOperationFail(previousStencilOperationFail);
  86871. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  86872. engine.setStencilFunctionReference(previousStencilReference);
  86873. };
  86874. /**
  86875. * Returns true if the layer contains information to display, otherwise false.
  86876. */
  86877. HighlightLayer.prototype.shouldRender = function () {
  86878. if (_super.prototype.shouldRender.call(this)) {
  86879. return this._meshes ? true : false;
  86880. }
  86881. return false;
  86882. };
  86883. /**
  86884. * Returns true if the mesh should render, otherwise false.
  86885. * @param mesh The mesh to render
  86886. * @returns true if it should render otherwise false
  86887. */
  86888. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  86889. // Excluded Mesh
  86890. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  86891. return false;
  86892. }
  86893. ;
  86894. return true;
  86895. };
  86896. /**
  86897. * Sets the required values for both the emissive texture and and the main color.
  86898. */
  86899. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  86900. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  86901. if (highlightLayerMesh) {
  86902. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  86903. }
  86904. else {
  86905. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  86906. }
  86907. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  86908. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  86909. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  86910. }
  86911. else {
  86912. this._emissiveTextureAndColor.texture = null;
  86913. }
  86914. };
  86915. /**
  86916. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  86917. * @param mesh The mesh to exclude from the highlight layer
  86918. */
  86919. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  86920. if (!this._excludedMeshes) {
  86921. return;
  86922. }
  86923. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  86924. if (!meshExcluded) {
  86925. this._excludedMeshes[mesh.uniqueId] = {
  86926. mesh: mesh,
  86927. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  86928. mesh.getEngine().setStencilBuffer(false);
  86929. }),
  86930. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  86931. mesh.getEngine().setStencilBuffer(true);
  86932. }),
  86933. };
  86934. }
  86935. };
  86936. /**
  86937. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  86938. * @param mesh The mesh to highlight
  86939. */
  86940. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  86941. if (!this._excludedMeshes) {
  86942. return;
  86943. }
  86944. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  86945. if (meshExcluded) {
  86946. if (meshExcluded.beforeRender) {
  86947. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  86948. }
  86949. if (meshExcluded.afterRender) {
  86950. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  86951. }
  86952. }
  86953. this._excludedMeshes[mesh.uniqueId] = null;
  86954. };
  86955. /**
  86956. * Determine if a given mesh will be highlighted by the current HighlightLayer
  86957. * @param mesh mesh to test
  86958. * @returns true if the mesh will be highlighted by the current HighlightLayer
  86959. */
  86960. HighlightLayer.prototype.hasMesh = function (mesh) {
  86961. if (!this._meshes) {
  86962. return false;
  86963. }
  86964. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  86965. };
  86966. /**
  86967. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  86968. * @param mesh The mesh to highlight
  86969. * @param color The color of the highlight
  86970. * @param glowEmissiveOnly Extract the glow from the emissive texture
  86971. */
  86972. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  86973. var _this = this;
  86974. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  86975. if (!this._meshes) {
  86976. return;
  86977. }
  86978. var meshHighlight = this._meshes[mesh.uniqueId];
  86979. if (meshHighlight) {
  86980. meshHighlight.color = color;
  86981. }
  86982. else {
  86983. this._meshes[mesh.uniqueId] = {
  86984. mesh: mesh,
  86985. color: color,
  86986. // Lambda required for capture due to Observable this context
  86987. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  86988. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  86989. _this._defaultStencilReference(mesh);
  86990. }
  86991. else {
  86992. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  86993. }
  86994. }),
  86995. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  86996. glowEmissiveOnly: glowEmissiveOnly
  86997. };
  86998. }
  86999. this._shouldRender = true;
  87000. };
  87001. /**
  87002. * Remove a mesh from the highlight layer in order to make it stop glowing.
  87003. * @param mesh The mesh to highlight
  87004. */
  87005. HighlightLayer.prototype.removeMesh = function (mesh) {
  87006. if (!this._meshes) {
  87007. return;
  87008. }
  87009. var meshHighlight = this._meshes[mesh.uniqueId];
  87010. if (meshHighlight) {
  87011. if (meshHighlight.observerHighlight) {
  87012. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  87013. }
  87014. if (meshHighlight.observerDefault) {
  87015. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  87016. }
  87017. delete this._meshes[mesh.uniqueId];
  87018. }
  87019. this._shouldRender = false;
  87020. for (var meshHighlightToCheck in this._meshes) {
  87021. if (this._meshes[meshHighlightToCheck]) {
  87022. this._shouldRender = true;
  87023. break;
  87024. }
  87025. }
  87026. };
  87027. /**
  87028. * Force the stencil to the normal expected value for none glowing parts
  87029. */
  87030. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  87031. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  87032. };
  87033. /**
  87034. * Free any resources and references associated to a mesh.
  87035. * Internal use
  87036. * @param mesh The mesh to free.
  87037. */
  87038. HighlightLayer.prototype._disposeMesh = function (mesh) {
  87039. this.removeMesh(mesh);
  87040. this.removeExcludedMesh(mesh);
  87041. };
  87042. /**
  87043. * Dispose the highlight layer and free resources.
  87044. */
  87045. HighlightLayer.prototype.dispose = function () {
  87046. if (this._meshes) {
  87047. // Clean mesh references
  87048. for (var id in this._meshes) {
  87049. var meshHighlight = this._meshes[id];
  87050. if (meshHighlight && meshHighlight.mesh) {
  87051. if (meshHighlight.observerHighlight) {
  87052. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  87053. }
  87054. if (meshHighlight.observerDefault) {
  87055. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  87056. }
  87057. }
  87058. }
  87059. this._meshes = null;
  87060. }
  87061. if (this._excludedMeshes) {
  87062. for (var id in this._excludedMeshes) {
  87063. var meshHighlight = this._excludedMeshes[id];
  87064. if (meshHighlight) {
  87065. if (meshHighlight.beforeRender) {
  87066. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  87067. }
  87068. if (meshHighlight.afterRender) {
  87069. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  87070. }
  87071. }
  87072. }
  87073. this._excludedMeshes = null;
  87074. }
  87075. _super.prototype.dispose.call(this);
  87076. };
  87077. /**
  87078. * Effect Name of the highlight layer.
  87079. */
  87080. HighlightLayer.EffectName = "HighlightLayer";
  87081. /**
  87082. * The neutral color used during the preparation of the glow effect.
  87083. * This is black by default as the blend operation is a blend operation.
  87084. */
  87085. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  87086. /**
  87087. * Stencil value used for glowing meshes.
  87088. */
  87089. HighlightLayer.GlowingMeshStencilReference = 0x02;
  87090. /**
  87091. * Stencil value used for the other meshes in the scene.
  87092. */
  87093. HighlightLayer.NormalMeshStencilReference = 0x01;
  87094. return HighlightLayer;
  87095. }(BABYLON.EffectLayer));
  87096. BABYLON.HighlightLayer = HighlightLayer;
  87097. })(BABYLON || (BABYLON = {}));
  87098. //# sourceMappingURL=babylon.highlightLayer.js.map
  87099. "use strict";
  87100. var BABYLON;
  87101. (function (BABYLON) {
  87102. /**
  87103. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  87104. *
  87105. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  87106. * glowy meshes to your scene.
  87107. *
  87108. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  87109. */
  87110. var GlowLayer = /** @class */ (function (_super) {
  87111. __extends(GlowLayer, _super);
  87112. /**
  87113. * Instantiates a new glow Layer and references it to the scene.
  87114. * @param name The name of the layer
  87115. * @param scene The scene to use the layer in
  87116. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  87117. */
  87118. function GlowLayer(name, scene, options) {
  87119. var _this = _super.call(this, name, scene) || this;
  87120. _this.name = name;
  87121. _this._intensity = 1.0;
  87122. _this._includedOnlyMeshes = [];
  87123. _this._excludedMeshes = [];
  87124. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  87125. // Adapt options
  87126. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  87127. // Initialize the layer
  87128. _this._init({
  87129. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  87130. camera: _this._options.camera,
  87131. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  87132. mainTextureRatio: _this._options.mainTextureRatio
  87133. });
  87134. return _this;
  87135. }
  87136. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  87137. /**
  87138. * Gets the kernel size of the blur.
  87139. */
  87140. get: function () {
  87141. return this._horizontalBlurPostprocess1.kernel;
  87142. },
  87143. /**
  87144. * Sets the kernel size of the blur.
  87145. */
  87146. set: function (value) {
  87147. this._horizontalBlurPostprocess1.kernel = value;
  87148. this._verticalBlurPostprocess1.kernel = value;
  87149. this._horizontalBlurPostprocess2.kernel = value;
  87150. this._verticalBlurPostprocess2.kernel = value;
  87151. },
  87152. enumerable: true,
  87153. configurable: true
  87154. });
  87155. Object.defineProperty(GlowLayer.prototype, "intensity", {
  87156. /**
  87157. * Gets the glow intensity.
  87158. */
  87159. get: function () {
  87160. return this._intensity;
  87161. },
  87162. /**
  87163. * Sets the glow intensity.
  87164. */
  87165. set: function (value) {
  87166. this._intensity = value;
  87167. },
  87168. enumerable: true,
  87169. configurable: true
  87170. });
  87171. /**
  87172. * Get the effect name of the layer.
  87173. * @return The effect name
  87174. */
  87175. GlowLayer.prototype.getEffectName = function () {
  87176. return GlowLayer.EffectName;
  87177. };
  87178. /**
  87179. * Create the merge effect. This is the shader use to blit the information back
  87180. * to the main canvas at the end of the scene rendering.
  87181. */
  87182. GlowLayer.prototype._createMergeEffect = function () {
  87183. // Effect
  87184. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  87185. };
  87186. /**
  87187. * Creates the render target textures and post processes used in the glow layer.
  87188. */
  87189. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  87190. var _this = this;
  87191. var blurTextureWidth = this._mainTextureDesiredSize.width;
  87192. var blurTextureHeight = this._mainTextureDesiredSize.height;
  87193. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  87194. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  87195. var textureType = 0;
  87196. if (this._engine.getCaps().textureHalfFloatRender) {
  87197. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  87198. }
  87199. else {
  87200. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87201. }
  87202. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  87203. width: blurTextureWidth,
  87204. height: blurTextureHeight
  87205. }, this._scene, false, true, textureType);
  87206. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87207. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87208. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87209. this._blurTexture1.renderParticles = false;
  87210. this._blurTexture1.ignoreCameraViewport = true;
  87211. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  87212. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  87213. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  87214. width: blurTextureWidth2,
  87215. height: blurTextureHeight2
  87216. }, this._scene, false, true, textureType);
  87217. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87218. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87219. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87220. this._blurTexture2.renderParticles = false;
  87221. this._blurTexture2.ignoreCameraViewport = true;
  87222. this._textures = [this._blurTexture1, this._blurTexture2];
  87223. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  87224. width: blurTextureWidth,
  87225. height: blurTextureHeight
  87226. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  87227. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  87228. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  87229. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  87230. effect.setTexture("textureSampler", _this._mainTexture);
  87231. });
  87232. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  87233. width: blurTextureWidth,
  87234. height: blurTextureHeight
  87235. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  87236. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  87237. width: blurTextureWidth2,
  87238. height: blurTextureHeight2
  87239. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  87240. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  87241. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  87242. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  87243. effect.setTexture("textureSampler", _this._blurTexture1);
  87244. });
  87245. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  87246. width: blurTextureWidth2,
  87247. height: blurTextureHeight2
  87248. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  87249. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  87250. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  87251. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  87252. this._mainTexture.samples = this._options.mainTextureSamples;
  87253. this._mainTexture.onAfterUnbindObservable.add(function () {
  87254. var internalTexture = _this._blurTexture1.getInternalTexture();
  87255. if (internalTexture) {
  87256. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  87257. internalTexture = _this._blurTexture2.getInternalTexture();
  87258. if (internalTexture) {
  87259. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  87260. }
  87261. }
  87262. });
  87263. // Prevent autoClear.
  87264. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  87265. };
  87266. /**
  87267. * Checks for the readiness of the element composing the layer.
  87268. * @param subMesh the mesh to check for
  87269. * @param useInstances specify wether or not to use instances to render the mesh
  87270. * @param emissiveTexture the associated emissive texture used to generate the glow
  87271. * @return true if ready otherwise, false
  87272. */
  87273. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  87274. var material = subMesh.getMaterial();
  87275. var mesh = subMesh.getRenderingMesh();
  87276. if (!material || !mesh) {
  87277. return false;
  87278. }
  87279. var emissiveTexture = material.emissiveTexture;
  87280. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  87281. };
  87282. /**
  87283. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  87284. */
  87285. GlowLayer.prototype.needStencil = function () {
  87286. return false;
  87287. };
  87288. /**
  87289. * Implementation specific of rendering the generating effect on the main canvas.
  87290. * @param effect The effect used to render through
  87291. */
  87292. GlowLayer.prototype._internalRender = function (effect) {
  87293. // Texture
  87294. effect.setTexture("textureSampler", this._blurTexture1);
  87295. effect.setTexture("textureSampler2", this._blurTexture2);
  87296. effect.setFloat("offset", this._intensity);
  87297. // Cache
  87298. var engine = this._engine;
  87299. var previousStencilBuffer = engine.getStencilBuffer();
  87300. // Draw order
  87301. engine.setStencilBuffer(false);
  87302. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87303. // Draw order
  87304. engine.setStencilBuffer(previousStencilBuffer);
  87305. };
  87306. /**
  87307. * Sets the required values for both the emissive texture and and the main color.
  87308. */
  87309. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  87310. var textureLevel = 1.0;
  87311. if (this.customEmissiveTextureSelector) {
  87312. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  87313. }
  87314. else {
  87315. if (material) {
  87316. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  87317. if (this._emissiveTextureAndColor.texture) {
  87318. textureLevel = this._emissiveTextureAndColor.texture.level;
  87319. }
  87320. }
  87321. else {
  87322. this._emissiveTextureAndColor.texture = null;
  87323. }
  87324. }
  87325. if (this.customEmissiveColorSelector) {
  87326. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  87327. }
  87328. else {
  87329. if (material.emissiveColor) {
  87330. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  87331. }
  87332. else {
  87333. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  87334. }
  87335. }
  87336. };
  87337. /**
  87338. * Returns true if the mesh should render, otherwise false.
  87339. * @param mesh The mesh to render
  87340. * @returns true if it should render otherwise false
  87341. */
  87342. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  87343. return this.hasMesh(mesh);
  87344. };
  87345. /**
  87346. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  87347. * @param mesh The mesh to exclude from the glow layer
  87348. */
  87349. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  87350. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  87351. this._excludedMeshes.push(mesh.uniqueId);
  87352. }
  87353. };
  87354. /**
  87355. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  87356. * @param mesh The mesh to remove
  87357. */
  87358. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  87359. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  87360. if (index !== -1) {
  87361. this._excludedMeshes.splice(index, 1);
  87362. }
  87363. };
  87364. /**
  87365. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  87366. * @param mesh The mesh to include in the glow layer
  87367. */
  87368. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  87369. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  87370. this._includedOnlyMeshes.push(mesh.uniqueId);
  87371. }
  87372. };
  87373. /**
  87374. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  87375. * @param mesh The mesh to remove
  87376. */
  87377. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  87378. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  87379. if (index !== -1) {
  87380. this._includedOnlyMeshes.splice(index, 1);
  87381. }
  87382. };
  87383. /**
  87384. * Determine if a given mesh will be used in the glow layer
  87385. * @param mesh The mesh to test
  87386. * @returns true if the mesh will be highlighted by the current glow layer
  87387. */
  87388. GlowLayer.prototype.hasMesh = function (mesh) {
  87389. // Included Mesh
  87390. if (this._includedOnlyMeshes.length) {
  87391. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  87392. }
  87393. ;
  87394. // Excluded Mesh
  87395. if (this._excludedMeshes.length) {
  87396. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  87397. }
  87398. ;
  87399. return true;
  87400. };
  87401. /**
  87402. * Free any resources and references associated to a mesh.
  87403. * Internal use
  87404. * @param mesh The mesh to free.
  87405. */
  87406. GlowLayer.prototype._disposeMesh = function (mesh) {
  87407. this.removeIncludedOnlyMesh(mesh);
  87408. this.removeExcludedMesh(mesh);
  87409. };
  87410. /**
  87411. * Effect Name of the layer.
  87412. */
  87413. GlowLayer.EffectName = "GlowLayer";
  87414. /**
  87415. * The default blur kernel size used for the glow.
  87416. */
  87417. GlowLayer.DefaultBlurKernelSize = 32;
  87418. /**
  87419. * The default texture size ratio used for the glow.
  87420. */
  87421. GlowLayer.DefaultTextureRatio = 0.5;
  87422. return GlowLayer;
  87423. }(BABYLON.EffectLayer));
  87424. BABYLON.GlowLayer = GlowLayer;
  87425. })(BABYLON || (BABYLON = {}));
  87426. //# sourceMappingURL=babylon.glowLayer.js.map
  87427. "use strict";
  87428. var BABYLON;
  87429. (function (BABYLON) {
  87430. /**
  87431. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  87432. */
  87433. var AssetTaskState;
  87434. (function (AssetTaskState) {
  87435. /**
  87436. * Initialization
  87437. */
  87438. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  87439. /**
  87440. * Running
  87441. */
  87442. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  87443. /**
  87444. * Done
  87445. */
  87446. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  87447. /**
  87448. * Error
  87449. */
  87450. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  87451. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  87452. /**
  87453. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  87454. */
  87455. var AbstractAssetTask = /** @class */ (function () {
  87456. /**
  87457. * Creates a new {BABYLON.AssetsManager}
  87458. * @param name defines the name of the task
  87459. */
  87460. function AbstractAssetTask(
  87461. /**
  87462. * Task name
  87463. */ name) {
  87464. this.name = name;
  87465. this._isCompleted = false;
  87466. this._taskState = AssetTaskState.INIT;
  87467. }
  87468. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  87469. /**
  87470. * Get if the task is completed
  87471. */
  87472. get: function () {
  87473. return this._isCompleted;
  87474. },
  87475. enumerable: true,
  87476. configurable: true
  87477. });
  87478. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  87479. /**
  87480. * Gets the current state of the task
  87481. */
  87482. get: function () {
  87483. return this._taskState;
  87484. },
  87485. enumerable: true,
  87486. configurable: true
  87487. });
  87488. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  87489. /**
  87490. * Gets the current error object (if task is in error)
  87491. */
  87492. get: function () {
  87493. return this._errorObject;
  87494. },
  87495. enumerable: true,
  87496. configurable: true
  87497. });
  87498. /**
  87499. * Internal only
  87500. * @ignore
  87501. */
  87502. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  87503. if (this._errorObject) {
  87504. return;
  87505. }
  87506. this._errorObject = {
  87507. message: message,
  87508. exception: exception
  87509. };
  87510. };
  87511. /**
  87512. * Execute the current task
  87513. * @param scene defines the scene where you want your assets to be loaded
  87514. * @param onSuccess is a callback called when the task is successfully executed
  87515. * @param onError is a callback called if an error occurs
  87516. */
  87517. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  87518. var _this = this;
  87519. this._taskState = AssetTaskState.RUNNING;
  87520. this.runTask(scene, function () {
  87521. _this.onDoneCallback(onSuccess, onError);
  87522. }, function (msg, exception) {
  87523. _this.onErrorCallback(onError, msg, exception);
  87524. });
  87525. };
  87526. /**
  87527. * Execute the current task
  87528. * @param scene defines the scene where you want your assets to be loaded
  87529. * @param onSuccess is a callback called when the task is successfully executed
  87530. * @param onError is a callback called if an error occurs
  87531. */
  87532. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87533. throw new Error("runTask is not implemented");
  87534. };
  87535. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  87536. this._taskState = AssetTaskState.ERROR;
  87537. this._errorObject = {
  87538. message: message,
  87539. exception: exception
  87540. };
  87541. if (this.onError) {
  87542. this.onError(this, message, exception);
  87543. }
  87544. onError();
  87545. };
  87546. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  87547. try {
  87548. this._taskState = AssetTaskState.DONE;
  87549. this._isCompleted = true;
  87550. if (this.onSuccess) {
  87551. this.onSuccess(this);
  87552. }
  87553. onSuccess();
  87554. }
  87555. catch (e) {
  87556. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  87557. }
  87558. };
  87559. return AbstractAssetTask;
  87560. }());
  87561. BABYLON.AbstractAssetTask = AbstractAssetTask;
  87562. /**
  87563. * Class used to share progress information about assets loading
  87564. */
  87565. var AssetsProgressEvent = /** @class */ (function () {
  87566. /**
  87567. * Creates a {BABYLON.AssetsProgressEvent}
  87568. * @param remainingCount defines the number of remaining tasks to process
  87569. * @param totalCount defines the total number of tasks
  87570. * @param task defines the task that was just processed
  87571. */
  87572. function AssetsProgressEvent(remainingCount, totalCount, task) {
  87573. this.remainingCount = remainingCount;
  87574. this.totalCount = totalCount;
  87575. this.task = task;
  87576. }
  87577. return AssetsProgressEvent;
  87578. }());
  87579. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  87580. /**
  87581. * Define a task used by {BABYLON.AssetsManager} to load meshes
  87582. */
  87583. var MeshAssetTask = /** @class */ (function (_super) {
  87584. __extends(MeshAssetTask, _super);
  87585. /**
  87586. * Creates a new {BABYLON.MeshAssetTask}
  87587. * @param name defines the name of the task
  87588. * @param meshesNames defines the list of mesh's names you want to load
  87589. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  87590. * @param sceneFilename defines the filename of the scene to load from
  87591. */
  87592. function MeshAssetTask(
  87593. /**
  87594. * Defines the name of the task
  87595. */
  87596. name,
  87597. /**
  87598. * Defines the list of mesh's names you want to load
  87599. */
  87600. meshesNames,
  87601. /**
  87602. * Defines the root url to use as a base to load your meshes and associated resources
  87603. */
  87604. rootUrl,
  87605. /**
  87606. * Defines the filename of the scene to load from
  87607. */
  87608. sceneFilename) {
  87609. var _this = _super.call(this, name) || this;
  87610. _this.name = name;
  87611. _this.meshesNames = meshesNames;
  87612. _this.rootUrl = rootUrl;
  87613. _this.sceneFilename = sceneFilename;
  87614. return _this;
  87615. }
  87616. /**
  87617. * Execute the current task
  87618. * @param scene defines the scene where you want your assets to be loaded
  87619. * @param onSuccess is a callback called when the task is successfully executed
  87620. * @param onError is a callback called if an error occurs
  87621. */
  87622. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87623. var _this = this;
  87624. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  87625. _this.loadedMeshes = meshes;
  87626. _this.loadedParticleSystems = particleSystems;
  87627. _this.loadedSkeletons = skeletons;
  87628. onSuccess();
  87629. }, null, function (scene, message, exception) {
  87630. onError(message, exception);
  87631. });
  87632. };
  87633. return MeshAssetTask;
  87634. }(AbstractAssetTask));
  87635. BABYLON.MeshAssetTask = MeshAssetTask;
  87636. /**
  87637. * Define a task used by {BABYLON.AssetsManager} to load text content
  87638. */
  87639. var TextFileAssetTask = /** @class */ (function (_super) {
  87640. __extends(TextFileAssetTask, _super);
  87641. /**
  87642. * Creates a new TextFileAssetTask object
  87643. * @param name defines the name of the task
  87644. * @param url defines the location of the file to load
  87645. */
  87646. function TextFileAssetTask(
  87647. /**
  87648. * Defines the name of the task
  87649. */
  87650. name,
  87651. /**
  87652. * Defines the location of the file to load
  87653. */
  87654. url) {
  87655. var _this = _super.call(this, name) || this;
  87656. _this.name = name;
  87657. _this.url = url;
  87658. return _this;
  87659. }
  87660. /**
  87661. * Execute the current task
  87662. * @param scene defines the scene where you want your assets to be loaded
  87663. * @param onSuccess is a callback called when the task is successfully executed
  87664. * @param onError is a callback called if an error occurs
  87665. */
  87666. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87667. var _this = this;
  87668. scene._loadFile(this.url, function (data) {
  87669. _this.text = data;
  87670. onSuccess();
  87671. }, undefined, false, false, function (request, exception) {
  87672. if (request) {
  87673. onError(request.status + " " + request.statusText, exception);
  87674. }
  87675. });
  87676. };
  87677. return TextFileAssetTask;
  87678. }(AbstractAssetTask));
  87679. BABYLON.TextFileAssetTask = TextFileAssetTask;
  87680. /**
  87681. * Define a task used by {BABYLON.AssetsManager} to load binary data
  87682. */
  87683. var BinaryFileAssetTask = /** @class */ (function (_super) {
  87684. __extends(BinaryFileAssetTask, _super);
  87685. /**
  87686. * Creates a new BinaryFileAssetTask object
  87687. * @param name defines the name of the new task
  87688. * @param url defines the location of the file to load
  87689. */
  87690. function BinaryFileAssetTask(
  87691. /**
  87692. * Defines the name of the task
  87693. */
  87694. name,
  87695. /**
  87696. * Defines the location of the file to load
  87697. */
  87698. url) {
  87699. var _this = _super.call(this, name) || this;
  87700. _this.name = name;
  87701. _this.url = url;
  87702. return _this;
  87703. }
  87704. /**
  87705. * Execute the current task
  87706. * @param scene defines the scene where you want your assets to be loaded
  87707. * @param onSuccess is a callback called when the task is successfully executed
  87708. * @param onError is a callback called if an error occurs
  87709. */
  87710. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87711. var _this = this;
  87712. scene._loadFile(this.url, function (data) {
  87713. _this.data = data;
  87714. onSuccess();
  87715. }, undefined, true, true, function (request, exception) {
  87716. if (request) {
  87717. onError(request.status + " " + request.statusText, exception);
  87718. }
  87719. });
  87720. };
  87721. return BinaryFileAssetTask;
  87722. }(AbstractAssetTask));
  87723. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  87724. /**
  87725. * Define a task used by {BABYLON.AssetsManager} to load images
  87726. */
  87727. var ImageAssetTask = /** @class */ (function (_super) {
  87728. __extends(ImageAssetTask, _super);
  87729. /**
  87730. * Creates a new ImageAssetTask
  87731. * @param name defines the name of the task
  87732. * @param url defines the location of the image to load
  87733. */
  87734. function ImageAssetTask(
  87735. /**
  87736. * Defines the name of the task
  87737. */
  87738. name,
  87739. /**
  87740. * Defines the location of the image to load
  87741. */
  87742. url) {
  87743. var _this = _super.call(this, name) || this;
  87744. _this.name = name;
  87745. _this.url = url;
  87746. return _this;
  87747. }
  87748. /**
  87749. * Execute the current task
  87750. * @param scene defines the scene where you want your assets to be loaded
  87751. * @param onSuccess is a callback called when the task is successfully executed
  87752. * @param onError is a callback called if an error occurs
  87753. */
  87754. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87755. var _this = this;
  87756. var img = new Image();
  87757. BABYLON.Tools.SetCorsBehavior(this.url, img);
  87758. img.onload = function () {
  87759. _this.image = img;
  87760. onSuccess();
  87761. };
  87762. img.onerror = function (err) {
  87763. onError("Error loading image", err);
  87764. };
  87765. img.src = this.url;
  87766. };
  87767. return ImageAssetTask;
  87768. }(AbstractAssetTask));
  87769. BABYLON.ImageAssetTask = ImageAssetTask;
  87770. /**
  87771. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  87772. */
  87773. var TextureAssetTask = /** @class */ (function (_super) {
  87774. __extends(TextureAssetTask, _super);
  87775. /**
  87776. * Creates a new TextureAssetTask object
  87777. * @param name defines the name of the task
  87778. * @param url defines the location of the file to load
  87779. * @param noMipmap defines if mipmap should not be generated (default is false)
  87780. * @param invertY defines if texture must be inverted on Y axis (default is false)
  87781. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  87782. */
  87783. function TextureAssetTask(
  87784. /**
  87785. * Defines the name of the task
  87786. */
  87787. name,
  87788. /**
  87789. * Defines the location of the file to load
  87790. */
  87791. url,
  87792. /**
  87793. * Defines if mipmap should not be generated (default is false)
  87794. */
  87795. noMipmap,
  87796. /**
  87797. * Defines if texture must be inverted on Y axis (default is false)
  87798. */
  87799. invertY,
  87800. /**
  87801. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  87802. */
  87803. samplingMode) {
  87804. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  87805. var _this = _super.call(this, name) || this;
  87806. _this.name = name;
  87807. _this.url = url;
  87808. _this.noMipmap = noMipmap;
  87809. _this.invertY = invertY;
  87810. _this.samplingMode = samplingMode;
  87811. return _this;
  87812. }
  87813. /**
  87814. * Execute the current task
  87815. * @param scene defines the scene where you want your assets to be loaded
  87816. * @param onSuccess is a callback called when the task is successfully executed
  87817. * @param onError is a callback called if an error occurs
  87818. */
  87819. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87820. var onload = function () {
  87821. onSuccess();
  87822. };
  87823. var onerror = function (message, exception) {
  87824. onError(message, exception);
  87825. };
  87826. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  87827. };
  87828. return TextureAssetTask;
  87829. }(AbstractAssetTask));
  87830. BABYLON.TextureAssetTask = TextureAssetTask;
  87831. /**
  87832. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  87833. */
  87834. var CubeTextureAssetTask = /** @class */ (function (_super) {
  87835. __extends(CubeTextureAssetTask, _super);
  87836. /**
  87837. * Creates a new CubeTextureAssetTask
  87838. * @param name defines the name of the task
  87839. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  87840. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  87841. * @param noMipmap defines if mipmaps should not be generated (default is false)
  87842. * @param files defines the explicit list of files (undefined by default)
  87843. */
  87844. function CubeTextureAssetTask(
  87845. /**
  87846. * Defines the name of the task
  87847. */
  87848. name,
  87849. /**
  87850. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  87851. */
  87852. url,
  87853. /**
  87854. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  87855. */
  87856. extensions,
  87857. /**
  87858. * Defines if mipmaps should not be generated (default is false)
  87859. */
  87860. noMipmap,
  87861. /**
  87862. * Defines the explicit list of files (undefined by default)
  87863. */
  87864. files) {
  87865. var _this = _super.call(this, name) || this;
  87866. _this.name = name;
  87867. _this.url = url;
  87868. _this.extensions = extensions;
  87869. _this.noMipmap = noMipmap;
  87870. _this.files = files;
  87871. return _this;
  87872. }
  87873. /**
  87874. * Execute the current task
  87875. * @param scene defines the scene where you want your assets to be loaded
  87876. * @param onSuccess is a callback called when the task is successfully executed
  87877. * @param onError is a callback called if an error occurs
  87878. */
  87879. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87880. var onload = function () {
  87881. onSuccess();
  87882. };
  87883. var onerror = function (message, exception) {
  87884. onError(message, exception);
  87885. };
  87886. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  87887. };
  87888. return CubeTextureAssetTask;
  87889. }(AbstractAssetTask));
  87890. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  87891. /**
  87892. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  87893. */
  87894. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  87895. __extends(HDRCubeTextureAssetTask, _super);
  87896. /**
  87897. * Creates a new HDRCubeTextureAssetTask object
  87898. * @param name defines the name of the task
  87899. * @param url defines the location of the file to load
  87900. * @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.
  87901. * @param noMipmap defines if mipmaps should not be generated (default is false)
  87902. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  87903. * @param useInGammaSpace 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)
  87904. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  87905. */
  87906. function HDRCubeTextureAssetTask(
  87907. /**
  87908. * Defines the name of the task
  87909. */
  87910. name,
  87911. /**
  87912. * Defines the location of the file to load
  87913. */
  87914. url,
  87915. /**
  87916. * 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.
  87917. */
  87918. size,
  87919. /**
  87920. * Defines if mipmaps should not be generated (default is false)
  87921. */
  87922. noMipmap,
  87923. /**
  87924. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  87925. */
  87926. generateHarmonics,
  87927. /**
  87928. * 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)
  87929. */
  87930. useInGammaSpace,
  87931. /**
  87932. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  87933. */
  87934. usePMREMGenerator) {
  87935. if (noMipmap === void 0) { noMipmap = false; }
  87936. if (generateHarmonics === void 0) { generateHarmonics = true; }
  87937. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  87938. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  87939. var _this = _super.call(this, name) || this;
  87940. _this.name = name;
  87941. _this.url = url;
  87942. _this.size = size;
  87943. _this.noMipmap = noMipmap;
  87944. _this.generateHarmonics = generateHarmonics;
  87945. _this.useInGammaSpace = useInGammaSpace;
  87946. _this.usePMREMGenerator = usePMREMGenerator;
  87947. return _this;
  87948. }
  87949. /**
  87950. * Execute the current task
  87951. * @param scene defines the scene where you want your assets to be loaded
  87952. * @param onSuccess is a callback called when the task is successfully executed
  87953. * @param onError is a callback called if an error occurs
  87954. */
  87955. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  87956. var onload = function () {
  87957. onSuccess();
  87958. };
  87959. var onerror = function (message, exception) {
  87960. onError(message, exception);
  87961. };
  87962. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  87963. };
  87964. return HDRCubeTextureAssetTask;
  87965. }(AbstractAssetTask));
  87966. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  87967. /**
  87968. * This class can be used to easily import assets into a scene
  87969. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  87970. */
  87971. var AssetsManager = /** @class */ (function () {
  87972. /**
  87973. * Creates a new AssetsManager
  87974. * @param scene defines the scene to work on
  87975. */
  87976. function AssetsManager(scene) {
  87977. this._isLoading = false;
  87978. this._tasks = new Array();
  87979. this._waitingTasksCount = 0;
  87980. this._totalTasksCount = 0;
  87981. /**
  87982. * Observable called when all tasks are processed
  87983. */
  87984. this.onTaskSuccessObservable = new BABYLON.Observable();
  87985. /**
  87986. * Observable called when a task had an error
  87987. */
  87988. this.onTaskErrorObservable = new BABYLON.Observable();
  87989. /**
  87990. * Observable called when a task is successful
  87991. */
  87992. this.onTasksDoneObservable = new BABYLON.Observable();
  87993. /**
  87994. * Observable called when a task is done (whatever the result is)
  87995. */
  87996. this.onProgressObservable = new BABYLON.Observable();
  87997. /**
  87998. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  87999. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  88000. */
  88001. this.useDefaultLoadingScreen = true;
  88002. this._scene = scene;
  88003. }
  88004. /**
  88005. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  88006. * @param taskName defines the name of the new task
  88007. * @param meshesNames defines the name of meshes to load
  88008. * @param rootUrl defines the root url to use to locate files
  88009. * @param sceneFilename defines the filename of the scene file
  88010. * @returns a new {BABYLON.MeshAssetTask} object
  88011. */
  88012. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  88013. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  88014. this._tasks.push(task);
  88015. return task;
  88016. };
  88017. /**
  88018. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  88019. * @param taskName defines the name of the new task
  88020. * @param url defines the url of the file to load
  88021. * @returns a new {BABYLON.TextFileAssetTask} object
  88022. */
  88023. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  88024. var task = new TextFileAssetTask(taskName, url);
  88025. this._tasks.push(task);
  88026. return task;
  88027. };
  88028. /**
  88029. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  88030. * @param taskName defines the name of the new task
  88031. * @param url defines the url of the file to load
  88032. * @returns a new {BABYLON.BinaryFileAssetTask} object
  88033. */
  88034. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  88035. var task = new BinaryFileAssetTask(taskName, url);
  88036. this._tasks.push(task);
  88037. return task;
  88038. };
  88039. /**
  88040. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  88041. * @param taskName defines the name of the new task
  88042. * @param url defines the url of the file to load
  88043. * @returns a new {BABYLON.ImageAssetTask} object
  88044. */
  88045. AssetsManager.prototype.addImageTask = function (taskName, url) {
  88046. var task = new ImageAssetTask(taskName, url);
  88047. this._tasks.push(task);
  88048. return task;
  88049. };
  88050. /**
  88051. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  88052. * @param taskName defines the name of the new task
  88053. * @param url defines the url of the file to load
  88054. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  88055. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  88056. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  88057. * @returns a new {BABYLON.TextureAssetTask} object
  88058. */
  88059. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  88060. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  88061. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  88062. this._tasks.push(task);
  88063. return task;
  88064. };
  88065. /**
  88066. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  88067. * @param taskName defines the name of the new task
  88068. * @param url defines the url of the file to load
  88069. * @param extensions defines the extension to use to load the cube map (can be null)
  88070. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  88071. * @param files defines the list of files to load (can be null)
  88072. * @returns a new {BABYLON.CubeTextureAssetTask} object
  88073. */
  88074. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  88075. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  88076. this._tasks.push(task);
  88077. return task;
  88078. };
  88079. /**
  88080. *
  88081. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  88082. * @param taskName defines the name of the new task
  88083. * @param url defines the url of the file to load
  88084. * @param size defines the size you want for the cubemap (can be null)
  88085. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  88086. * @param generateHarmonics defines if you want to automatically generate (true by default)
  88087. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  88088. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  88089. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  88090. */
  88091. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  88092. if (noMipmap === void 0) { noMipmap = false; }
  88093. if (generateHarmonics === void 0) { generateHarmonics = true; }
  88094. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  88095. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  88096. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  88097. this._tasks.push(task);
  88098. return task;
  88099. };
  88100. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  88101. var _this = this;
  88102. this._waitingTasksCount--;
  88103. try {
  88104. if (task.taskState === AssetTaskState.DONE) {
  88105. // Let's remove successfull tasks
  88106. BABYLON.Tools.SetImmediate(function () {
  88107. var index = _this._tasks.indexOf(task);
  88108. if (index > -1) {
  88109. _this._tasks.splice(index, 1);
  88110. }
  88111. });
  88112. }
  88113. if (this.onProgress) {
  88114. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  88115. }
  88116. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  88117. }
  88118. catch (e) {
  88119. BABYLON.Tools.Error("Error running progress callbacks.");
  88120. console.log(e);
  88121. }
  88122. if (this._waitingTasksCount === 0) {
  88123. try {
  88124. if (this.onFinish) {
  88125. this.onFinish(this._tasks);
  88126. }
  88127. this.onTasksDoneObservable.notifyObservers(this._tasks);
  88128. }
  88129. catch (e) {
  88130. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  88131. console.log(e);
  88132. }
  88133. this._isLoading = false;
  88134. this._scene.getEngine().hideLoadingUI();
  88135. }
  88136. };
  88137. AssetsManager.prototype._runTask = function (task) {
  88138. var _this = this;
  88139. var done = function () {
  88140. try {
  88141. if (_this.onTaskSuccess) {
  88142. _this.onTaskSuccess(task);
  88143. }
  88144. _this.onTaskSuccessObservable.notifyObservers(task);
  88145. _this._decreaseWaitingTasksCount(task);
  88146. }
  88147. catch (e) {
  88148. error("Error executing task success callbacks", e);
  88149. }
  88150. };
  88151. var error = function (message, exception) {
  88152. task._setErrorObject(message, exception);
  88153. if (_this.onTaskError) {
  88154. _this.onTaskError(task);
  88155. }
  88156. _this.onTaskErrorObservable.notifyObservers(task);
  88157. _this._decreaseWaitingTasksCount(task);
  88158. };
  88159. task.run(this._scene, done, error);
  88160. };
  88161. /**
  88162. * Reset the {BABYLON.AssetsManager} and remove all tasks
  88163. * @return the current instance of the {BABYLON.AssetsManager}
  88164. */
  88165. AssetsManager.prototype.reset = function () {
  88166. this._isLoading = false;
  88167. this._tasks = new Array();
  88168. return this;
  88169. };
  88170. /**
  88171. * Start the loading process
  88172. * @return the current instance of the {BABYLON.AssetsManager}
  88173. */
  88174. AssetsManager.prototype.load = function () {
  88175. if (this._isLoading) {
  88176. return this;
  88177. }
  88178. this._isLoading = true;
  88179. this._waitingTasksCount = this._tasks.length;
  88180. this._totalTasksCount = this._tasks.length;
  88181. if (this._waitingTasksCount === 0) {
  88182. this._isLoading = false;
  88183. if (this.onFinish) {
  88184. this.onFinish(this._tasks);
  88185. }
  88186. this.onTasksDoneObservable.notifyObservers(this._tasks);
  88187. return this;
  88188. }
  88189. if (this.useDefaultLoadingScreen) {
  88190. this._scene.getEngine().displayLoadingUI();
  88191. }
  88192. for (var index = 0; index < this._tasks.length; index++) {
  88193. var task = this._tasks[index];
  88194. this._runTask(task);
  88195. }
  88196. return this;
  88197. };
  88198. return AssetsManager;
  88199. }());
  88200. BABYLON.AssetsManager = AssetsManager;
  88201. })(BABYLON || (BABYLON = {}));
  88202. //# sourceMappingURL=babylon.assetsManager.js.map
  88203. "use strict";
  88204. var BABYLON;
  88205. (function (BABYLON) {
  88206. var serializedGeometries = [];
  88207. var serializeGeometry = function (geometry, serializationGeometries) {
  88208. if (serializedGeometries[geometry.id]) {
  88209. return;
  88210. }
  88211. if (geometry.doNotSerialize) {
  88212. return;
  88213. }
  88214. if (geometry instanceof BABYLON.BoxGeometry) {
  88215. serializationGeometries.boxes.push(geometry.serialize());
  88216. }
  88217. else if (geometry instanceof BABYLON.SphereGeometry) {
  88218. serializationGeometries.spheres.push(geometry.serialize());
  88219. }
  88220. else if (geometry instanceof BABYLON.CylinderGeometry) {
  88221. serializationGeometries.cylinders.push(geometry.serialize());
  88222. }
  88223. else if (geometry instanceof BABYLON.TorusGeometry) {
  88224. serializationGeometries.toruses.push(geometry.serialize());
  88225. }
  88226. else if (geometry instanceof BABYLON.GroundGeometry) {
  88227. serializationGeometries.grounds.push(geometry.serialize());
  88228. }
  88229. else if (geometry instanceof BABYLON.Plane) {
  88230. serializationGeometries.planes.push(geometry.serialize());
  88231. }
  88232. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  88233. serializationGeometries.torusKnots.push(geometry.serialize());
  88234. }
  88235. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  88236. throw new Error("Unknown primitive type");
  88237. }
  88238. else {
  88239. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  88240. }
  88241. serializedGeometries[geometry.id] = true;
  88242. };
  88243. var serializeMesh = function (mesh, serializationScene) {
  88244. var serializationObject = {};
  88245. // Geometry
  88246. var geometry = mesh._geometry;
  88247. if (geometry) {
  88248. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  88249. // 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
  88250. serializeGeometry(geometry, serializationScene.geometries);
  88251. }
  88252. }
  88253. // Custom
  88254. if (mesh.serialize) {
  88255. mesh.serialize(serializationObject);
  88256. }
  88257. return serializationObject;
  88258. };
  88259. var finalizeSingleMesh = function (mesh, serializationObject) {
  88260. //only works if the mesh is already loaded
  88261. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  88262. //serialize material
  88263. if (mesh.material) {
  88264. if (mesh.material instanceof BABYLON.StandardMaterial) {
  88265. serializationObject.materials = serializationObject.materials || [];
  88266. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  88267. serializationObject.materials.push(mesh.material.serialize());
  88268. }
  88269. }
  88270. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  88271. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  88272. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  88273. serializationObject.multiMaterials.push(mesh.material.serialize());
  88274. }
  88275. }
  88276. }
  88277. //serialize geometry
  88278. var geometry = mesh._geometry;
  88279. if (geometry) {
  88280. if (!serializationObject.geometries) {
  88281. serializationObject.geometries = {};
  88282. serializationObject.geometries.boxes = [];
  88283. serializationObject.geometries.spheres = [];
  88284. serializationObject.geometries.cylinders = [];
  88285. serializationObject.geometries.toruses = [];
  88286. serializationObject.geometries.grounds = [];
  88287. serializationObject.geometries.planes = [];
  88288. serializationObject.geometries.torusKnots = [];
  88289. serializationObject.geometries.vertexData = [];
  88290. }
  88291. serializeGeometry(geometry, serializationObject.geometries);
  88292. }
  88293. // Skeletons
  88294. if (mesh.skeleton) {
  88295. serializationObject.skeletons = serializationObject.skeletons || [];
  88296. serializationObject.skeletons.push(mesh.skeleton.serialize());
  88297. }
  88298. //serialize the actual mesh
  88299. serializationObject.meshes = serializationObject.meshes || [];
  88300. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  88301. }
  88302. };
  88303. var SceneSerializer = /** @class */ (function () {
  88304. function SceneSerializer() {
  88305. }
  88306. SceneSerializer.ClearCache = function () {
  88307. serializedGeometries = [];
  88308. };
  88309. SceneSerializer.Serialize = function (scene) {
  88310. var serializationObject = {};
  88311. SceneSerializer.ClearCache();
  88312. // Scene
  88313. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  88314. serializationObject.autoClear = scene.autoClear;
  88315. serializationObject.clearColor = scene.clearColor.asArray();
  88316. serializationObject.ambientColor = scene.ambientColor.asArray();
  88317. serializationObject.gravity = scene.gravity.asArray();
  88318. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  88319. serializationObject.workerCollisions = scene.workerCollisions;
  88320. // Fog
  88321. if (scene.fogMode && scene.fogMode !== 0) {
  88322. serializationObject.fogMode = scene.fogMode;
  88323. serializationObject.fogColor = scene.fogColor.asArray();
  88324. serializationObject.fogStart = scene.fogStart;
  88325. serializationObject.fogEnd = scene.fogEnd;
  88326. serializationObject.fogDensity = scene.fogDensity;
  88327. }
  88328. //Physics
  88329. if (scene.isPhysicsEnabled()) {
  88330. var physicEngine = scene.getPhysicsEngine();
  88331. if (physicEngine) {
  88332. serializationObject.physicsEnabled = true;
  88333. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  88334. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  88335. }
  88336. }
  88337. // Metadata
  88338. if (scene.metadata) {
  88339. serializationObject.metadata = scene.metadata;
  88340. }
  88341. // Morph targets
  88342. serializationObject.morphTargetManagers = [];
  88343. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  88344. var abstractMesh = _a[_i];
  88345. var manager = abstractMesh.morphTargetManager;
  88346. if (manager) {
  88347. serializationObject.morphTargetManagers.push(manager.serialize());
  88348. }
  88349. }
  88350. // Lights
  88351. serializationObject.lights = [];
  88352. var index;
  88353. var light;
  88354. for (index = 0; index < scene.lights.length; index++) {
  88355. light = scene.lights[index];
  88356. if (!light.doNotSerialize) {
  88357. serializationObject.lights.push(light.serialize());
  88358. }
  88359. }
  88360. // Cameras
  88361. serializationObject.cameras = [];
  88362. for (index = 0; index < scene.cameras.length; index++) {
  88363. var camera = scene.cameras[index];
  88364. if (!camera.doNotSerialize) {
  88365. serializationObject.cameras.push(camera.serialize());
  88366. }
  88367. }
  88368. if (scene.activeCamera) {
  88369. serializationObject.activeCameraID = scene.activeCamera.id;
  88370. }
  88371. // Animations
  88372. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  88373. // Materials
  88374. serializationObject.materials = [];
  88375. serializationObject.multiMaterials = [];
  88376. var material;
  88377. for (index = 0; index < scene.materials.length; index++) {
  88378. material = scene.materials[index];
  88379. if (!material.doNotSerialize) {
  88380. serializationObject.materials.push(material.serialize());
  88381. }
  88382. }
  88383. // MultiMaterials
  88384. serializationObject.multiMaterials = [];
  88385. for (index = 0; index < scene.multiMaterials.length; index++) {
  88386. var multiMaterial = scene.multiMaterials[index];
  88387. serializationObject.multiMaterials.push(multiMaterial.serialize());
  88388. }
  88389. // Environment texture
  88390. if (scene.environmentTexture) {
  88391. serializationObject.environmentTexture = scene.environmentTexture.name;
  88392. }
  88393. // Skeletons
  88394. serializationObject.skeletons = [];
  88395. for (index = 0; index < scene.skeletons.length; index++) {
  88396. var skeleton = scene.skeletons[index];
  88397. if (!skeleton.doNotSerialize) {
  88398. serializationObject.skeletons.push(skeleton.serialize());
  88399. }
  88400. }
  88401. // Transform nodes
  88402. serializationObject.transformNodes = [];
  88403. for (index = 0; index < scene.transformNodes.length; index++) {
  88404. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  88405. }
  88406. // Geometries
  88407. serializationObject.geometries = {};
  88408. serializationObject.geometries.boxes = [];
  88409. serializationObject.geometries.spheres = [];
  88410. serializationObject.geometries.cylinders = [];
  88411. serializationObject.geometries.toruses = [];
  88412. serializationObject.geometries.grounds = [];
  88413. serializationObject.geometries.planes = [];
  88414. serializationObject.geometries.torusKnots = [];
  88415. serializationObject.geometries.vertexData = [];
  88416. serializedGeometries = [];
  88417. var geometries = scene.getGeometries();
  88418. for (index = 0; index < geometries.length; index++) {
  88419. var geometry = geometries[index];
  88420. if (geometry.isReady()) {
  88421. serializeGeometry(geometry, serializationObject.geometries);
  88422. }
  88423. }
  88424. // Meshes
  88425. serializationObject.meshes = [];
  88426. for (index = 0; index < scene.meshes.length; index++) {
  88427. var abstractMesh = scene.meshes[index];
  88428. if (abstractMesh instanceof BABYLON.Mesh) {
  88429. var mesh = abstractMesh;
  88430. if (!mesh.doNotSerialize) {
  88431. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  88432. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  88433. }
  88434. }
  88435. }
  88436. }
  88437. // Particles Systems
  88438. serializationObject.particleSystems = [];
  88439. for (index = 0; index < scene.particleSystems.length; index++) {
  88440. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  88441. }
  88442. // Lens flares
  88443. serializationObject.lensFlareSystems = [];
  88444. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  88445. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  88446. }
  88447. // Shadows
  88448. serializationObject.shadowGenerators = [];
  88449. for (index = 0; index < scene.lights.length; index++) {
  88450. light = scene.lights[index];
  88451. var shadowGenerator = light.getShadowGenerator();
  88452. if (shadowGenerator) {
  88453. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  88454. }
  88455. }
  88456. // Action Manager
  88457. if (scene.actionManager) {
  88458. serializationObject.actions = scene.actionManager.serialize("scene");
  88459. }
  88460. // Audio
  88461. serializationObject.sounds = [];
  88462. for (index = 0; index < scene.soundTracks.length; index++) {
  88463. var soundtrack = scene.soundTracks[index];
  88464. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  88465. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  88466. }
  88467. }
  88468. return serializationObject;
  88469. };
  88470. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  88471. if (withParents === void 0) { withParents = false; }
  88472. if (withChildren === void 0) { withChildren = false; }
  88473. var serializationObject = {};
  88474. SceneSerializer.ClearCache();
  88475. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  88476. if (withParents || withChildren) {
  88477. //deliberate for loop! not for each, appended should be processed as well.
  88478. for (var i = 0; i < toSerialize.length; ++i) {
  88479. if (withChildren) {
  88480. toSerialize[i].getDescendants().forEach(function (node) {
  88481. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  88482. toSerialize.push(node);
  88483. }
  88484. });
  88485. }
  88486. //make sure the array doesn't contain the object already
  88487. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  88488. toSerialize.push(toSerialize[i].parent);
  88489. }
  88490. }
  88491. }
  88492. toSerialize.forEach(function (mesh) {
  88493. finalizeSingleMesh(mesh, serializationObject);
  88494. });
  88495. return serializationObject;
  88496. };
  88497. return SceneSerializer;
  88498. }());
  88499. BABYLON.SceneSerializer = SceneSerializer;
  88500. })(BABYLON || (BABYLON = {}));
  88501. //# sourceMappingURL=babylon.sceneSerializer.js.map
  88502. "use strict";
  88503. var BABYLON;
  88504. (function (BABYLON) {
  88505. var ReflectionProbe = /** @class */ (function () {
  88506. function ReflectionProbe(name, size, scene, generateMipMaps) {
  88507. if (generateMipMaps === void 0) { generateMipMaps = true; }
  88508. var _this = this;
  88509. this.name = name;
  88510. this._viewMatrix = BABYLON.Matrix.Identity();
  88511. this._target = BABYLON.Vector3.Zero();
  88512. this._add = BABYLON.Vector3.Zero();
  88513. this._invertYAxis = false;
  88514. this.position = BABYLON.Vector3.Zero();
  88515. this._scene = scene;
  88516. this._scene.reflectionProbes.push(this);
  88517. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  88518. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  88519. switch (faceIndex) {
  88520. case 0:
  88521. _this._add.copyFromFloats(1, 0, 0);
  88522. break;
  88523. case 1:
  88524. _this._add.copyFromFloats(-1, 0, 0);
  88525. break;
  88526. case 2:
  88527. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  88528. break;
  88529. case 3:
  88530. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  88531. break;
  88532. case 4:
  88533. _this._add.copyFromFloats(0, 0, 1);
  88534. break;
  88535. case 5:
  88536. _this._add.copyFromFloats(0, 0, -1);
  88537. break;
  88538. }
  88539. if (_this._attachedMesh) {
  88540. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  88541. }
  88542. _this.position.addToRef(_this._add, _this._target);
  88543. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  88544. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  88545. scene._forcedViewPosition = _this.position;
  88546. });
  88547. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  88548. scene._forcedViewPosition = null;
  88549. scene.updateTransformMatrix(true);
  88550. });
  88551. if (scene.activeCamera) {
  88552. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  88553. }
  88554. }
  88555. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  88556. get: function () {
  88557. return this._renderTargetTexture.samples;
  88558. },
  88559. set: function (value) {
  88560. this._renderTargetTexture.samples = value;
  88561. },
  88562. enumerable: true,
  88563. configurable: true
  88564. });
  88565. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  88566. get: function () {
  88567. return this._renderTargetTexture.refreshRate;
  88568. },
  88569. set: function (value) {
  88570. this._renderTargetTexture.refreshRate = value;
  88571. },
  88572. enumerable: true,
  88573. configurable: true
  88574. });
  88575. ReflectionProbe.prototype.getScene = function () {
  88576. return this._scene;
  88577. };
  88578. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  88579. get: function () {
  88580. return this._renderTargetTexture;
  88581. },
  88582. enumerable: true,
  88583. configurable: true
  88584. });
  88585. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  88586. get: function () {
  88587. return this._renderTargetTexture.renderList;
  88588. },
  88589. enumerable: true,
  88590. configurable: true
  88591. });
  88592. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  88593. this._attachedMesh = mesh;
  88594. };
  88595. /**
  88596. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  88597. *
  88598. * @param renderingGroupId The rendering group id corresponding to its index
  88599. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  88600. */
  88601. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  88602. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  88603. };
  88604. ReflectionProbe.prototype.dispose = function () {
  88605. var index = this._scene.reflectionProbes.indexOf(this);
  88606. if (index !== -1) {
  88607. // Remove from the scene if found
  88608. this._scene.reflectionProbes.splice(index, 1);
  88609. }
  88610. if (this._renderTargetTexture) {
  88611. this._renderTargetTexture.dispose();
  88612. this._renderTargetTexture = null;
  88613. }
  88614. };
  88615. return ReflectionProbe;
  88616. }());
  88617. BABYLON.ReflectionProbe = ReflectionProbe;
  88618. })(BABYLON || (BABYLON = {}));
  88619. //# sourceMappingURL=babylon.reflectionProbe.js.map
  88620. "use strict";
  88621. var BABYLON;
  88622. (function (BABYLON) {
  88623. var Layer = /** @class */ (function () {
  88624. function Layer(name, imgUrl, scene, isBackground, color) {
  88625. this.name = name;
  88626. this.scale = new BABYLON.Vector2(1, 1);
  88627. this.offset = new BABYLON.Vector2(0, 0);
  88628. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  88629. this.layerMask = 0x0FFFFFFF;
  88630. this._vertexBuffers = {};
  88631. // Events
  88632. /**
  88633. * An event triggered when the layer is disposed.
  88634. */
  88635. this.onDisposeObservable = new BABYLON.Observable();
  88636. /**
  88637. * An event triggered before rendering the scene
  88638. */
  88639. this.onBeforeRenderObservable = new BABYLON.Observable();
  88640. /**
  88641. * An event triggered after rendering the scene
  88642. */
  88643. this.onAfterRenderObservable = new BABYLON.Observable();
  88644. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  88645. this.isBackground = isBackground === undefined ? true : isBackground;
  88646. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  88647. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  88648. this._scene.layers.push(this);
  88649. var engine = this._scene.getEngine();
  88650. // VBO
  88651. var vertices = [];
  88652. vertices.push(1, 1);
  88653. vertices.push(-1, 1);
  88654. vertices.push(-1, -1);
  88655. vertices.push(1, -1);
  88656. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  88657. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  88658. this._createIndexBuffer();
  88659. // Effects
  88660. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  88661. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  88662. }
  88663. Object.defineProperty(Layer.prototype, "onDispose", {
  88664. set: function (callback) {
  88665. if (this._onDisposeObserver) {
  88666. this.onDisposeObservable.remove(this._onDisposeObserver);
  88667. }
  88668. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  88669. },
  88670. enumerable: true,
  88671. configurable: true
  88672. });
  88673. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  88674. set: function (callback) {
  88675. if (this._onBeforeRenderObserver) {
  88676. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  88677. }
  88678. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  88679. },
  88680. enumerable: true,
  88681. configurable: true
  88682. });
  88683. Object.defineProperty(Layer.prototype, "onAfterRender", {
  88684. set: function (callback) {
  88685. if (this._onAfterRenderObserver) {
  88686. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  88687. }
  88688. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  88689. },
  88690. enumerable: true,
  88691. configurable: true
  88692. });
  88693. Layer.prototype._createIndexBuffer = function () {
  88694. var engine = this._scene.getEngine();
  88695. // Indices
  88696. var indices = [];
  88697. indices.push(0);
  88698. indices.push(1);
  88699. indices.push(2);
  88700. indices.push(0);
  88701. indices.push(2);
  88702. indices.push(3);
  88703. this._indexBuffer = engine.createIndexBuffer(indices);
  88704. };
  88705. Layer.prototype._rebuild = function () {
  88706. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88707. if (vb) {
  88708. vb._rebuild();
  88709. }
  88710. this._createIndexBuffer();
  88711. };
  88712. Layer.prototype.render = function () {
  88713. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  88714. // Check
  88715. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  88716. return;
  88717. var engine = this._scene.getEngine();
  88718. this.onBeforeRenderObservable.notifyObservers(this);
  88719. // Render
  88720. engine.enableEffect(currentEffect);
  88721. engine.setState(false);
  88722. // Texture
  88723. currentEffect.setTexture("textureSampler", this.texture);
  88724. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  88725. // Color
  88726. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  88727. // Scale / offset
  88728. currentEffect.setVector2("offset", this.offset);
  88729. currentEffect.setVector2("scale", this.scale);
  88730. // VBOs
  88731. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  88732. // Draw order
  88733. if (!this.alphaTest) {
  88734. engine.setAlphaMode(this.alphaBlendingMode);
  88735. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  88736. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  88737. }
  88738. else {
  88739. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  88740. }
  88741. this.onAfterRenderObservable.notifyObservers(this);
  88742. };
  88743. Layer.prototype.dispose = function () {
  88744. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88745. if (vertexBuffer) {
  88746. vertexBuffer.dispose();
  88747. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  88748. }
  88749. if (this._indexBuffer) {
  88750. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  88751. this._indexBuffer = null;
  88752. }
  88753. if (this.texture) {
  88754. this.texture.dispose();
  88755. this.texture = null;
  88756. }
  88757. // Remove from scene
  88758. var index = this._scene.layers.indexOf(this);
  88759. this._scene.layers.splice(index, 1);
  88760. // Callback
  88761. this.onDisposeObservable.notifyObservers(this);
  88762. this.onDisposeObservable.clear();
  88763. this.onAfterRenderObservable.clear();
  88764. this.onBeforeRenderObservable.clear();
  88765. };
  88766. return Layer;
  88767. }());
  88768. BABYLON.Layer = Layer;
  88769. })(BABYLON || (BABYLON = {}));
  88770. //# sourceMappingURL=babylon.layer.js.map
  88771. "use strict";
  88772. var BABYLON;
  88773. (function (BABYLON) {
  88774. var TextureTools = /** @class */ (function () {
  88775. function TextureTools() {
  88776. }
  88777. /**
  88778. * Uses the GPU to create a copy texture rescaled at a given size
  88779. * @param texture Texture to copy from
  88780. * @param width Desired width
  88781. * @param height Desired height
  88782. * @return Generated texture
  88783. */
  88784. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  88785. if (useBilinearMode === void 0) { useBilinearMode = true; }
  88786. var scene = texture.getScene();
  88787. var engine = scene.getEngine();
  88788. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  88789. rtt.wrapU = texture.wrapU;
  88790. rtt.wrapV = texture.wrapV;
  88791. rtt.uOffset = texture.uOffset;
  88792. rtt.vOffset = texture.vOffset;
  88793. rtt.uScale = texture.uScale;
  88794. rtt.vScale = texture.vScale;
  88795. rtt.uAng = texture.uAng;
  88796. rtt.vAng = texture.vAng;
  88797. rtt.wAng = texture.wAng;
  88798. rtt.coordinatesIndex = texture.coordinatesIndex;
  88799. rtt.level = texture.level;
  88800. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  88801. rtt._texture.isReady = false;
  88802. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88803. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88804. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  88805. passPostProcess.getEffect().executeWhenCompiled(function () {
  88806. passPostProcess.onApply = function (effect) {
  88807. effect.setTexture("textureSampler", texture);
  88808. };
  88809. var internalTexture = rtt.getInternalTexture();
  88810. if (internalTexture) {
  88811. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  88812. engine.unBindFramebuffer(internalTexture);
  88813. rtt.disposeFramebufferObjects();
  88814. passPostProcess.dispose();
  88815. internalTexture.isReady = true;
  88816. }
  88817. });
  88818. return rtt;
  88819. };
  88820. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  88821. if (!scene._environmentBRDFTexture) {
  88822. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  88823. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88824. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88825. scene._environmentBRDFTexture = texture;
  88826. }
  88827. return scene._environmentBRDFTexture;
  88828. };
  88829. TextureTools._environmentBRDFBase64Texture = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR4Xu19Z7PtTHbW1g3jMMbGmGDAZAMm5xxMLDAU0WSKWOQcCoqccw6eGdtgk4yNbZxnvvAL+Af8Af6AsQl+06ako9X36dXPSi3pnPu+cz/cOntL3S1pq5+w1mrpLs/eud9fvn27rf9evPPwFz+v22S7fGZ/n7/70G79J5/Xv/qzbLP+Pnvvoc/6Tz7jX/15/c62LfeH7fofbpfP3l/ct36Wf+u4+D37+XYb++G26LPsr/zFttnPuh37bm1bt0f7MvtlnOx4uv0H4fty8UUsz77rfn/57u32cgXvDv72eQf0tl0+G38b0Nf9K4Dl704MEfA16KsE8Gw9JgD+DQE8EA0DT2b7GwK4GHnF4a8iguXZt9/vL5/dbisJbEq/uwD5vIK/fbbAv4N9U/8nJIDNCazKvBLBGwdwu62OhajxmQSAx6gqNp5HCg9wPan2nwSNjhLD8ux/3u8vP3y7vbwDAYjtR8AzFyDqLu1Q+YEINnew23rPCYiKb+q/K7o4AVT4tg0t/h4ydJZfkQASQ/d5b9fZ/Z1ENmuPn/cwYCYEELBguKC3nRkCnE0AFOwOKCOAR/sH/L4hgFMpbSWP5dn/uN9ffs7t9mJ5cAHoBLTyszBAFJ/F/xIKdASw5wgaEWDMLySxAk4svf6L+4QAGPiJCziNAPb4f3UZ2dh/m+z7BK4SAPYrxf5FB6ABPgCUAfANAZwKyscc7IEA/vv9/uLzbreXzx9cQCMACAl00m8jAlF7ov6SCMQ8gJsMFFBnCECSg5H6TxJAU3vPAbwhgFfz9AABeOEDBcIbB3AqPzwQwH+731/8sNvt5Ydut5e3B2C/fG9P+jESgGz/RgxG9r9VAwTUUh0goQDafUz+DYnAnSha5l99Z1l/yQVswAZSGIAugNd/9xBgCw9E8aECkHUB22QPHIAVDlQdQAMWAibhBgZAasAVHUAI8Cqg96Tm0bj3VBS9jwd7IIBvuN9ffMHt9vLTbreXy+32QlwAhgMIeuNzKwOqCoB2Aa00KHE+EsIeDuj4H2N+Hf/TfAC6A4nhgQCQDDwiaKDXiq9KgBEJNPArAtCk0AEd2mpAizW3/lYIoANpBPg3BPA+hjs/9eXZV+0E8Bm32wsJA9aEoBCAuAABPiEAC/yDC4gSgRgKRHkAlgsI6v7iEFqJEMgBwb4BGkEfEEDnDlReoAP/SQRgOYIB+IYDMEE/SQBbXoLNr0jhq4qOZc0PHBSf5oKW519xvz//kbfby8+83V68ABfwniIBgwgQ/HoRUMv8w5qAoQqgk4DWQiCw+63eD8k/XAPQgK5s/5a5xzAAqgR6wY9k+ZEMtCOoJABb230hEHMFWQdgAl0Ap/+uc6tKBrrP/n0AuwfiNwTwNKguHHV5/qX3+/M1B/Ddb7cXax7g2e324vaQB3hhkMAW92tHoFb96cVAbimwkgQ0Vv7R+D8iACfuxzKfLvnNlAAjAsBwwP2MwLQAD9sbYJME0AFcg5uBPSAA0x0AobhtcDKDA0j3KYDhk7Hp8uKj9/vzH3C7vfget9uLT9nDgDUZuOYCLBJA8MNKPyGGIftPrL+4gy3eh5p/lwRUYYAs9Fn7tM/E9lvJwCH2DxJ/mPTr4nyyLiDtBgTAGCrgNuPzNuETgN+suEEAFhng9lkCoICMLH7V0isCeEMCxylrefkl9/uzz90J4NNUGLDmAnYXINUBrf5dCCAuQCcCvYVAYPk3G++VAveVfkIAFRLolgbr2F9ifP33pAqAV/fHRF4HcAS7AKlAAEIYFNwITOszs/wMsB6II4BXFZ0QwBsSOEYCDwTw2TsBfPrt9uLlqzCgcwFABI0EVCiANl8Uvq0JWNsi2JPZ/0YKsOiHxftsW4v51ZqAaBWgZf91PsBL/jFHwEqBR1cCiuJ3gAfCmCEA3cf8rmz8AMZHIoA3JDBPAsuHVgL4jNvt+UoCH34ggK0asIYBGArsAB7AD+reQgCl+GwZ8LaNlP3MEEDaSg4ACMGr/+ulwV4JsAEfLH42/vdKgWElAJ4QpBl+LAlKErHwt+oGMgTA2ngE4IUIOH3dGr/hAKT/m/UBdSJYPuVL7vflU26352sScCWAD+0EsCcDVxewKjfmAzAsENVn4EfgdySgnYB81yEAgL4RA8T8mTUASAAYBgylQAkL8K/+zL6rsl8qF6ArAeS7WRGoAB8Sf7isN/VZqTs6jQ5wXlweWfyqpQ8I4I0TmCCAT/3I/b48u92ef9bt9nwNAdZE4FoOFALYXcAGegkDMByAzzQEgJh+cAIs/legH0IA5QTCPADE+7ISkD0TgA/8sBIgLQfOgF/F9kPcr+J8fIYguyCILQRKgV4DNviOzoKqeJS0u4AA3pBAjQSWT//I/b5OmC0MWB3ASgBrGLA+IryvDNxCgRXo+wKhjgwk8bcTwUACsJ09ANRVAALwCxmEoFcrAUsuAJ4M1E8BDuHABAHomJ8RgACrZfQLyT9dBWi2OOEG9NJd/TDQ8HAQuBE97ZhjGKy6o+imnU+4gDckkCeB5cMfud/v6zr9Dz84gOdCAM/3JwQhF9CAD25gBWWz/8wNgMpj3K9Lfy0foMMBVffXyT4r+cceC9bvCcDFP0311QrATPkvWgosYQFLAuoqQEcQuw3v2si25F+M1RkZXLUU+CgBmCBOEsCbvECOBJbP+Oj9fv+u2+3Zp91uz9cy4Kfebs/3ROD6iPD2b10YJCXB+0PyrgsHdtBuRACfBeTN+uM+suJPSEDbfh3/oxPoHgwiC3/06j8Eutj69sAQqj++I0CUfvIpwCEvYCT90O4Pn1XsT5Ve1/+dcp9FBh3woqXBSEJkvjHHEOUPqJPAjUUCeOMGfCJYPvOj9/t7//d2e7YmAlcS2B3A8xcPYcBm/7ULEDIQew+5gS0EIEA31R8Uf6gAoBsgKwBd9ddvBBJAs6XARgLQXQ2o7T8+IETe+9eRACg7rhCMVgCiE8D4O9wOCb2ubOht1/vYd2ubzLlgKbBHEDSnAMfL6durVm8qBPwXWz7rY/f7/X/fbsvL2+3Zqv4QAjzfw4COAMAJbEC3wC8koBJ9lAhgxZ+4hi3Oh/f8dU8EqtV/JhHgWn9cC4CJQZXZp6GAk/1nawMkrrcqAiwPIIA2FwOB2oaAF5UkcX+GADBs0I5gsNbBQqCorJcFJjqWKvhNMjky0Aek7/LZH7vf3/vO2215vruAD91uz/dSYCOAPQzYkoD7vw34sFIQw4LNymNSUKk8Wv0hCYhkoJ74Q6BboO9eDKoWAHXvBiCvAdPZf4nt3QqA924AbfXV8t8uN4Bt2We029WkoErWpSoCSm11TM8AOYA5uRS4RAITIQDDavaYHxCcm5exfM7H7vd3v2N9McDt9uxDD//WKsAG/ue32/M1DEACuO3g1jkBsf57fqCL/7UbIISAio85AAG0VQEYiIC9DJTYfy/+Dx8HlpeDRK8G90IBHQbgWgD2WT8LoOJ7NyeA5JEkAwwxmuqzur5X6y+sBEwDMggrqoBNH7c68Puk/fI9Vwfwvx4e6H724oEA1iSg5AAaAewlweeyLmAnAHQCTfU1CTAH4GyTMt+QDMRFQFEYQB71lXUAOjHYlvTqh4N2xe5yASoh2PpaJUGDBDrLr9cGIDlY1l+vDlQOAQHckYMiA68KMFsGtOy65RCGsMIDT+QqJoD3yUwCy/f+6P3+7koAt50AXrwigM0FrIuEoBrwHMMAUhmQUKAlAwHo7VmAPURo9h/r//ozLv1V7/5v6wGMV4B3rwYPXEBqIZAQwp4TYDE+LQlqtQfw6my/LgsyZaeLg7wVgmDnWQ5AA5ZWCDRx7ECzyn3udgFptFCIgTlyFRMEUCKgA+O/jl2Xz/3o/f7Otz88QvpszQOsLmAPARoBSDVgud02AthdwPZ5BSxUBVr8L3kAVHrvs076KSLQi3/M9QCJ7H/G/rf4n8X41XIgcwHecuBMDgAe+BHA6uQgqnvbF5DB5hwUQM3vQgIWkKOVftH+gAC6cz0RXZ9MjmD5fh/ZCWCd1CsB7CSwhgArAUgIIC5AQoDOCewJwab+CH79WR4C0mQAZT4hEQS9DgfEztNkoEECDfi6FAhZflb6Q1XXqwHDEECpvZX4a0qP1l7bfAS98cQfzQUo9a4mASMC0CsIm6JGK/2i/QkCuFK9PxmIYPm8nQDu795uy3K7LTvwVyJAB7ARwJoAVLkA7QIkJ9A5AQS95Ad2YmgvAJWwQFcBpB38pUuB9wVKbAWgCXwV86Mz2ICKTwUWFgOxMEBicr0eoBwCGBUADfxsDsAiA+zflNay31ZcfnAdAAXgDGkcdAcfZCJYfuCX3O9vf/vtthHAmgcQF7ATwOoAtn9IACsRSDkQ/wqIIUGoXYEQQ/sL5IDJP539776DwodVAGlr5QBgP8sDdApP3gSUXQa8/rZsRaBeHmy+HwDyCI1MUNlZzX9iJSBO9igJGJYCo4RdIqMfJQ4Ztq8C7FXjHuSnQ92XH/yvdwJ4Z68ErOXAlQRW0O9/JRG42v9GBHsuAImAqv+uzDo30C3yAfVHoHeg9xyAp/7wlp+WFCSWv1sOTBb+0EoAZP5DImBrApAUMFHolQG19c+EAkbpjyUEdQ6gm/QEsCzZFxKDlWNwprJVWfBm/1WAvWrcQ0ie7Lz80H91v7/9v263+9sPI2zrAZAEdvXvXMBKBJIIFDcgyUAEvHICg/o7wA/Bvyt35wCc2F9Cg03RvRyAA34N8hD0xsIfXP7bQgDMFSgyYO8GsF4N/hQ5ALak1yUGRQDZZJ5VWXgKEsie8yQuH63b8vn/8oEA3lsJYJ2EQgD73xX4z9bs/74gaHMBQgA7+DsXAJWBBniHCLTtNx2AUnkG/LYNiUCpvX7wp6sIOHF/lwgkNf8UGagwYMgLMBdgLQCyVgOyciCGCs5nz/Jr8EXOQOcQZEbrfjjTU8qaCBseMyx4vxPB8iP+RU8A24Kg9R8Qgaj/av8lDBgcwApQ+QdVgW0bKr3+jsk//AztzBKgtv4K+Kj08rl7JFgt9BnCAIsQcD2AsQAolQj0CAGAqhOFCK5u3cA+84dyIJLCPm6buAgoBa5qDoDF6wzUkZ13iSDKKwTamSKZSf29cuzJUwq7LV/wz18RwH2Nl9dKABLArv6bC5B/+9OBGxmsIIR1AQ3w2gk4RECTfwBulgC0rP96/FYJUOv9SzkAB/xuKTBY/qsTgZ0LILF/s/RW9v81ywEwhbeAwUIH6hRwGp+wEOhqoF49fojqQoPlR/+z+/3t77jd3n3rdru999CzEYAQAYJfXACEAqL8W5lQgA5uoJUK9zxBB3ii9ALiYT2AjvuN72wFILP+XdlP8gLKFeg6f5QM3AC+VlMMZ9ABGuN+VePHWL6tHVD23or3tQPo2iWfBRgShDp0ELcBjmIAbwTWqEzIJvLM6kEDEFcD9erxCzg3my4/9p/e7299x+323lu32+oAtjwAhgE7Cazqv7mAvRLQcgG7A9B5AAwHus87CWBYsIKFfe+eCSBgt2J+7QBQ+VsogOU/9fIPBvLhASEF8AHwlhPQ2wVYFhmo/Wby74QyYLcmQAEbbbue2FcnAb28QTmHQKBwNVCvHv8IESw//h/f7299pyIA7QIE/LsTeIbqL59hPUADvHIBG8jBIWgn0L4rsKMj2Noomz8QgZELsCoAAnh0Caj8lup7ib9tX+ZBoKgUmFkWTGJ8S/UHZa/kAHT+QGaeoeQmMUC/CoAzVYAjYDvSNwPCq8fPnINus/zEfwQE8O7tdt8dwGZjIQQQ9Y9cwAB+RQIC4I4MdvvdLL+O//E7LgLykn6q3Efjf6X8bOUfkoNYcQZ8z/KzBUBYCqT/YQgjBuOBHxPs7JHh7JoAy/IzWz+xEtBKBEYg8fIGw+SeQQQ+CzHZP+oWXWPU/8z9y0/+h/f729/5kAN4791X/6/cpl4SCsDfLRQwHEBLCmJFYH92vssNgBPo7D8qv4CekIHpAjKgx1iffGbKb5UAQwdguIAtz2KsEWj7vIQggNON91lYoIFN2mznYKj9UBmwQgXLLcDstRTdBchEFWAWcLP9MgC9cuzM8aXN8lP//v3+9v/uCUDyAM0FIBFADqAjAsgFiAvYwK3/MfAL8InSd/Yfy37Qpyv3OSTgxf8C5vZXPfF3aB2AA3hJGg5LghMOgCUBo8SgEAyC3Irvh5xAwhW0cT1iQBKYWds/QQLdeVUQcrEjeGoiWH7633sggHfWJOAaAkglYL/wLQyQf3tYsCp9CwmgFIgOgIJ/JwMdBuB3cQTDX4z9wR2whN+WE9idh67761p/F/8bpb8O/OotQCsJDhZfji0qT9p0LsCI83X9H8E9KH8iCSiTrQO29bwAAbvlCipPAw4T/oRKQAVElbaMJ472t7jnqnEjrlt+1t+539/6P4oAxLquawIkF7Bb/40M9hAAHcD2GVzABmBYKSgxfyMGAbROCipl1w6gs/8ZF0Cy/UIOOr7vHAIu9iHP/2v77yX9ROUt29+AHVUCnDJgtvSn8wXsnQGzIUAW3F27qFS4z2CrD07wCogqbR8LtGecUwR4vX/5OX/7FQFsOYC9FCiToBGAEAH83ZwA5AM06BspiPKrNQIt/kcg69iffBegNqVXb/wdQgIMC0DltUuQ+L+Bmz0OrNTdK/91+4JVf15SEPMCYRkwEfc3stBxurMS0AoTMKRocaV8cKw6jpcFsdUn2/8qRT8buGeP55HC8vP+5v3+1v99cADvvfNQBZB4dO24Kv5GAntSUOz/+n1wAis4wAnoMAC/N9svSUKsBABgmwPAbQTwWzsW/2vAI6j14h+1CEjnBYZFQWSxj+sEVFyPjgBBrhf+aOtPY39vRaBVJlQ2vyOGIATQsb6etBguDMSQyAF4IMhUAmZANNNnUNSqBDvtzzif6HSWL/wbuwN4eycA4gDEBQgRYPzfSGC3/BYBdOCHxKBHBAJoAbdWfIz1I9XXsf5g9y0yAJB7iUDPCaC6e2EA2ngMGyIHwAgBldncf4ID0EDXVp1NYmbnrclOtyfDhiPOoCO4CEXB/rOBfOZ4yy/8a7sDAALY1gKAfWMEgOovoNdk0IArKr+7gwH02gWQ2L4t/sEEoLL2IQnoFX96HYC4CIz/jcSgAJSVAtu2RPZ/SPRBHkC7AkYEqceC2fqBfdKaCcHAAeAkpKVBCANcElBVgBQRTC4HngHOTJ+rQo2jhEbP6xf/VU4AmBza7L+EAZgLgGSgxP8dGQDwmQOQbS2xp6oEWAnQn1seIEMCJO4fsv8Q2w/JQU0IJMvPiCCT/NPuQP/noJ0rAFBa23VSr1N/vQhIgxzzB9odMMIAkGvFZPF6JkyIlJeFFl6IcRYYX0ciOOOcll/6l+/3t/7fngPYy4BSCmyT0SGAlgvY4/+BAET10fZjUhAWCg2AV8nBEPQ6D6DJgSUAoQ/G+Dr+T9l/pfg0HxAs/e3WBUhbsihIgHKkHGiGCQHYO/UHomDgdd0BcRkZlYtyAFlgZNtlzqkSJcwc1xr/6FjLL/tLPQG8t+YA3tuXBKPiqISgAB//bjZdkoNE/Rs5EAIYXIAKCwYHYJADlvhalp8RgS4PogNwFN8jgo1A2LoALxRw1gA09TbCAjckQHBZlQEFwEoS0Iv1S3mAYFGPlwOIJn+0v+ocPohEsHzRX9gJYM0BvPvwTyoB2gGsP6iEAowANsBJWAAVgRYeAPCb/WdkAKEAttNJwRbzM+UPQI8K36k9Kf3RagBTe2vhj3o8uAFXLxUGxTdXBrK1AIltTZ2JzUe7Lp/Ralvxvrb5kcWP9nv2fwBzIRF4FRFkx/XcwRljHCGm5Vf++fv9re+63d4xCABVRhOAJoOtRCguQKoCmghwv7L/mBPQwB/KfMQhCEF0ym8RAUkIToUAxrP/gxOwSoDGmn9WCjTzASw3kHQA5poA7Q4g3n+MEMAChiadiopXwHZV26usvB43e/7Lr/pznADakmBdDcB8AFj+5ggcF4AhgAlwwyUM6m+pPgF8U3BS6jOdAAkJ3HUAO5C7ZKBT99/IVDsGhwyY3e8qNfhCERXDa5BrlW/ftaoqe265Ar0U+PIQQCUzqwqYBYfnSK4AcuW8sjmHaMzl1/zZnQDeud3eXRcCrfH/ngNYbyxzAKL8nQNAMiC5gI0gBNz42XIBAnAkBACwqDyWByPlp2BPWP7WD0Crs/5ewq+1JaBnWX8rEajbDiVAlbNpwHRyAJ4D6EqECQcQWfxo/0wI4E3wcPJnUbSLXqH5A26qHaD9kb7ssKaj+nV/ZiSALRG4rwhsJLBfUKt/k3yAJMGwEtCFBGD/PTIY4n6d8ANyaEk/Q/nPUv8h+WeRgXYCVgIwSwbK3osKi4PonEGUC2C2Pngc2LL73Xanlj9bBTg7BIgAFe2vuoxZS14B7wy/DCT8xX/qfn/rrYccwLtrElA7AJkgkrDSJUHJfO/Z/wZ4Kx8g4IXyYKfm0i9QfkoSJK5HghALr51Ce2Jwv0ad9BvAj1WCidKfZf1x3UDnvPQ90HYf7o1WfSQMGbOpU1D3H6oCynpjPE7VfSccpoalMEHNdAxFKkDLgDzTRo5ZaXukz1E34f1Gy2/8kzEB6MUlsjCoCwWMEAAdgOcGTECrnECn+JYTgPyABn0U82vwt7hfJft0rK9DAlHooTSolH94GxBUAnTSL/reAbz6UBADt344SDkIJBIT5E62HgnEAwgFmjq3ChFkAJUFd7Zd9fwsdZ89nnX85Tf/8Z0A1hwAOgDJAxBbuU1usboYCoiCKvWX+L/lAUDlNUG0bD8Bt7dviP9Vf0v9LbV3XQCz/3qbZf2d0h8D+JAPYDb/RAfArL1l92W7Z/OjEICpOZvkw7bES0EisET7M0RxRNkzx78qJGj37rf+MUUA+zoAnQjs1gTAhJNyFy4X7kBtkYHKB0ifDMgrLiADfJMESGa/Cwe0/a+CHsmA5QQ8N6ByAzJZh1IhEobOAegsvwaVDhEKDkCre0cielYbau4SQfIZggyIM0DMtMkc6ywnMHMsduzlt/+R+/2tt2+3d8QBiAtQSUBaEVDxPyYB22cEuiYDQgJtLUFk7539ke1vgAeAR05gC3ekbAclwuaEjEVA3XoAAnLpT6sBCuStrUrIpqsBHhkwcBOVTecFJAteCAFSyk/GzapwBOJofwV0mbEQkNX2p/X9HX9IEcB7eyLw3q8IlPgSbV/LBThEIMreQJkhAeYOIsDrsELV8VmIgHX9ITGo1L+BnxGB5wQY6IvKLzZZCKD7nsj8m+sADjoAVHk9ga19tF1CzSk5GO8T9MCUAdpZbSqEUW17lpNYfucfvN/fBgfwLlQBcEnwdkA9cdGiCjCgGrCpZhACDMSA6wL28dewgKl6GzuI963EXwtf1Nr/wQ0YMb+bCJwAPgKc5gPIPeiImeUC4B5J2zbZnGXBQjI4Mdk2HFNPYqv9MNlJCJByAzPPEezIiUAe7a8ANjPWGYpePc52Db/799/vb7/zKgQQAnhvDwH0cwFWLqBluwkRYJ7AqgoMTiHjApTqR9ZfbLxbCbCUX1wOKQGiO8ASn7XdKgMimL2SoG4nkxGVnqk+OoeBDHR4AN87EmCWnlULBGiBuiNJMFC5RJB8HsACRgYwZ7WpEEY2pNEuYOoYv/f37Q7g3dvtnT3+39YC6BBAv3IK1wVA9p8SAYC5gRDBqz53QDasvag/dQboGMCy0zBA7e/CgoTyszX/VeA35QeH1YGc2Hwr2YchGn5mJNGVd8FdoEOIHEBo9VkeQc3cqFJgEkPhxSBHwoIMCVTAlx1vlggq4y+/7/fe72+tDuDdV2XARgD7isDtd95BpZWjKRUov4Acwa6BT5OEsEjICg1aBUAl8DpwA2kgQeCYbHsjL0zygfKbll9XC5xk3zYGgM1yA0IKERGgI2PJQJ20M13CAQfgWv1kEjBj+Yc2zlqAGdWPgBPtrwI2O16FXMrn8Ad+z04AaxVgTwDiasAtBNgnrK4E6HBgSApichCBBHkBCnQNbmb1iTPoSEXlDXCfTv6x0EAA2OUDtCPA70bMT6sAXjVAlf4sIhieC8BYXy0CYk5gIPKCA8CJGzoAI5QYJqoRzx8NAZ6KCLLgzra7igSWP/i79hzA6gCAAMQFrBMNSUCrFypUm+x78k/cQRffY45AqatOGDJy0CDHkh5dDERielFhWvrTIYHO+icy/jK+qe6sCkCAH70erLsXylXMWv5GFowQrLyACISU6HZ0W+RALX0Qz2ug4NgYUWScRNQ+q6IZ8GbaVMCdHS99jX/4dwIBCAmsoNd5AHAB1sRDArByAV1YgLkBnfRDF6AtPbP4LNY32lkOgMX/tPynSKFzC466Y2JP+mT+mk8BOiVAVP2MA9COgH4nQGcgHxyCAe5uMicqARTcJ+QBIlB5+6O+V4E7c9wMCSx/9HfkCEDyAMPDJiQZ2AABqtZUVwG7s+ZWMlCDO/F9iPFZso9l/IkDaMRgxPqe4g8JQa30yg14pdaM7TddgWHxXcUPVgLqvnqyWw6AqrlT0jPV33AekYJb4IlAdfX+6LwR0BVi8Yhg+WO//X5/e68AyLMAawlwCAEwF2BkpTfgqwlu5QU6G45KrdYNsNi9qwAQMgjBnyEDI77XYGcxfjXut1wAhlfSptsGoNHJPab6XkLwTAeAk1MIidp+mJlRJYCqPxCABwizr0aUDl3I/ogEMsDMjJEZp0oYjECWP/HbSA4ACEDWAbA8gJ6MjADWbYP6i5LqvyRROBBABHgjXEAV14k963s7d0koOkm/s+J+FiaERADqbjkAHKNNrsRCoE7lmYsQ0HjlPm+dgMzKRLmQkkgyBJhR/SPWPwPyTJuriWD5U78FHMB7eyJQ5QDaYiBhXL0mgGWumRNQAO/KbieTASMOL8bvVgUSq2/lAvAaOvDiwiEjs6/BThdZ6bUBJNvfuQN0Z+pzVzI09nXqrT3UMRMAACAASURBVJcKg+J6xKAnLao7Tvruc6ZcyBS6EDpUXUIEvgyAz2oTnQuqe+aYzT386d98v69rALZ1AEIAazVgz/4zBzC8aorlAdS2rkIgC4e8v2TxkOsGMLeA45I6vgZ7ygFg4g8JQhOdl+FPZv+ZnRey0CQhE4PtH1TfCBmkXQd+S+1ZXkCTiQZq0gG4sb6qMHSAKFYQHpsIMoDMtKla/syYy5/9Tb0DWGP/7R8QgOUA2NtnzEw3LhRS6hjlA9CK6/gfS4XU5rOk427p9bg02cfATtS9CwGcSsB6/taTf9Zvx0ItvQ2JgH7WgEYyMMA+5AwmHMBMDsAjAhrPTz5M9H4mggy4M65g+XO/YSeAXf1lLYAsBca/24D7MwKdakBIYOUBxKYyJ0BDAeIOTOW2QI75AgVkXNVH7b+VBFTgDisAQda/gd5LrCrlZpa/WXJrEVBk+cGxNWAkqwDMQWiFNq2/zNKgDOi6A2NFICULRAV8rrSN7HgEzmh/NH4G2MZlDi8qXf78Fz8QgNj/thjIcADtvw9HNcgQwGxIwPIGLHTQVj8BfszWmzkAlZsQwFrlPbcCYOUCjBwKKwl6pUBRWyFhukxY7LmO7414X8f61BVY4YLY9iDBhy6BTX6LPJCoPHtcAXelbQRUD+gZEojGZyCvjrv8hV/fOwArBGBLgnFpcGdJYUJ0gNknxLDNCwm8xKEV6xtqPwt4DWpm92kIQICN7bSNF2Xv/pLfUgNd5wxoCEAA34GbqL0VAmhSuMIBuIqv8wGJRUQWmCzAfNIQwV/8tff7O+9BEhBKgEMiUIUAXjLQinMbAAAcCIruFWMVgBPFX28iLhW2Yvzu+JCo06A21wAQm69XRVJwk+RpaiEQCxeQKEDlaWhgtEWQWEqvt7vhwoQDKAFfjR+5hytdgjf20X1HLH/kIpa//GtUCLATgE4CogOQz628IwzslKx0gosuG1bWnuUGotJhyzUYYUIjBSsnoJKVXZnPCAeYo3EBH1UDDIA38CniiBR/CA1I1r5VEQBUg/1XVt8jjG7iWZUD5WEz5UIK8sRagIhYquQQgfqI/a/aeBYKZMOD5a/86r0MCGsApAqQcQDbgTQBMNuqJ70GE/nuOgMSGjDFj7ZZhNABnxBTIxon459Vfa9yYpUEEfRU5RXounEUkJEgGJlEYNb9O2IQ16hsO07y9nk2ETjzJKG4JIKUSlgQKqyDzgzQM22ic/AcxPLXflXSAew30no8eDsJvBGWyhmJsKojQOAOi3R0yRFtPcvuqxo/tf7qeryYv2T/mZqT0IARgfzmG9Eg6erP8Jvr+4Tk4Sk6IwnWfgA/IxsCPhmfKWuk3ugcqENIgLwC+hl1j4Ac7c+CPDNOd4/++q/ccwCRA1iFHkqAtBrA3ICh/J46Yp7AjM+DHIK27t1aA0YIbKGPIisrw59NAOqSH/0NEKyMCBS4qwnAtNpnk4JGnN8pfKYKoIgiA2R2DEYglW1XE8FZQI6AHu1vv8nf+BUPBNDKgFYOgDkAsHdmQhAnkhP74kNDg72OwgMP0CRuN90GW+CTdCwWoVluQKv3EAYQ1cZjuOpv9JXJNyT49KIgliMwlByVu7kJUFwvPBjcQuaxYSuUOBAGZMjGIxEP1BEQn3z/3/oi4gA0CQD4uxAACMBLCKLNjFSPJd3Q7rtJOWu1oZNcHMgmE+8H5T3P3Xj7OlCzCgEeN+sEVDs8Rpu4Ol9ggd1ScuYWkAQIsDv1lrYqB+BZ/2FfsBqQAe3sbZG6Xwn2aGzr3Ja//cuJA8CnAXfr314SajgBkwBwAs6EAwmwWWFChThY0s8iI297B3DDPYRtCLi3Psb2AdRAHrKvqb9BCEyNtaKXS4OkoqAnomXjKUEo9e/GSjqAs0HvAS8C5WzfaNwKES1/95cZDmAlAbIacPudIRcgi4H0oqBuUirgU6WDSVtJsHnJw8gtZNyGWeJLEJNn61vZzYjzo/3dQ0Ea1DgmUXMWAqTAbil9UOaLynttQj+iAzibCCLQRfstUM+ShJiqqP/y937p7gDuex5gBz5bByD23woDMA9ACeCAG8jkCLTis+8ZUhjCAisZOKvwySw/OoWONFWMrmv4ZsWAqX+wrXMGbLkwnMvgIowEIWuHTsV1CTKz978WeViA88IKDzRnA/Ts8TyCcUng7/+SngC2twFZJLBPljIB4IQ1wgA9waPM+rCfJApN9Tae1beOGZ1LO06CEKj7UbF9A7CVB7AShIa9R3Uf1gOwhF9V6S1iEEQFDqFN3my14IJEYNYRTANNERd+PZMMIsXXp7H8g198v68VgHf2uP9dBX5xAtvbgaUUqEqCg/1HKweAlx9vsLeGIlqxchWojCyqY1RCgXK5jxGHofIsD9B+V92nSAgIxCEkgLEGBU8mAaO4PgoVmEJbOQQG1CzIs+08Msg6kAwRzJBOlgiWf/SLRgewksCq8l0YAKBveQAgBGb/t4vDhJQmAwf4a9dQeZPWnJbiHMfgOYeNlAKlx3BFOxs3L6B+LySS8EUg6rzwuEgQ3luBGugDqx/lCzyCGPbtCBBi05M9Io2OFB4hEXgmGLMgzZDEjIvYruUf/0I7BGgkAJWAbY46SUArGThMyAIZVADH2ppEkiCBir2n5xmpu5ME1I5pUH+LYEnFICKEDpiFEADPSSu0JhQX/MphTBFBIYnI3MRjgLviLs48H9OR/JNf4IcAK9bxPwoV9TerAXgj4T0BOJk9MhAQDZOfACUCNgIy0zbTJpPZpyGAQwTiKug7AYkr0L+N991Vf00gpGyHINbK3yZVMQQwVT2xEMh1BEZ/Nvk1EKsKmgXyGeOeTQQdEf/TL3wggNX2b/H//jqwLRGo1gC0HMCeD9AlQPw+WDqZJEZIoCdaNY6OgOmFAVq5u7ae3Y9AHam7sd8kApUsZHaekclAvrv86eoBcwkZkFvrA1hf1wU4Cu4Btu1T/c8G/hWgrxDEmSFDc0D//OdDCEAqADoPIMnA7a8wrv6LpSEFfJlkoQtAdfKShEmAWlUDN7xgOYYE6DPuBY+Lv0W0HRXdK/cN2X6l0jqcsICubbx2AVeFAK7Sy+zV1YDiasAjgH6MvqZth+vXH6sksfyLn/eKAFaw6yoA5gEE9FYScDsZZfsR8CwhSJNb2Tq5UVLsQO0lE5Pk4bqRiBDU/oEcHFVn9X1T4dFZ6TKhYfWZcltqbm6HsZm6D07QKuGRcqQGgEUKSF5N2QySYPutbZkw4SmJwCIIJIXIYSz/8uf2BEDXAWAosN/w7gUhAHwhge7GY2wGBKFtf5oMGKgcl1Cx/wKwKKQY2hWB3oHbqver7ab6J8t/2L9VbaR6sM8auk4gArlRNbBchQnSaBw5RyV7lRCAgSYCerS/otRZwqiMmSECc7x/9XNUDkCvAyB5AAwDtrlBQgG8KegCOsvolQgrgPKcQKTQSReBhOCquBP3a8LTToXF/vpY8ls2J6AdBFH/rNJfov4YDoL6UzVP5gDc8MBJBFbBnwHrWW08EEcqrvhw+5oNBZZ//bMLBCDqb7kAcAJtUQeyOuQDcGIPnzFeJQClSbJqngBULW3xIzKpkBYe3wGxkISn/u5zASwccLbh5NHhht43ELsFcGeFXwfmA1UAdBsZ9YxU/ej+zDkwJ+RtO5Mkmhh9yc+637cKwJ79lxyAlP/kKcC1IqBzAJgL0K4AQwC0m7hgyAsBrAVEaL0HJU6SQKeiyT6dWictOwsTsqW+9ttosAax/pA3AKJBEqEhQLX+T+J2PG9GEIxEPPC6ag/SNzhOtm/fZo3JABYpfLT/KBFU+leUvxHNR37mSAAC/lYBUDkA76EgIYWOAHASKnXHm4/hwaB8pIxIV8oFFpxlziNws/0diSgF91bwuQQmE7QQ+2fUvwO+pf7KkXRA9db6W6QB1+KCHu1qMgTQE70DoTOG24/Y5qMuIEMOFYBXQ4FM++WjP2MnAFUClGTg5gCEAMhy4M4F7JNou/eZ0qBWELD7qO6D0uNkZXmEwKqb4HXI4wzAa8ejLTYSjb5mfXz8jgCvlP86YrhC/ZH4lfpSFU4SgAfMo88TZFxAlRgyY1aI4Iy2zQF87KfbBLCVAAP199YCaBJAV9AlnAxX0NqwnIBSrHSSziAPa/VeJt/ACMp0AY6l1+CNvofqb6h6NikoJMMUHN2apayZNt3YxRwAPa6Tb2iTXj4cVP2MwkdkUQFz5njsGt1tX/rTHghArwHY7P++DBhdwDanYCWgzgPIfh2TtfUB+6QcJhcBedfGUXoGwAaOyXhdKy4rC1rxPAtlymqfjP0x5h6ArVSdARJdiQa6BWC8t3h8RhQ616AnY+cEigRQdREWUZ1NDBnFz4I5Y+OroMf2y5f9VE4ACH50AS4B7OD28gDtxyEVgW6yOIQwWGlg/Uz8bQLXcBoa/AM56Dq8FcMbCTyx/o3ISF3fsvaMWPRv7JLEPht08nC4TyTDb5UNI1VnwO3coaHQFPBKxa0QwAO/G1LAucwA+2oHkDkny2Vs27/8pygCANUXF9D+h2CdC1CA334rcQf7Z7yxsp8qiFpBOKhPQAiW6jIlN9UdzllAKQBjdtxT9eF8HJLQ5xNae6Lska1nSu+pfyMjb3GOlxwEYrHANwA6sO/abdBxyRiPAf4ZoGf6WOA9y0Es/+YnAwHs4JfsP4v/JSEoTgD/is1veYFZEsB+xAp7gDEX0yRU2asQaHX2wD8QjEEsCDKt0pZqM2LpSqaiiNpteCW7mQSgukc4UTWxsH0Z8EaKT/erRGIW/E/pAo6AOdt35+Pxvwf/t0gA8BKQFfzZMiDmAYakoJ4oUB2gE4UtHDLiYQSa9bnsDEhJj4HfdBYHF/V4Vn8gvh3sh9Rfk60ot7c9Uf+Xc80AkDnCNGng+RrnzCa/RS6Z8zXBJDv0ORnf9bHY96Pbov7LV/ykMQfQrQMgVQABvP67//60BKgXA7UTU9Z/mDgk+TeAndjrBtpCBcEF9Wz23on7j1p9TW74mzaH4jgC/Vtri20uDdakzvIDbTL0y1I9Gx+V8CJHgNeTBfIMEXhjz5LDU5HB8pU/ccwByBOAXQ6AxP9sQVBL5EJGF8uByPYDCehJE1UGAuB7JKD3MadA22iFx9DCiPPpeZAFOZWyH46Jk2cDPiZFRX1IvI7XrMdg2fsOvCRsYGMM25QadgC8KAeQIg5BblAajOL26v5Z4DPrb6m95wKWf/cTxhwAPgJskQAu/aUhAIB5+22J9aelQa0uOuFFQoRBCY2Soc4PNBDBMQVAGJ50amqVI8kYOH4F3FTZsyU9EvuLMs4q/NBP3SNT1Y2FPQyQcs0RYYT7JxYTZQgiAmoE/Ki/8E80DgO+RQYe8Nvx/v2P3wng9updALgAyEoEYrY/ejS4katyBegG2OfOEqpSX7s4K0QohgVUpSft+5VgR7BFsb/nEkxScByD/s31pB2IIOMSIETRE9YLF0wiOGMtwcUu4EoyyIAe79uyEsDwIhAsBSrrT6sAuyJ0i4KU6p9CAkpl9boBNuHT7iCw9vThJBJfe8erKrt2IZZjoWSIcTkLCTwVt6oC6nojwLKYvuoWIsUf1DsZRljn7m3PAPcMBY/GqIK8YU/IHTYs/+HHKQLYAd+tBCQkMIQA7L0AQAxo8bbjI1MXPiOIqMJNOgIEly4HmvsUIaUA7oQ0tD/LuBsAzTqC7XosUnAy/MwBZADtKTl1fjhB2aT19j9RCHAGOWTGyII/Gyos//HHAgEo5c8kAbv4X6m+lRDEmy73EtViSEA5pcFOIVTSMHIEAgTLVuvVceXVeFWwO3F+ByIW5zuxv1ZRRqL6d2TK64E1Y/9dIiDWfVB3veqPEcEThAARcDNgPKtNdC6Dw/lPP+Z+fxcWAOHbgM2FQKDsQ/wP+7TSo+qzsiAqk1apLmGoVUor4kTpcCCDALzZen1EQpbNp+QEjgNdiZWxN8t4pCKQUXeLOChZOFacEoFxTmzsYRIjEZwQAnjjRwCL7Hu0PxofLnVc1IM7gzxGE96vWgkAHwUWF8AWAuGDQOyhIAQ/KwPu+9t5KmVvJwXtMHSgE9BQfU0g7oMy2g4byb9ZMFtkwUCMhNDtJ2VDDVoNLBoSEBLpQBYB18kPpElkv9HM1XRzwFB85gzw2BaArX4uoRRAFYG7up+RQYYgKm5i+aof/RACiPK39wAAEbB3ArSq3v4Bl//qpcAa8Nt3QhAM7N0FE7DTSWc4goEUAAwm8Ky1CNYCG69syWr/BJBWLkArvWflL1H/iDwE2I6dH0hKJkeyYtCRFYCThSdZYLuEwo6hCGwGlE9FBsNx//OP2gkAwwBJBBoVgK4SsE8KyQWwuJ8RAoIdCQJvpMXqVnlQA3z4TpRdjsHA1IEo6hss7JFzQQDQYwaE0AHAUmMrSWgAmJKomuRH7D8DmOVWGMAjgHb7T8oBeORR2XcFOcyMyfps2776C/ocwPr7df8rkEMC23xS/0uQLgVm3IBOAHYni1ldneHVcSMJKdbJEYYOQU7BDR+M8VMZeQZUY1tHVNYxlQJnQgJNKNbk9tzGAFovx0CWDXurDkPF1+MVcgBZhzDbbgaoVWdQsftNaIHcNwLQIYCQgCh9SwaC2jfgQ/lPg92qAnQnokIB6gCUcrlVAqNsZqqco+xMtTM2/FTwVxyBofAsvGGgNe25UxqskgxV+ETIkCaCAgFEzkLmqdXuqZ1ARBam6gMAl6/5kSoEUPYfwa/fBNSeBQBi2MZW7wRox8skBgnYTUfgKLeA11O4KDk3gJ0pWzI00BOYxuhOeU9fhwXWqdg/Io7MfuJKKNhBfRrAJisAFJgH1wF4oPYAF4HxyP6oLwN6xhls/f7Lj7jf5dHf9hdeBNoRgJH5L4UB+2TSpBDmBADsCG5U9izYq+Sg25uKqqsJhnJ64JdrcC13Mfan14tAdDL76MhM0qmOFdh2fRxGJBZQoycKI7BkQZ5tFx0v2h+BPw30BrhXH7bweCOA/eWf+kUgFvjxKcChGqAAbuYADCLQ4N5O14j9I/DjftcGe1UDpn7Ogh2LhCrHfyzw098Hwews/aVkkMzkD8qd7JciggNJQItUjoC0CuAjxMLOMzz3r/3h4ADgLcDM+ktOwKwC4HJg9ZmV/RoXWaGBUv1TiYABO8ofWLHwRDLPBd8JCn8quLMWPeMkiPozK5/dNpBCkAPIgnwWiLP9QqAqBc8of6rN1/3wh4VA8gRg9AxARwI7iFgJUCcAKwlBFg50lQIdDoCbMC1rpYKQrBygW+kUMcjkR+CsxvHus/sReCPQRvsR0A74rPCBnXtK6ZVTsdzgYwK+ovaVthE5zCi/8MnydZ+vQgC1AIiFARveINHnJQMbNlHlAbDbiTj7NBmUiYCoNqsiDBNUT+YjoHaSh3Lz3BDBcivedkaSjvqa8X2ypBe+QEQBVl9vBHrmCCi4H7EKcJban00GFcJYvv6H9UlA+i4AXAuAZT/1WWf/LdXv8G6VAQkxlMHPMsJFJ3CJylugstTaU2FPdT3wZpQ9UZ4LiYvU/TswJ1xDRsWZ88v0a0oIFjtDNt7YEQCPEEc0dnX/AwGQ2P9oDkDCAvld9XdP9dEV4I3tbpaenMZ3V2lIn0yCSlv0wyTh1Nkz9p6ppxVGoFU2VV/UOqn+6NKiMbtzdQgmcgRv1P/hJlXdw/C7/dcfajsAifeFDESU27MB+wa5jzoUaOB3LD4SA4v9NVF4LgAnd3ehgeozAHugHianEx6wCR+FG2YeA294whVQYtjvWQRUMw9BlDIkG7b6j4VmVrusOp9s/y0ncJX6R+POAD4kiI0A4L8BQ+Uf3gfg2H/2MBBTfdP+C7vAzdaPAFfIwLSERHVoIoqUBjNKm3EDGVIwx8kAOFLuaL86hkkkxcU/jDgrSh8CUhG9B6iMzc+0iUB7xO6H4EWszLqBb/ghJARgTwKytwI7OYAhBHBcQDYckOtlTmFYABIA3XILbCEJ3QaE1ampsRItHTbsF+mqqpUryCzZzYA/QzJJN+ICPLFqLwPCI/F/aXy5N4YjiRT6akB7BGmd2/INP/ghBGjJPwL+1QnIfGf2X8CuQ4GGEZXoO9UFEOdwhAxYDiCtXE79ngKh2t7LFWTAHwAbSTEKEby2kaqznEHUJ6XmCUJJjaPUdFbFK4CvtI2IprJ/+caVAHQSkD0ObL0MxCgJbnNNqb7+XlX+KATYLlwdky4NZVaRxY/ZcMGLZwNHkCaXCPwZ1bbOBZXNyS0wkJruSKmll1w9CsrHdACzZOBdYwWwYj7CcAhcijf+8o0/KHYAkgzs/u4Trqm+/g7gKYUDRNG7F4jKhTlAbz+SbgNjdz+g0S5yA0wFO5AQAnHVzwOoZ/vPAn8yMeclKSMlPwOspm1nhO2oeRZEM+0qgH8q9d/O8ZtWAig4AMGQuRDIWQ48JAUBkO3eRcDWuQSi+pETQOBSdpxQ/kjJI7IYljkrVXaBlajpZxbqeGrOQEDzGqA8OoywfvdqHP5+IICznEKFSDJOYhjvm35g0QEkFwIh2Bm4w3AgcAJ6MrV5R+y9BpcmCFQl+oOz8MByE0qNu/EK4UDkJBihWHF7Bvz4m5jAJct+I8Wn+6+I1a8YE0k4+OwBtaLwlbYZwIfjrQQwrP4jK/82+6+2y8q/IQmolR2SiNvvqFUc3x/A9jOwESfAgB6BnxGJFR6E9tWbhJ499ey9FUbIhDT6ejadAjwKMbSVtkgxY7kvAOuZjwFn1fvq0CACeAhucGPycejzzT9gdABYERheCLqDUQhh+0qeC2iYNcBvWf4wMWgQhE7+CdHoC04TAlFy0zkY6+41udAJkyANar8JKVIHEBFEspYfOZLIxofkmSEOr82B+H9WvWcIoALaStuILNj+bdtKAF4JUKu+uQpQx/5AFKj6NBwQeiLOYCCxKEegCELb++GHcCoCA2taYHXU0IrtXTJhjsd5kKcDpziDBEEgQZkkg+MBWVigiYjA/T3gZofjGI4kC+azwTszXgTaqwlgHX/5ls97tRRYVL2tADRCgUH1yYKgDofE4nc4VqDG/EGbE0ZiziMIF/yGYlCHYJEKKzviJLaOEWTbQ5CQpN9AAhcoP5JWGaBA8lmyKYHZI+FgldwMeLNhgncNlX0RWczufyAAWQqcjP2tCgACV+Z+t0RYAUmIpAOxEdtHTmDbTybBsHaAnIMmiuHmatcBk9m8iexcEgrqVgP2c6cxvFL+LMii2HkYJ5Er8H6TaeL4ANj/CKSPofiIowcH8P23COBGnwHQhOBVALxHg1l4kCED0mbIEVjqTIhk+4GT26dJIXAF0yGBQR4U6MR5ZNsNTkIRS0mVsa8ir+o4LnF4ZKvPYXKV3xWK/1o4gG/9/ioJKC8E9dyAAXaM75sDANDp+N8LA7p3CyjF1Y5B3xxKEsZ6AVo5SIDYZHMvGRUlqqLseLCSbzunpBVGMsy6hTA0icAWXf9sIjC45irZyPzKuJUjIH4KxR8cwLd+v50A1PMAmOzTnwXTYvkld7Bth5uM+9uBo3yAodKR8uP4HUEQ5dFtGYEM25QCDwQQqVAEzAgcQdx/JvipC4jICX50Cpxk/wzoorCkAsrM8WbHM0WCEGXU9qr9y0oAWwiglH8LCYz1/w3wqvznqr5BDhqsUwuEqg5BkUwHdgOI2yGsx02tHIHcaGd/pMQIbArMRF7hCGAwFMqAxWwTEdys+sO9zJzfjBuoKPVVba8lgGISsFsApElivyE45wdXADdNhwUdlkm8nnYCCeWXY+l439tecgvG5OxuZqSMjnPoJnwWYJETYUoenWOkaBP9M2C2yDML8my72fg/Am2FLKKxZvZvfb7t+77KAWxOwEj8NXUHp7DNb3QBCvwSAnSCq0MAQhiitugOcCzcbsX71qrAri9OXEY21nMGHUu9GnG4oQVncMg2Z8FPSDEFNMcVHemf6ssIidw3a6wsyM9oVwXhUQLwznkQMVIKbQRAV/45RKDJoAHcIQMhiwjUQwjQscer3hYh0BWBxhhCNCzej/ZZx9FuIsolHLbMFUWfAXIUviAY2ecKOUVjMTIoXH8EmAwhRSA/Cuoj/c255pHot33uQw6A5QFku5cLQGAjMSDmLCcw4BImixUaCDCZkntuwGtPCcABCx6nHBJkVDg7qSuvwEoAcQDIBPi9MTIAKyt59rcKyGWWHCr9IvJ4kv2NAII8gIC1Wwqs1wUAoi0yEABrx82UP+sGziCFDsgkHLDyBN1N80gjqCLg+CkQJOPqdn4BUOhEniENVJtE/2x8TduRa/IAmT1WBMSzxomO8yj7P/65r1YCotIPn0m8j28BFpVvwGdkoCRf2/gOd1k3MNgImIEEyBZZYEKJugVrHYEoi3EsTSzu5HEIZCCFyuQPnMIl4If7kgVMtt0hUkOCMj5XgVex7VM2XU3IlEAQxyPDdP0//n3GlYAh+FWs370OXBbbqWSfblNxAlbbsuUPyMLLBeA9YLafTZruB8+AO2vps+32650Flqem4b4T1d881oyreWICqJLL1e2XjQDkjUDkmX+d5WffEVeWE0CBNJU/qfq6f0eQBdVv/Qw1tdyCBWzGsDJGqBIZgiCAzjqK0kQ6A1hnjOGBNUEwIUmd5AAqxyndB0PFw7nkOAY9R5ePf+9XSUBGBAJudAVt234Ttn37xi4ESGyTE0rnAIBtBqwfAD/+Zl68r8nGdA3RykEsy2TtfJYkKsfWk+wM4GavJwnA2fj/CDCPgqzSPwoLov1HSOUVAeBKwGgtgJH80+AfbL8OC9A66Od0gFy0UiuCa+Sjt0cKboYQRGmHsR0w4vmGE0GRltk+AapuIlTbG9dcDh8mxpkCauL6wt/eUcojfY8AUiv0Wd+tc3ogAA/8xsKfDuykTVP2/YO1GlCLNnUCiii0Cpu7LUfgjUf2WTG/JgXLORwFtbkE2VLQRNKPTgiHjNKASBw7PZZ2J0Vnc+Q4ugsk6gAAG0BJREFUVVKKQH/muZxKCp/4Xv3DQGLn0fI3sEerAPVTghAaaFyllgcDi1Asq43t6yzwI2IIKgHiOFKWjZyjZ3XZBMuAOJqYbTJVwwuDfIb/l8FR2cy5VX6Ts0HmZdunz90i7eClJZnjZdoMv1EjAMcFbLiYAT+x8TpX0DCeAHPXxAA5XTug7YiW7on9NPYPwgLtEEKiSNjcTg2y4YSehCeBv+xUZid98ne5khCmwHaQDGeOGfVZVgKwqgAiiBH4U2XAfTCco1qxNcAZxiOAm+J/kSvwEoYU4Anl325ath0hr5BYNPDYq9Sr4LzY+reJfBZZVa/vhPYRGGf2Z/p4bZZPfM++CmCFAF4YIETR/upnApw3AqUJAQ4ShQPD/ovA3wjdANDwwxvKZbVjN45uSwI427eqnIywpsbIKOT7iAAy4Ix+p5kxMn2kzSsCCKoA+AiwJoOOAJTtF8vPSAK3NSFLhAJdPwLuTKiwHc8jhsx+1YaGBSRxJdeadQgWETBVTJNG0mVEE3TbXww9yg6lmPzL/gapawNSitpXgIdcF40783tlzmUd94EAEiVAuc8m+HWOoCH61fxAy19R/mplAElHicqrryeD3wM1fVkpm1gBkOgxHEV0gZA4VnpiFlQ5MzHNNoXjpM+9APBozKuI59BvpgAwJgE/B0KA6CWgrP7vZP4bWcBJZJYEI1FYQuzlAtw8gTFg2jXs12I+diz7gQA9tu/2GaRkOQvrfYapiZgNR6znyMn1zQCkpG7GOZfG0PenQAAZIM6cS2bcq9osnxAC0C6AgH14+Ie9EIQQwoY5FRo0HAbbKY5In3Yf2QtHEGVWiGEAVhHow1cHPHgeJnAZqAIll3GrSUdKBkdyBmQF41WTsxv3LMK6mAAe5bdwSKt6/AcCMEIAmevrbz88A7Dv1CofVQQ66w9ftAJrMdSuAHD46ucIiEGDeRDcKCwgB43KgZYa47l4biIav0QyybjfOufhWGcRiQHK7nivKQFUATcQ+Ylgnhl7+cT3sEOARgDO038dATjZ/w74AKTM9q05AScjBY8YEHRVy4/Kr4mEKZXbRnaSa/IAvR3HISk3CZkkr3AMOPeM3c2SiTtWAfyzgDyz3+xYZ/6e6XPoCMBZ9tuAboB8cALKIbT5x54H2CeVBrkGOHUFHjFQNlBJ6wnVZ+AWgogA3Fg6cVymuJ1zME/kYQdT0CwgXTUpEFdmUodtCgQQjrVf2NXtMuNn2lTu18x4rxyACgO8sp+n+ts+A+Rs+a+0Z1jFfXS/ASLLGQxjJEAYlgpn1FwdN0UazloDD6wR4aQVH4GTPP+ZCUkn/MmhxtWgsu7H7O9x5fkun/hsFQKw5B+AGsGfjfc9UrDIYjukmmjatlv4taoAFduvyccFWYJIvOSdFvIo7s8Avps0ScBaE606VoVUdFvL9byO4Inc2PvhnEcC2CfL+mf7p+P//ar1dgTsEA7AmJ1gFrZ36k36tXEjV8CshFwT3tEsqBPt2rDQNqX68GNl2kfEUQGmpcQR+VSOkQJIQf2vUMorxkxdd1R+hbl6aLzmAMhCnuEZAKPmrxW+EYAFcGtpsLM9dATgUrSiMvLQbSruYArQCaKIAJxyCjgxnGN6hGLuyy55npicFuEcJZSjAD7aPwvOK46TGfPBAej4nz3959T8B8VXYMR5aK4HIACOLD8DLZvzlp2nZiAB1G1+J9pVbD8jrdR6Awts5PymQL+Pf6j6EBCCNVHN/7iV/lgq6XkWCcn1k2NmwX2UxLLHyQBeLkPGXD7x3cccQGbdP1P9UPmt5CAAqiMLOVvD8re2XkjggHXASALUWfAzl4BzKLT0wblk+kdt0vuNc6lMbBPkhtU9tMpRgfUogGaApfmi8lsdPd9S/44ASLyPQEelZwlATQqIPU/56ctB1MtEGI61slP1NybvU4LfELBXmxMZfzZGxnGkQY8HgB9rxkVM9XkK0imqfYUYqgRYAnHBEelxXzkAJwcg4EOFz9p+5hSasBPlZuGCMgIPIkwmiN50RjWg+22zDsFxHRnwR21cEKtzjADvTUx0OzMgjsY2VbEI/iq4ps+L3JiKslfPszJ2pS2exwMBZHMA+8Re709HAGxxELTtnACgWZNIa5ew/APY9c0xngno+qlBXHxfDP7tBlaOwSZjsn+GFLZJciAMOUQYRQI4dKxHBvWVJDAz9vKJz4rXAYjidiHA/sPRtQDWE4LGOwIt1e+2KxvgEsD7DPyotNPqXwQNO84ApIkxI3IJwXryMcPjnUAAVeCd1f6MaxsJgNX9WXjgKbzlCIwyX7vn3jJhpZCUAGBjRBCKTzjukoraOlfbp04iooTk04mFic4I6QiwvQkvp+XlL44cewYkZwF0uDZ1D2Ztu76VR8ZZPv5ZDxpOwwDr+X9P4ZV9b66B2HodRmgXnHEGrc8Tgz98B4GF4wJp0Bud7B+BqDu9fcxMn6hNaT+5llL/IsnNkMNMn9eZUDYC0M/5I2jXzxqowzaw9l1bZzsCl1p9I1zQJCHkhffeVH+HJBgA9HwysZYE4TA/Z/sZziECi+clPAXOKg62y5xLFHJMjZFU2ciVnA30GRJ4jD7Lxz/zVQ5AwFVa/rt3osAv5gIQ3A+25OFuenbefV6AlBLZeBb4U/hMNSLQC8gonPyzx7Xq7gapyObwfKJx4SfIOJmzjveYQM78VlW7PktU2eseCSCI9wegW5Y/SQwakDpksPYLM1juofVTQHFxE71NKGkJQmyGDTyt9qsFGeCYo8N5ZcfJtnMnsvo9smNm2mWBUHU50bFnjvvYY67H6wiAvvLLyQPgk3xWqKCFRZSdAbdti5KBilws8YrcAd70cgxfJYtAYQPI97uPEog62DbxCmNGE7UKJjx2duwz2kVjXLl/hiAihzEz5isCCFYByhzRCj0A37H92xjE1neuwtmP/V1nQBYKWfMbQ40MCKvtD5EMO6ErgBqMGQGBnWa6z37sdPujoUYUipy4f9a+R0A/c9zl277bXgXYRQABjsDUIK0Anym7DiW0m2CCaS0ZHsggafuzYO6GSwCQNkn0CwnojDESYUwFjDjcTL9osVHZTTwigCMgvu77txCAEkCy7s9IAcHI3IIGNoJwIAV0ppmwYD+4xgn9HoCpAuIQl0aDsF9nH0J6KDWo2v5DKk86zxy/QjCZtq9Tm+hcrtq/EUCn9M4LQIYwYL+x5mpABUgK8H0jgmH47IC/U38Sl1fBnwV+GryzuYILwd+GTl5ENPmyzNONkzx2xg7PklP2ujLtHqtNdJxov3YljQBEibW1t7Y34CVW/Wngt3vv9MXxB4sPd5w5CBY+6PESTvihCUzU7JzF68uCwzrnSnKudCx1MZmJUxo/itWTP+bMeWX7PEW7s46ZGSdq00IA+uYfou4DkEG9vX2W7Weqz8gBccjcAQNPRfnNuUjcCQPB6a7BZIMqBI32SfBVjhZNtm6sxPFL48HglX5XtM2OeWa7zFhWm+VbP6NPAgrYXOX3VH8fwFT9qEqg+rvq76izRxQZfEVlQXcOJ4nDBdgZY6TZKoZ6ZpLFo4iq8JZHj1Htf1X7K8bNjDnTZiCAyPLPxvs4LnUEiaW/HaifCPyReEXEkSGfM22/nO82OaKTTyP4QMOLQo/M5NdnfXWf6viZ9pk263Vm2m0hwOoAUK3NxUCBsrvEkFH9YI1AN3+zFYHki0M6UBog8bCDYcth0SUHOgW3pwxyAPiJ9wvMjp6Z7Gzsx+pXPU62/RntGgFYyt/IQVnS9au3DwHL6vc6RIjWASDIBntvOMvsSkAPwBZuuu0HQBuNUwUFPd+LwZ+diFc4kPSxyQ/52H2rx6u0z7bV7ZZvkRyAEddr694BP3IFmXyAE/NHlt8iAv2fjXju1wJ/Cvhq4AzOzDZO58y4mXxClUxObX/4IvqzyU547xqOjnGkf7VvpX2p7bd8eCIJKIpLXAFTfq322jl0feCOee00qC2HYIHfUt408GFgb26n5v0JawVmiOVUgHuDpX6E+GwqEzseLRcnXz3OzDVV+3jtl5UAEKAIOhO40WO+mZifOA5KBEG7DuCJhUADIcDkZPPUJIQDil21/dP4KXYsNs9g46HNgYGrkz1/UucRwHrMo+c527/abwwBdgLoSIAou1bjSNU98jD/81Ct/t7/IyAuRPocAH9F9be2pEM0x+l+tTEag03u11H55Zy2yTZzURUUH2xbBVDmcEfGfOy+yzfrEMBaCrzfTAbsiBwyYcGg/oSEAOu9sKi2oe2fUP3WJQnacN4XbH84lp6VB9xJZoKn25RPPD3yaQ2PAC5zEkfHP9I/03cjAAbgAegHFv9YBMEsPyqsPgcNbNaWgb+bh4QsNLHgjWV9Q4IxZoZFIubxghmWcRWZSVrgj/xwb8Df/VYZMEY/7hVjPBAAgIIqvKHGkfJ3Y0UEsl99+L4AaQcoxLmm593Z4Gfz2pvrw76kg5giBXIiV+EwHDdsEE336/efAaiZszzzuEfHWr7508k7ARXIEMjMGZhKnnkpKGnDxhu2ESWfAX8K0Jn/ZwBmgjn3E7Y/i5uIWDITM3uszFgdYV01cPVEgvZHwXP0dK46fmXc5Zs+nZcBN8BFqn10v7H8V5NMZ7kTVYHBoicBTMkgqaqhC3AaRHiJ9m8TccJZeBM4dUw2wIHrjABVmdjkJ2nDV8eJzuus/VeelzX2RgCDwnuLghxV74CbedQ3Uy5MvBQkUn53P7odreIJUFnzvdueGKdq+b3xLwF2NqE/zRxnweiDNc6VpLD+Uo0AGnjBWg92f6dVur2yNFhA59h4nEfb5+T6fw2MCPxU9ZV8mG3UXKNzn1yjnqIRZtz9RXIpinaIplkiCgd+08D9Bc4ihuUbMQRQkzXrDBAv4UNBcllR+IDK/Ejgb5MZZnVEIJ7V9J4M9EAdEUI7ZqZhVrkzZJawFslTegPvR/gFMiSxEYBW2PX7oPIROWTe+JsIHzoygS/6fDTwjiq/Bv8s8BmJAOfR2x6BxnMW1dDBIyxrTkbnt/VzGqX6PwIgjhxCX0MGXEeO9xh912t4IIAo5nfAj2o0kAaqeDLb341hHNcDf/QEoAvsI8lCA4nW5D/iAE5558ABxR/O/SDCD3a/DCuZ83q/E8HyDZ/mVAF2pCEoKcizdj5DJEIaVfAnlgJXwT/lApxS3wzoM2DLTNSK8mfHE+UvtS/A9apxM6fwlMeW81vJ5WrnsREAA/W2LQHsVMyfGKez/gr8Q1ignEXm8V8PzFXXYIHJUmY2mWbIwPq/EvWEzkzeTJuQNMgg2XEzIJwJb6rjHgp7zjrYI43D3MryX8EBWHZ+VvUtEmGAbseAGUSPWwT/2apvglntOAv0bRwDWRnAXdYmM/BkEvKpgZm8tEeC7nWH6QhgRvVdkColt9rKcT1ioC4gsP0V8LttjUnMwFkBvjXJhu2EFGcBEk3saL8cN5uHmD3PaMpnzzMax9v/GMc4cn5n9N0IANXXBWnmPQCi0Enwb8AO2mbAXwFw1fJXiKQBxLg7FYJAR8aGiyboZfvVwNFxMhN1ZoyZPplzie5hZYzXve3y9RICEBAOZJAEdQnQxpiuG3DWBWA//RnJhu5TdyskFTIDKwBPtU2qfwQGb3/Ut/utEo0TTUxczPSd6ZMF5pVjZ88hanfkHDcCiAC7HSAqFQJthi4icAlU8YMyImPtAcAOmLBtCHzCHikwR6GEvtMnVxQY6ZFD2vMt8TDTjFN5yj5Xgisa29t/BNSV4y5f/6nj04ADABNZfI8kqJor5XcVPwF+D7RybimSgF/PHDNQ5YhAPCC2vkl3EYF6VvlpP7VxZpJW+lTasntbAYLVduYcKse9evzoXJav+9RX6wBkMnUKfgH4U+VFDcTkcmANCAR/SBIF8M+CPOUUCDnijZwB9UyfDlSJmZpo0s3HTPtMm7McRMkNRcgK9s9e18HDDt03AugArx7qMfftQ0XKP+MmvD4U4HguhDi8PpV9mfUGTJFToJdrMGaGNWHO2u46iYCQjgAwC4RsuyxRZoA0c8xo3CvGjI7p3dvla4kD2Dqom06JIOsOEs8A4A9jOZCzwV9yBKpxBtSZNt01JY5h3cwzicA7p84VZGZech1AFhjZdjPneYTIop+iet7ReGed60YAFuBc9T8R/IPiF2N+Rh6RWtM+xEmIw/EmlEckacA6KnsGuL0JaO5LJv2ykztqF+2fBXV23LNApcc5cnyPCM4Yd/kv6ACyoM62q7wSTD+BaDiQlAuYLBNSIBeAGRGBSQbkTlZAf0bb4dySbqQ62TOTNtPGDVkIarJjnkkCR45Z/V1nHMPa5xUBwEQ/TfnhF3DHJC8TYa7gKPhLqg8Hi4Bd3W9ZbDZhzgB3ZYx2bs7szUzsqM3R/Y/pBqJzPZM0HgP4eD0bAaTi/WxeoBDvD6SQIAzG/K1bslJgEUF3o48+XUhi32EiFev8WYKYAjzOPBCDSFkicHj7o75Zlc+MQy4vurS2vzp+9ryvtveZ81i+5lPGMiBT3zRJ7J3Tig9UHvVxHYC6SxmQm22csVwC2q8lcgTbGGRWHQF4tq83KbYxjNkegWAW6NG4mUk84wYyx50Zt3K+FgFUzu2o+9gIIALeVeBHuxmdQxb8VeAP48IAEZCn9zvHsCZQFuDZdvQ4CeWPJudTE0F0fjNOoDLmEQKoHmfmWjRhLF8dOQA1KVygFpKDrwP4B7IwgDkNdOYIDJBlgXt2O7wPenJEE3IG7DN9qhM9Ou8rx5slgMo5zzoT5hY2AjBBfTL48cfZhs6+OhzOvANtArBpR5AA5mEiIHc5GjPrCLLEcIXyW5O3uj07sTNgybTJgjU7Vna8KtEebe/1X/6z5QAmwT+AnL1g9CD4hTzcsMAiDba9mPCLQEv3G2RlTfoMoDNtvEnZ+quBZlR6Buwzx7lCvTMAz7SZIYDsuFlyZCrvnddGAIMDCMDfgbxCFIkKgUcg2q6m1X3/VWj7yTUD7Ec1iSHhLrJEcAT0dLIVKxHRRKwSQQSAq/dH15PdX2030z76LRj4oz7LV2kHQJRqIAgB1GOD31DRChF0bR3lM8GcKO91fYvuwmJr73y8yeQSRlL5zwL1rOJHk/jo/oxyR8e4GtDZ41fPoyeAQhKvVBk4Q/kD8FdIYLvhCTLxQozIAWzDBwCLQB3tj87BnQwTyl8hgkrbzKSNAHD1/gxJZNtkrhfVPLo2rfyV9hsBlMH8RMpfBjn8MpbyZ8asEEEbT/1GFZWOgB/tD13EBcpfBfwVbiCa+FfvrwA7OpfKWLNksZ7D8p8+lFwI9AS2H1U0A1Rp47YlwLTaTwF/7xSB9Oj+I+pfeX15SCYGyWYm5etGAhlQPmabqxwFjrsRgAaO+f0k5ccTcI+dBGuaHJLjReByCSNQ16PAj/qHgIUBKqrN2h7tH6ncFQQRgSoCeLQ/Gj+65gxxasufPSZrt/zHrAN4jcCfBjyG4RPPCZQdgAOuCLgeqUSEFIIeZt0VQD46pjeBryCBCMRX788CNjqPCplYx9wIIHQAB8GfVvwT3gNAgTQBflflme0l7qJCIDMgzwCvtQmcSZpECi82rTiECBTVsWbHi/pl9kdtzgT20bGW/xA5gNcc/K4bOAh8D8DdD3/kPygplhVLoL9Q+TPnESlUFdTV9rPOIgLw0f1HQRv9rjpE8I63EYDpAF5D8LuAP2j5o7GpSkMn/UNXvlfaZtxCa3Oh8lcAWWk7C9yzjpEFmAes2X3ZY2dIKNNm+feWA3hC8FeASNuS9QxZNbeOTfur38i6edkxI2BnVFc7kyPWPnO8yvhntI0m9WOSwBGQRy7g6P4skWwEMDiASfDjzTFdxX5m3f4CYCNyyCzwicZIkQUBv6fiFYWvtDVB9cjKnyWLqrqfBehZsM4CcbZfFrjR+BFRynGWf6cdwCT4GahSJBCAPwJrtx++6GOnQK3icVO5T3p+oAL0qG13fYScvImVAW/p+CoIzYxfPb8qkUSAuIIgZseMzjWzP9NmPb+NABpYXgPwlwAPE02vZjwT8BHJsMn7ZG6AzLoMAM9qU7H5Z6j7GWNkVLd6nCwAFVe2r5HCn7V/+crVAVSeAUALbyjhrPJ7LsIC9NaHKN4lDsBQVtMpOI7CIyg2ebxjzKr/DOgzfSok8NhtI2CeCfQjID3SN7pG3L985cvEOgAE/ZFXfSceCio7AMO1uIShriflFhySqQL2DMKgx0yofwbAnnupALYCpsx5PUaY8H4ILSoAjxzG8hUvi88C7Ee3VB5PjrZJuA02BgVp4EBSwM7E/cn1BBVV90A2tQ86RQCOCCuz/ygRZAF/lETOBLSnypXz9Igssy8igIp7WP7tTgAhcCfVuyOBE8DfLq4A/shVuERhAGsKpBeFBNH/gmRNqogoov2PRQJHj/MYJDBDDkeAPHs8fcxGAJaiVwHMwLZtS4Df7Kst+8HKgQX44fj7hizYz24XKbH8rmjzItAe3R+dU9WmZ53AB5UEZoE8228ggH+TdQAFADMgpQhGAZ0SAlHkSOGj/VZ4MRNCZPvMtuv6JQgqA9gqKWTBmAV3tl32uGcpvgWy6vZZpT8L5CgQlAA85a2qtwZ6RflDB5AEfwT4aL+21Fb7LIhn+kfAzfzHIhVgR22j8zmq/BVQZc61SgKV41fH9n6bWXI4q9/y5SoJiAMfBb9Xm7ccwXB8cQVE7QayIW8groI0s5KwOmYEHm9Cm/suUP+MEp/V5oiaV8B6VdsZEphR9Jk+FXLYCMAE0oTtb2OpCZoBq+kAjLFMsgDP4x33TOsfugohMnJuEUEM56lmRaSIV+/PnP8RwGfHrxzjyrZnksPlBPBlRhlwxrpnwW8CnWXJC0RymBCS5b4zwV5Wf+hwBNhH+lqW9rHdwVF1P9r/dQZ6ljiWlQC0SjIbPLRRilYFv0cC7Yc9WOrLAFWf94y9n+ljnZurdie8YnzquMS9PAUJHAVshqCs63oMsFeuzzvPaB8eZ/lS7QCU4jJVNckgUGurH1XuiVJfilSYFTdUtUIgR0nA67/tU7OjouBll2GEKVnQZ4EWXUPFps8es3KM15EEskoPt3T7KP02AojUO0UCk+CnoCWAzII7Au2w3yG8o6COzoUBioKCnKPrFBjJqRlQcQLVY2WJIjNuBaCvIwlUVX0G0NVjdATwMXEAAYBdEnhC8Ecgc/efGPNH5xFNdhOQRdt/ptpHCh3tj675CFE8JTFUjv2UriFz7GUlgOp/DNKRwUHwdxPfUeMjDoCCq5BfOOoEZvpr2x+BLavolXEyAM6obnTMzHEqoMuc09HxKv2rbTPAVYZO/ydUbXfkKP4/BnecprBuissAAAAASUVORK5CYII=";
  88830. return TextureTools;
  88831. }());
  88832. BABYLON.TextureTools = TextureTools;
  88833. })(BABYLON || (BABYLON = {}));
  88834. //# sourceMappingURL=babylon.textureTools.js.map
  88835. "use strict";
  88836. var BABYLON;
  88837. (function (BABYLON) {
  88838. var FramingBehavior = /** @class */ (function () {
  88839. function FramingBehavior() {
  88840. this._mode = FramingBehavior.FitFrustumSidesMode;
  88841. this._radiusScale = 1.0;
  88842. this._positionScale = 0.5;
  88843. this._defaultElevation = 0.3;
  88844. this._elevationReturnTime = 1500;
  88845. this._elevationReturnWaitTime = 1000;
  88846. this._zoomStopsAnimation = false;
  88847. this._framingTime = 1500;
  88848. this._isPointerDown = false;
  88849. this._lastInteractionTime = -Infinity;
  88850. // Framing control
  88851. this._animatables = new Array();
  88852. this._betaIsAnimating = false;
  88853. }
  88854. Object.defineProperty(FramingBehavior.prototype, "name", {
  88855. get: function () {
  88856. return "Framing";
  88857. },
  88858. enumerable: true,
  88859. configurable: true
  88860. });
  88861. Object.defineProperty(FramingBehavior.prototype, "mode", {
  88862. /**
  88863. * Gets current mode used by the behavior.
  88864. */
  88865. get: function () {
  88866. return this._mode;
  88867. },
  88868. /**
  88869. * Sets the current mode used by the behavior
  88870. */
  88871. set: function (mode) {
  88872. this._mode = mode;
  88873. },
  88874. enumerable: true,
  88875. configurable: true
  88876. });
  88877. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  88878. /**
  88879. * Gets the scale applied to the radius
  88880. */
  88881. get: function () {
  88882. return this._radiusScale;
  88883. },
  88884. /**
  88885. * Sets the scale applied to the radius (1 by default)
  88886. */
  88887. set: function (radius) {
  88888. this._radiusScale = radius;
  88889. },
  88890. enumerable: true,
  88891. configurable: true
  88892. });
  88893. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  88894. /**
  88895. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  88896. */
  88897. get: function () {
  88898. return this._positionScale;
  88899. },
  88900. /**
  88901. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  88902. */
  88903. set: function (scale) {
  88904. this._positionScale = scale;
  88905. },
  88906. enumerable: true,
  88907. configurable: true
  88908. });
  88909. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  88910. /**
  88911. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  88912. * behaviour is triggered, in radians.
  88913. */
  88914. get: function () {
  88915. return this._defaultElevation;
  88916. },
  88917. /**
  88918. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  88919. * behaviour is triggered, in radians.
  88920. */
  88921. set: function (elevation) {
  88922. this._defaultElevation = elevation;
  88923. },
  88924. enumerable: true,
  88925. configurable: true
  88926. });
  88927. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  88928. /**
  88929. * Gets the time (in milliseconds) taken to return to the default beta position.
  88930. * Negative value indicates camera should not return to default.
  88931. */
  88932. get: function () {
  88933. return this._elevationReturnTime;
  88934. },
  88935. /**
  88936. * Sets the time (in milliseconds) taken to return to the default beta position.
  88937. * Negative value indicates camera should not return to default.
  88938. */
  88939. set: function (speed) {
  88940. this._elevationReturnTime = speed;
  88941. },
  88942. enumerable: true,
  88943. configurable: true
  88944. });
  88945. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  88946. /**
  88947. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  88948. */
  88949. get: function () {
  88950. return this._elevationReturnWaitTime;
  88951. },
  88952. /**
  88953. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  88954. */
  88955. set: function (time) {
  88956. this._elevationReturnWaitTime = time;
  88957. },
  88958. enumerable: true,
  88959. configurable: true
  88960. });
  88961. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  88962. /**
  88963. * Gets the flag that indicates if user zooming should stop animation.
  88964. */
  88965. get: function () {
  88966. return this._zoomStopsAnimation;
  88967. },
  88968. /**
  88969. * Sets the flag that indicates if user zooming should stop animation.
  88970. */
  88971. set: function (flag) {
  88972. this._zoomStopsAnimation = flag;
  88973. },
  88974. enumerable: true,
  88975. configurable: true
  88976. });
  88977. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  88978. /**
  88979. * Gets the transition time when framing the mesh, in milliseconds
  88980. */
  88981. get: function () {
  88982. return this._framingTime;
  88983. },
  88984. /**
  88985. * Sets the transition time when framing the mesh, in milliseconds
  88986. */
  88987. set: function (time) {
  88988. this._framingTime = time;
  88989. },
  88990. enumerable: true,
  88991. configurable: true
  88992. });
  88993. FramingBehavior.prototype.init = function () {
  88994. // Do notihng
  88995. };
  88996. FramingBehavior.prototype.attach = function (camera) {
  88997. var _this = this;
  88998. this._attachedCamera = camera;
  88999. var scene = this._attachedCamera.getScene();
  89000. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  89001. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  89002. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  89003. _this._isPointerDown = true;
  89004. return;
  89005. }
  89006. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  89007. _this._isPointerDown = false;
  89008. }
  89009. });
  89010. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  89011. if (mesh) {
  89012. _this.zoomOnMesh(mesh);
  89013. }
  89014. });
  89015. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  89016. // Stop the animation if there is user interaction and the animation should stop for this interaction
  89017. _this._applyUserInteraction();
  89018. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  89019. // back to the default position after a given timeout
  89020. _this._maintainCameraAboveGround();
  89021. });
  89022. };
  89023. FramingBehavior.prototype.detach = function () {
  89024. if (!this._attachedCamera) {
  89025. return;
  89026. }
  89027. var scene = this._attachedCamera.getScene();
  89028. if (this._onPrePointerObservableObserver) {
  89029. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  89030. }
  89031. if (this._onAfterCheckInputsObserver) {
  89032. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  89033. }
  89034. if (this._onMeshTargetChangedObserver) {
  89035. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  89036. }
  89037. this._attachedCamera = null;
  89038. };
  89039. /**
  89040. * Targets the given mesh and updates zoom level accordingly.
  89041. * @param mesh The mesh to target.
  89042. * @param radius Optional. If a cached radius position already exists, overrides default.
  89043. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89044. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89045. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89046. */
  89047. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  89048. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89049. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89050. mesh.computeWorldMatrix(true);
  89051. var boundingBox = mesh.getBoundingInfo().boundingBox;
  89052. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  89053. };
  89054. /**
  89055. * Targets the given mesh with its children and updates zoom level accordingly.
  89056. * @param mesh The mesh to target.
  89057. * @param radius Optional. If a cached radius position already exists, overrides default.
  89058. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89059. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89060. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89061. */
  89062. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  89063. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89064. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89065. mesh.computeWorldMatrix(true);
  89066. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  89067. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  89068. };
  89069. /**
  89070. * Targets the given meshes with their children and updates zoom level accordingly.
  89071. * @param meshes The mesh to target.
  89072. * @param radius Optional. If a cached radius position already exists, overrides default.
  89073. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89074. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89075. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89076. */
  89077. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  89078. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89079. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89080. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  89081. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  89082. for (var i = 0; i < meshes.length; i++) {
  89083. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  89084. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  89085. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  89086. }
  89087. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  89088. };
  89089. /**
  89090. * Targets the given mesh and updates zoom level accordingly.
  89091. * @param mesh The mesh to target.
  89092. * @param radius Optional. If a cached radius position already exists, overrides default.
  89093. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89094. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89095. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89096. */
  89097. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  89098. var _this = this;
  89099. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89100. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89101. var zoomTarget;
  89102. if (!this._attachedCamera) {
  89103. return;
  89104. }
  89105. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  89106. var bottom = minimumWorld.y;
  89107. var top = maximumWorld.y;
  89108. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  89109. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  89110. if (focusOnOriginXZ) {
  89111. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  89112. }
  89113. else {
  89114. var centerWorld = minimumWorld.add(radiusWorld);
  89115. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  89116. }
  89117. if (!this._vectorTransition) {
  89118. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  89119. }
  89120. this._betaIsAnimating = true;
  89121. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  89122. if (animatable) {
  89123. this._animatables.push(animatable);
  89124. }
  89125. // sets the radius and lower radius bounds
  89126. // Small delta ensures camera is not always at lower zoom limit.
  89127. var radius = 0;
  89128. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  89129. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  89130. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  89131. radius = position;
  89132. }
  89133. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  89134. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  89135. if (this._attachedCamera.lowerRadiusLimit === null) {
  89136. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  89137. }
  89138. }
  89139. // Set sensibilities
  89140. var extend = maximumWorld.subtract(minimumWorld).length();
  89141. this._attachedCamera.panningSensibility = 5000 / extend;
  89142. this._attachedCamera.wheelPrecision = 100 / radius;
  89143. // transition to new radius
  89144. if (!this._radiusTransition) {
  89145. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  89146. }
  89147. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  89148. _this.stopAllAnimations();
  89149. if (onAnimationEnd) {
  89150. onAnimationEnd();
  89151. }
  89152. if (_this._attachedCamera) {
  89153. _this._attachedCamera.storeState();
  89154. }
  89155. });
  89156. if (animatable) {
  89157. this._animatables.push(animatable);
  89158. }
  89159. };
  89160. /**
  89161. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  89162. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  89163. * frustum width.
  89164. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  89165. * to fully enclose the mesh in the viewing frustum.
  89166. */
  89167. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  89168. var size = maximumWorld.subtract(minimumWorld);
  89169. var boxVectorGlobalDiagonal = size.length();
  89170. var frustumSlope = this._getFrustumSlope();
  89171. // Formula for setting distance
  89172. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  89173. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  89174. // Horizon distance
  89175. var radius = radiusWithoutFraming * this._radiusScale;
  89176. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  89177. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  89178. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  89179. var camera = this._attachedCamera;
  89180. if (!camera) {
  89181. return 0;
  89182. }
  89183. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  89184. // Don't exceed the requested limit
  89185. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  89186. }
  89187. // Don't exceed the upper radius limit
  89188. if (camera.upperRadiusLimit) {
  89189. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  89190. }
  89191. return distance;
  89192. };
  89193. /**
  89194. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  89195. * is automatically returned to its default position (expected to be above ground plane).
  89196. */
  89197. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  89198. var _this = this;
  89199. if (this._elevationReturnTime < 0) {
  89200. return;
  89201. }
  89202. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  89203. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  89204. var limitBeta = Math.PI * 0.5;
  89205. // Bring the camera back up if below the ground plane
  89206. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  89207. this._betaIsAnimating = true;
  89208. //Transition to new position
  89209. this.stopAllAnimations();
  89210. if (!this._betaTransition) {
  89211. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  89212. }
  89213. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  89214. _this._clearAnimationLocks();
  89215. _this.stopAllAnimations();
  89216. });
  89217. if (animatabe) {
  89218. this._animatables.push(animatabe);
  89219. }
  89220. }
  89221. };
  89222. /**
  89223. * Returns the frustum slope based on the canvas ratio and camera FOV
  89224. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  89225. */
  89226. FramingBehavior.prototype._getFrustumSlope = function () {
  89227. // Calculate the viewport ratio
  89228. // Aspect Ratio is Height/Width.
  89229. var camera = this._attachedCamera;
  89230. if (!camera) {
  89231. return BABYLON.Vector2.Zero();
  89232. }
  89233. var engine = camera.getScene().getEngine();
  89234. var aspectRatio = engine.getAspectRatio(camera);
  89235. // Camera FOV is the vertical field of view (top-bottom) in radians.
  89236. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  89237. var frustumSlopeY = Math.tan(camera.fov / 2);
  89238. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  89239. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  89240. // along the forward vector.
  89241. var frustumSlopeX = frustumSlopeY * aspectRatio;
  89242. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  89243. };
  89244. /**
  89245. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  89246. */
  89247. FramingBehavior.prototype._clearAnimationLocks = function () {
  89248. this._betaIsAnimating = false;
  89249. };
  89250. /**
  89251. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  89252. */
  89253. FramingBehavior.prototype._applyUserInteraction = function () {
  89254. if (this.isUserIsMoving) {
  89255. this._lastInteractionTime = BABYLON.Tools.Now;
  89256. this.stopAllAnimations();
  89257. this._clearAnimationLocks();
  89258. }
  89259. };
  89260. /**
  89261. * Stops and removes all animations that have been applied to the camera
  89262. */
  89263. FramingBehavior.prototype.stopAllAnimations = function () {
  89264. if (this._attachedCamera) {
  89265. this._attachedCamera.animations = [];
  89266. }
  89267. while (this._animatables.length) {
  89268. if (this._animatables[0]) {
  89269. this._animatables[0].onAnimationEnd = null;
  89270. this._animatables[0].stop();
  89271. }
  89272. this._animatables.shift();
  89273. }
  89274. };
  89275. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  89276. /**
  89277. * Gets a value indicating if the user is moving the camera
  89278. */
  89279. get: function () {
  89280. if (!this._attachedCamera) {
  89281. return false;
  89282. }
  89283. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  89284. this._attachedCamera.inertialBetaOffset !== 0 ||
  89285. this._attachedCamera.inertialRadiusOffset !== 0 ||
  89286. this._attachedCamera.inertialPanningX !== 0 ||
  89287. this._attachedCamera.inertialPanningY !== 0 ||
  89288. this._isPointerDown;
  89289. },
  89290. enumerable: true,
  89291. configurable: true
  89292. });
  89293. /**
  89294. * The easing function used by animations
  89295. */
  89296. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  89297. /**
  89298. * The easing mode used by animations
  89299. */
  89300. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  89301. // Statics
  89302. /**
  89303. * The camera can move all the way towards the mesh.
  89304. */
  89305. FramingBehavior.IgnoreBoundsSizeMode = 0;
  89306. /**
  89307. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  89308. */
  89309. FramingBehavior.FitFrustumSidesMode = 1;
  89310. return FramingBehavior;
  89311. }());
  89312. BABYLON.FramingBehavior = FramingBehavior;
  89313. })(BABYLON || (BABYLON = {}));
  89314. //# sourceMappingURL=babylon.framingBehavior.js.map
  89315. "use strict";
  89316. var BABYLON;
  89317. (function (BABYLON) {
  89318. /**
  89319. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  89320. */
  89321. var BouncingBehavior = /** @class */ (function () {
  89322. function BouncingBehavior() {
  89323. /**
  89324. * The duration of the animation, in milliseconds
  89325. */
  89326. this.transitionDuration = 450;
  89327. /**
  89328. * Length of the distance animated by the transition when lower radius is reached
  89329. */
  89330. this.lowerRadiusTransitionRange = 2;
  89331. /**
  89332. * Length of the distance animated by the transition when upper radius is reached
  89333. */
  89334. this.upperRadiusTransitionRange = -2;
  89335. this._autoTransitionRange = false;
  89336. // Animations
  89337. this._radiusIsAnimating = false;
  89338. this._radiusBounceTransition = null;
  89339. this._animatables = new Array();
  89340. }
  89341. Object.defineProperty(BouncingBehavior.prototype, "name", {
  89342. get: function () {
  89343. return "Bouncing";
  89344. },
  89345. enumerable: true,
  89346. configurable: true
  89347. });
  89348. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  89349. /**
  89350. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  89351. */
  89352. get: function () {
  89353. return this._autoTransitionRange;
  89354. },
  89355. /**
  89356. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  89357. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  89358. */
  89359. set: function (value) {
  89360. var _this = this;
  89361. if (this._autoTransitionRange === value) {
  89362. return;
  89363. }
  89364. this._autoTransitionRange = value;
  89365. var camera = this._attachedCamera;
  89366. if (!camera) {
  89367. return;
  89368. }
  89369. if (value) {
  89370. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  89371. if (!mesh) {
  89372. return;
  89373. }
  89374. mesh.computeWorldMatrix(true);
  89375. var diagonal = mesh.getBoundingInfo().diagonalLength;
  89376. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  89377. _this.upperRadiusTransitionRange = diagonal * 0.05;
  89378. });
  89379. }
  89380. else if (this._onMeshTargetChangedObserver) {
  89381. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  89382. }
  89383. },
  89384. enumerable: true,
  89385. configurable: true
  89386. });
  89387. BouncingBehavior.prototype.init = function () {
  89388. // Do notihng
  89389. };
  89390. BouncingBehavior.prototype.attach = function (camera) {
  89391. var _this = this;
  89392. this._attachedCamera = camera;
  89393. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  89394. if (!_this._attachedCamera) {
  89395. return;
  89396. }
  89397. // Add the bounce animation to the lower radius limit
  89398. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  89399. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  89400. }
  89401. // Add the bounce animation to the upper radius limit
  89402. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  89403. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  89404. }
  89405. });
  89406. };
  89407. BouncingBehavior.prototype.detach = function () {
  89408. if (!this._attachedCamera) {
  89409. return;
  89410. }
  89411. if (this._onAfterCheckInputsObserver) {
  89412. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  89413. }
  89414. if (this._onMeshTargetChangedObserver) {
  89415. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  89416. }
  89417. this._attachedCamera = null;
  89418. };
  89419. /**
  89420. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  89421. * @param radiusLimit The limit to check against.
  89422. * @return Bool to indicate if at limit.
  89423. */
  89424. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  89425. if (!this._attachedCamera) {
  89426. return false;
  89427. }
  89428. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  89429. return true;
  89430. }
  89431. return false;
  89432. };
  89433. /**
  89434. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  89435. * @param radiusDelta The delta by which to animate to. Can be negative.
  89436. */
  89437. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  89438. var _this = this;
  89439. if (!this._attachedCamera) {
  89440. return;
  89441. }
  89442. if (!this._radiusBounceTransition) {
  89443. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  89444. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  89445. }
  89446. // Prevent zoom until bounce has completed
  89447. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  89448. this._attachedCamera.wheelPrecision = Infinity;
  89449. this._attachedCamera.inertialRadiusOffset = 0;
  89450. // Animate to the radius limit
  89451. this.stopAllAnimations();
  89452. this._radiusIsAnimating = true;
  89453. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  89454. if (animatable) {
  89455. this._animatables.push(animatable);
  89456. }
  89457. };
  89458. /**
  89459. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  89460. */
  89461. BouncingBehavior.prototype._clearAnimationLocks = function () {
  89462. this._radiusIsAnimating = false;
  89463. if (this._attachedCamera) {
  89464. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  89465. }
  89466. };
  89467. /**
  89468. * Stops and removes all animations that have been applied to the camera
  89469. */
  89470. BouncingBehavior.prototype.stopAllAnimations = function () {
  89471. if (this._attachedCamera) {
  89472. this._attachedCamera.animations = [];
  89473. }
  89474. while (this._animatables.length) {
  89475. this._animatables[0].onAnimationEnd = null;
  89476. this._animatables[0].stop();
  89477. this._animatables.shift();
  89478. }
  89479. };
  89480. /**
  89481. * The easing function used by animations
  89482. */
  89483. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  89484. /**
  89485. * The easing mode used by animations
  89486. */
  89487. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  89488. return BouncingBehavior;
  89489. }());
  89490. BABYLON.BouncingBehavior = BouncingBehavior;
  89491. })(BABYLON || (BABYLON = {}));
  89492. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  89493. "use strict";
  89494. var BABYLON;
  89495. (function (BABYLON) {
  89496. var AutoRotationBehavior = /** @class */ (function () {
  89497. function AutoRotationBehavior() {
  89498. this._zoomStopsAnimation = false;
  89499. this._idleRotationSpeed = 0.05;
  89500. this._idleRotationWaitTime = 2000;
  89501. this._idleRotationSpinupTime = 2000;
  89502. this._isPointerDown = false;
  89503. this._lastFrameTime = null;
  89504. this._lastInteractionTime = -Infinity;
  89505. this._cameraRotationSpeed = 0;
  89506. this._lastFrameRadius = 0;
  89507. }
  89508. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  89509. get: function () {
  89510. return "AutoRotation";
  89511. },
  89512. enumerable: true,
  89513. configurable: true
  89514. });
  89515. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  89516. /**
  89517. * Gets the flag that indicates if user zooming should stop animation.
  89518. */
  89519. get: function () {
  89520. return this._zoomStopsAnimation;
  89521. },
  89522. /**
  89523. * Sets the flag that indicates if user zooming should stop animation.
  89524. */
  89525. set: function (flag) {
  89526. this._zoomStopsAnimation = flag;
  89527. },
  89528. enumerable: true,
  89529. configurable: true
  89530. });
  89531. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  89532. /**
  89533. * Gets the default speed at which the camera rotates around the model.
  89534. */
  89535. get: function () {
  89536. return this._idleRotationSpeed;
  89537. },
  89538. /**
  89539. * Sets the default speed at which the camera rotates around the model.
  89540. */
  89541. set: function (speed) {
  89542. this._idleRotationSpeed = speed;
  89543. },
  89544. enumerable: true,
  89545. configurable: true
  89546. });
  89547. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  89548. /**
  89549. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  89550. */
  89551. get: function () {
  89552. return this._idleRotationWaitTime;
  89553. },
  89554. /**
  89555. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  89556. */
  89557. set: function (time) {
  89558. this._idleRotationWaitTime = time;
  89559. },
  89560. enumerable: true,
  89561. configurable: true
  89562. });
  89563. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  89564. /**
  89565. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  89566. */
  89567. get: function () {
  89568. return this._idleRotationSpinupTime;
  89569. },
  89570. /**
  89571. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  89572. */
  89573. set: function (time) {
  89574. this._idleRotationSpinupTime = time;
  89575. },
  89576. enumerable: true,
  89577. configurable: true
  89578. });
  89579. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  89580. /**
  89581. * Gets a value indicating if the camera is currently rotating because of this behavior
  89582. */
  89583. get: function () {
  89584. return Math.abs(this._cameraRotationSpeed) > 0;
  89585. },
  89586. enumerable: true,
  89587. configurable: true
  89588. });
  89589. AutoRotationBehavior.prototype.init = function () {
  89590. // Do notihng
  89591. };
  89592. AutoRotationBehavior.prototype.attach = function (camera) {
  89593. var _this = this;
  89594. this._attachedCamera = camera;
  89595. var scene = this._attachedCamera.getScene();
  89596. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  89597. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  89598. _this._isPointerDown = true;
  89599. return;
  89600. }
  89601. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  89602. _this._isPointerDown = false;
  89603. }
  89604. });
  89605. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  89606. var now = BABYLON.Tools.Now;
  89607. var dt = 0;
  89608. if (_this._lastFrameTime != null) {
  89609. dt = now - _this._lastFrameTime;
  89610. }
  89611. _this._lastFrameTime = now;
  89612. // Stop the animation if there is user interaction and the animation should stop for this interaction
  89613. _this._applyUserInteraction();
  89614. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  89615. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  89616. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  89617. // Step camera rotation by rotation speed
  89618. if (_this._attachedCamera) {
  89619. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  89620. }
  89621. });
  89622. };
  89623. AutoRotationBehavior.prototype.detach = function () {
  89624. if (!this._attachedCamera) {
  89625. return;
  89626. }
  89627. var scene = this._attachedCamera.getScene();
  89628. if (this._onPrePointerObservableObserver) {
  89629. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  89630. }
  89631. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  89632. this._attachedCamera = null;
  89633. };
  89634. /**
  89635. * Returns true if user is scrolling.
  89636. * @return true if user is scrolling.
  89637. */
  89638. AutoRotationBehavior.prototype._userIsZooming = function () {
  89639. if (!this._attachedCamera) {
  89640. return false;
  89641. }
  89642. return this._attachedCamera.inertialRadiusOffset !== 0;
  89643. };
  89644. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  89645. if (!this._attachedCamera) {
  89646. return false;
  89647. }
  89648. var zoomHasHitLimit = false;
  89649. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  89650. zoomHasHitLimit = true;
  89651. }
  89652. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  89653. this._lastFrameRadius = this._attachedCamera.radius;
  89654. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  89655. };
  89656. /**
  89657. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  89658. */
  89659. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  89660. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  89661. this._lastInteractionTime = BABYLON.Tools.Now;
  89662. }
  89663. };
  89664. // Tools
  89665. AutoRotationBehavior.prototype._userIsMoving = function () {
  89666. if (!this._attachedCamera) {
  89667. return false;
  89668. }
  89669. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  89670. this._attachedCamera.inertialBetaOffset !== 0 ||
  89671. this._attachedCamera.inertialRadiusOffset !== 0 ||
  89672. this._attachedCamera.inertialPanningX !== 0 ||
  89673. this._attachedCamera.inertialPanningY !== 0 ||
  89674. this._isPointerDown;
  89675. };
  89676. return AutoRotationBehavior;
  89677. }());
  89678. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  89679. })(BABYLON || (BABYLON = {}));
  89680. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  89681. "use strict";
  89682. var BABYLON;
  89683. (function (BABYLON) {
  89684. var NullEngineOptions = /** @class */ (function () {
  89685. function NullEngineOptions() {
  89686. this.renderWidth = 512;
  89687. this.renderHeight = 256;
  89688. this.textureSize = 512;
  89689. this.deterministicLockstep = false;
  89690. this.lockstepMaxSteps = 4;
  89691. }
  89692. return NullEngineOptions;
  89693. }());
  89694. BABYLON.NullEngineOptions = NullEngineOptions;
  89695. /**
  89696. * The null engine class provides support for headless version of babylon.js.
  89697. * This can be used in server side scenario or for testing purposes
  89698. */
  89699. var NullEngine = /** @class */ (function (_super) {
  89700. __extends(NullEngine, _super);
  89701. function NullEngine(options) {
  89702. if (options === void 0) { options = new NullEngineOptions(); }
  89703. var _this = _super.call(this, null) || this;
  89704. if (options.deterministicLockstep === undefined) {
  89705. options.deterministicLockstep = false;
  89706. }
  89707. if (options.lockstepMaxSteps === undefined) {
  89708. options.lockstepMaxSteps = 4;
  89709. }
  89710. _this._options = options;
  89711. // Init caps
  89712. // We consider we are on a webgl1 capable device
  89713. _this._caps = new BABYLON.EngineCapabilities();
  89714. _this._caps.maxTexturesImageUnits = 16;
  89715. _this._caps.maxVertexTextureImageUnits = 16;
  89716. _this._caps.maxTextureSize = 512;
  89717. _this._caps.maxCubemapTextureSize = 512;
  89718. _this._caps.maxRenderTextureSize = 512;
  89719. _this._caps.maxVertexAttribs = 16;
  89720. _this._caps.maxVaryingVectors = 16;
  89721. _this._caps.maxFragmentUniformVectors = 16;
  89722. _this._caps.maxVertexUniformVectors = 16;
  89723. // Extensions
  89724. _this._caps.standardDerivatives = false;
  89725. _this._caps.astc = null;
  89726. _this._caps.s3tc = null;
  89727. _this._caps.pvrtc = null;
  89728. _this._caps.etc1 = null;
  89729. _this._caps.etc2 = null;
  89730. _this._caps.textureAnisotropicFilterExtension = null;
  89731. _this._caps.maxAnisotropy = 0;
  89732. _this._caps.uintIndices = false;
  89733. _this._caps.fragmentDepthSupported = false;
  89734. _this._caps.highPrecisionShaderSupported = true;
  89735. _this._caps.colorBufferFloat = false;
  89736. _this._caps.textureFloat = false;
  89737. _this._caps.textureFloatLinearFiltering = false;
  89738. _this._caps.textureFloatRender = false;
  89739. _this._caps.textureHalfFloat = false;
  89740. _this._caps.textureHalfFloatLinearFiltering = false;
  89741. _this._caps.textureHalfFloatRender = false;
  89742. _this._caps.textureLOD = false;
  89743. _this._caps.drawBuffersExtension = false;
  89744. _this._caps.depthTextureExtension = false;
  89745. _this._caps.vertexArrayObject = false;
  89746. _this._caps.instancedArrays = false;
  89747. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  89748. // Wrappers
  89749. if (typeof URL === "undefined") {
  89750. URL = {
  89751. createObjectURL: function () { },
  89752. revokeObjectURL: function () { }
  89753. };
  89754. }
  89755. if (typeof Blob === "undefined") {
  89756. Blob = function () { };
  89757. }
  89758. return _this;
  89759. }
  89760. NullEngine.prototype.isDeterministicLockStep = function () {
  89761. return this._options.deterministicLockstep;
  89762. };
  89763. NullEngine.prototype.getLockstepMaxSteps = function () {
  89764. return this._options.lockstepMaxSteps;
  89765. };
  89766. NullEngine.prototype.getHardwareScalingLevel = function () {
  89767. return 1.0;
  89768. };
  89769. NullEngine.prototype.createVertexBuffer = function (vertices) {
  89770. return {
  89771. capacity: 0,
  89772. references: 1,
  89773. is32Bits: false
  89774. };
  89775. };
  89776. NullEngine.prototype.createIndexBuffer = function (indices) {
  89777. return {
  89778. capacity: 0,
  89779. references: 1,
  89780. is32Bits: false
  89781. };
  89782. };
  89783. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  89784. if (stencil === void 0) { stencil = false; }
  89785. };
  89786. NullEngine.prototype.getRenderWidth = function (useScreen) {
  89787. if (useScreen === void 0) { useScreen = false; }
  89788. if (!useScreen && this._currentRenderTarget) {
  89789. return this._currentRenderTarget.width;
  89790. }
  89791. return this._options.renderWidth;
  89792. };
  89793. NullEngine.prototype.getRenderHeight = function (useScreen) {
  89794. if (useScreen === void 0) { useScreen = false; }
  89795. if (!useScreen && this._currentRenderTarget) {
  89796. return this._currentRenderTarget.height;
  89797. }
  89798. return this._options.renderHeight;
  89799. };
  89800. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  89801. this._cachedViewport = viewport;
  89802. };
  89803. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  89804. return {
  89805. transformFeedback: null,
  89806. __SPECTOR_rebuildProgram: null
  89807. };
  89808. };
  89809. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  89810. return [];
  89811. };
  89812. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  89813. return [];
  89814. };
  89815. NullEngine.prototype.bindSamplers = function (effect) {
  89816. this._currentEffect = null;
  89817. };
  89818. NullEngine.prototype.enableEffect = function (effect) {
  89819. this._currentEffect = effect;
  89820. if (effect.onBind) {
  89821. effect.onBind(effect);
  89822. }
  89823. effect.onBindObservable.notifyObservers(effect);
  89824. };
  89825. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  89826. if (zOffset === void 0) { zOffset = 0; }
  89827. if (reverseSide === void 0) { reverseSide = false; }
  89828. };
  89829. NullEngine.prototype.setIntArray = function (uniform, array) {
  89830. };
  89831. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  89832. };
  89833. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  89834. };
  89835. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  89836. };
  89837. NullEngine.prototype.setFloatArray = function (uniform, array) {
  89838. };
  89839. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  89840. };
  89841. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  89842. };
  89843. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  89844. };
  89845. NullEngine.prototype.setArray = function (uniform, array) {
  89846. };
  89847. NullEngine.prototype.setArray2 = function (uniform, array) {
  89848. };
  89849. NullEngine.prototype.setArray3 = function (uniform, array) {
  89850. };
  89851. NullEngine.prototype.setArray4 = function (uniform, array) {
  89852. };
  89853. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  89854. };
  89855. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  89856. };
  89857. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  89858. };
  89859. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  89860. };
  89861. NullEngine.prototype.setFloat = function (uniform, value) {
  89862. };
  89863. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  89864. };
  89865. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  89866. };
  89867. NullEngine.prototype.setBool = function (uniform, bool) {
  89868. };
  89869. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  89870. };
  89871. NullEngine.prototype.setColor3 = function (uniform, color3) {
  89872. };
  89873. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  89874. };
  89875. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  89876. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  89877. if (this._alphaMode === mode) {
  89878. return;
  89879. }
  89880. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  89881. if (!noDepthWriteChange) {
  89882. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  89883. }
  89884. this._alphaMode = mode;
  89885. };
  89886. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  89887. };
  89888. NullEngine.prototype.wipeCaches = function (bruteForce) {
  89889. if (this.preventCacheWipeBetweenFrames) {
  89890. return;
  89891. }
  89892. this.resetTextureCache();
  89893. this._currentEffect = null;
  89894. if (bruteForce) {
  89895. this._currentProgram = null;
  89896. this._stencilState.reset();
  89897. this._depthCullingState.reset();
  89898. this._alphaState.reset();
  89899. }
  89900. this._cachedVertexBuffers = null;
  89901. this._cachedIndexBuffer = null;
  89902. this._cachedEffectForVertexBuffers = null;
  89903. };
  89904. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  89905. };
  89906. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  89907. };
  89908. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  89909. };
  89910. NullEngine.prototype._createTexture = function () {
  89911. return {};
  89912. };
  89913. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  89914. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  89915. if (onLoad === void 0) { onLoad = null; }
  89916. if (onError === void 0) { onError = null; }
  89917. if (buffer === void 0) { buffer = null; }
  89918. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  89919. var url = String(urlArg);
  89920. texture.url = url;
  89921. texture.generateMipMaps = !noMipmap;
  89922. texture.samplingMode = samplingMode;
  89923. texture.invertY = invertY;
  89924. texture.baseWidth = this._options.textureSize;
  89925. texture.baseHeight = this._options.textureSize;
  89926. texture.width = this._options.textureSize;
  89927. texture.height = this._options.textureSize;
  89928. if (format) {
  89929. texture.format = format;
  89930. }
  89931. texture.isReady = true;
  89932. if (onLoad) {
  89933. onLoad();
  89934. }
  89935. return texture;
  89936. };
  89937. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  89938. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  89939. if (options !== undefined && typeof options === "object") {
  89940. fullOptions.generateMipMaps = options.generateMipMaps;
  89941. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  89942. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  89943. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  89944. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  89945. }
  89946. else {
  89947. fullOptions.generateMipMaps = options;
  89948. fullOptions.generateDepthBuffer = true;
  89949. fullOptions.generateStencilBuffer = false;
  89950. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89951. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  89952. }
  89953. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  89954. var width = size.width || size;
  89955. var height = size.height || size;
  89956. texture._depthStencilBuffer = {};
  89957. texture._framebuffer = {};
  89958. texture.baseWidth = width;
  89959. texture.baseHeight = height;
  89960. texture.width = width;
  89961. texture.height = height;
  89962. texture.isReady = true;
  89963. texture.samples = 1;
  89964. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  89965. texture.samplingMode = fullOptions.samplingMode;
  89966. texture.type = fullOptions.type;
  89967. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  89968. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  89969. return texture;
  89970. };
  89971. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  89972. texture.samplingMode = samplingMode;
  89973. };
  89974. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  89975. if (this._currentRenderTarget) {
  89976. this.unBindFramebuffer(this._currentRenderTarget);
  89977. }
  89978. this._currentRenderTarget = texture;
  89979. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  89980. if (this._cachedViewport && !forceFullscreenViewport) {
  89981. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  89982. }
  89983. };
  89984. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  89985. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  89986. this._currentRenderTarget = null;
  89987. if (onBeforeUnbind) {
  89988. if (texture._MSAAFramebuffer) {
  89989. this._currentFramebuffer = texture._framebuffer;
  89990. }
  89991. onBeforeUnbind();
  89992. }
  89993. this._currentFramebuffer = null;
  89994. };
  89995. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  89996. var vbo = {
  89997. capacity: 1,
  89998. references: 1,
  89999. is32Bits: false
  90000. };
  90001. return vbo;
  90002. };
  90003. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  90004. if (offset === void 0) { offset = 0; }
  90005. };
  90006. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  90007. };
  90008. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  90009. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  90010. this._boundTexturesCache[this._activeChannel] = texture;
  90011. }
  90012. };
  90013. NullEngine.prototype._bindTexture = function (channel, texture) {
  90014. if (channel < 0) {
  90015. return;
  90016. }
  90017. this._bindTextureDirectly(0, texture);
  90018. };
  90019. NullEngine.prototype._releaseBuffer = function (buffer) {
  90020. buffer.references--;
  90021. if (buffer.references === 0) {
  90022. return true;
  90023. }
  90024. return false;
  90025. };
  90026. return NullEngine;
  90027. }(BABYLON.Engine));
  90028. BABYLON.NullEngine = NullEngine;
  90029. })(BABYLON || (BABYLON = {}));
  90030. //# sourceMappingURL=babylon.nullEngine.js.map
  90031. "use strict";
  90032. var BABYLON;
  90033. (function (BABYLON) {
  90034. /**
  90035. * This class can be used to get instrumentation data from a Babylon engine
  90036. */
  90037. var EngineInstrumentation = /** @class */ (function () {
  90038. function EngineInstrumentation(engine) {
  90039. this.engine = engine;
  90040. this._captureGPUFrameTime = false;
  90041. this._gpuFrameTime = new BABYLON.PerfCounter();
  90042. this._captureShaderCompilationTime = false;
  90043. this._shaderCompilationTime = new BABYLON.PerfCounter();
  90044. // Observers
  90045. this._onBeginFrameObserver = null;
  90046. this._onEndFrameObserver = null;
  90047. this._onBeforeShaderCompilationObserver = null;
  90048. this._onAfterShaderCompilationObserver = null;
  90049. }
  90050. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  90051. // Properties
  90052. /**
  90053. * Gets the perf counter used for GPU frame time
  90054. */
  90055. get: function () {
  90056. return this._gpuFrameTime;
  90057. },
  90058. enumerable: true,
  90059. configurable: true
  90060. });
  90061. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  90062. /**
  90063. * Gets the GPU frame time capture status
  90064. */
  90065. get: function () {
  90066. return this._captureGPUFrameTime;
  90067. },
  90068. /**
  90069. * Enable or disable the GPU frame time capture
  90070. */
  90071. set: function (value) {
  90072. var _this = this;
  90073. if (value === this._captureGPUFrameTime) {
  90074. return;
  90075. }
  90076. this._captureGPUFrameTime = value;
  90077. if (value) {
  90078. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  90079. if (!_this._gpuFrameTimeToken) {
  90080. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  90081. }
  90082. });
  90083. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  90084. if (!_this._gpuFrameTimeToken) {
  90085. return;
  90086. }
  90087. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  90088. if (time > -1) {
  90089. _this._gpuFrameTimeToken = null;
  90090. _this._gpuFrameTime.fetchNewFrame();
  90091. _this._gpuFrameTime.addCount(time, true);
  90092. }
  90093. });
  90094. }
  90095. else {
  90096. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  90097. this._onBeginFrameObserver = null;
  90098. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  90099. this._onEndFrameObserver = null;
  90100. }
  90101. },
  90102. enumerable: true,
  90103. configurable: true
  90104. });
  90105. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  90106. /**
  90107. * Gets the perf counter used for shader compilation time
  90108. */
  90109. get: function () {
  90110. return this._shaderCompilationTime;
  90111. },
  90112. enumerable: true,
  90113. configurable: true
  90114. });
  90115. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  90116. /**
  90117. * Gets the shader compilation time capture status
  90118. */
  90119. get: function () {
  90120. return this._captureShaderCompilationTime;
  90121. },
  90122. /**
  90123. * Enable or disable the shader compilation time capture
  90124. */
  90125. set: function (value) {
  90126. var _this = this;
  90127. if (value === this._captureShaderCompilationTime) {
  90128. return;
  90129. }
  90130. this._captureShaderCompilationTime = value;
  90131. if (value) {
  90132. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  90133. _this._shaderCompilationTime.fetchNewFrame();
  90134. _this._shaderCompilationTime.beginMonitoring();
  90135. });
  90136. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  90137. _this._shaderCompilationTime.endMonitoring();
  90138. });
  90139. }
  90140. else {
  90141. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  90142. this._onBeforeShaderCompilationObserver = null;
  90143. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  90144. this._onAfterShaderCompilationObserver = null;
  90145. }
  90146. },
  90147. enumerable: true,
  90148. configurable: true
  90149. });
  90150. EngineInstrumentation.prototype.dispose = function () {
  90151. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  90152. this._onBeginFrameObserver = null;
  90153. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  90154. this._onEndFrameObserver = null;
  90155. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  90156. this._onBeforeShaderCompilationObserver = null;
  90157. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  90158. this._onAfterShaderCompilationObserver = null;
  90159. this.engine = null;
  90160. };
  90161. return EngineInstrumentation;
  90162. }());
  90163. BABYLON.EngineInstrumentation = EngineInstrumentation;
  90164. })(BABYLON || (BABYLON = {}));
  90165. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  90166. "use strict";
  90167. var BABYLON;
  90168. (function (BABYLON) {
  90169. /**
  90170. * This class can be used to get instrumentation data from a Babylon engine
  90171. */
  90172. var SceneInstrumentation = /** @class */ (function () {
  90173. function SceneInstrumentation(scene) {
  90174. var _this = this;
  90175. this.scene = scene;
  90176. this._captureActiveMeshesEvaluationTime = false;
  90177. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  90178. this._captureRenderTargetsRenderTime = false;
  90179. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  90180. this._captureFrameTime = false;
  90181. this._frameTime = new BABYLON.PerfCounter();
  90182. this._captureRenderTime = false;
  90183. this._renderTime = new BABYLON.PerfCounter();
  90184. this._captureInterFrameTime = false;
  90185. this._interFrameTime = new BABYLON.PerfCounter();
  90186. this._captureParticlesRenderTime = false;
  90187. this._particlesRenderTime = new BABYLON.PerfCounter();
  90188. this._captureSpritesRenderTime = false;
  90189. this._spritesRenderTime = new BABYLON.PerfCounter();
  90190. this._capturePhysicsTime = false;
  90191. this._physicsTime = new BABYLON.PerfCounter();
  90192. this._captureAnimationsTime = false;
  90193. this._animationsTime = new BABYLON.PerfCounter();
  90194. // Observers
  90195. this._onBeforeActiveMeshesEvaluationObserver = null;
  90196. this._onAfterActiveMeshesEvaluationObserver = null;
  90197. this._onBeforeRenderTargetsRenderObserver = null;
  90198. this._onAfterRenderTargetsRenderObserver = null;
  90199. this._onAfterRenderObserver = null;
  90200. this._onBeforeDrawPhaseObserver = null;
  90201. this._onAfterDrawPhaseObserver = null;
  90202. this._onBeforeAnimationsObserver = null;
  90203. this._onBeforeParticlesRenderingObserver = null;
  90204. this._onAfterParticlesRenderingObserver = null;
  90205. this._onBeforeSpritesRenderingObserver = null;
  90206. this._onAfterSpritesRenderingObserver = null;
  90207. this._onBeforePhysicsObserver = null;
  90208. this._onAfterPhysicsObserver = null;
  90209. this._onAfterAnimationsObserver = null;
  90210. // Before render
  90211. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  90212. if (_this._captureActiveMeshesEvaluationTime) {
  90213. _this._activeMeshesEvaluationTime.fetchNewFrame();
  90214. }
  90215. if (_this._captureRenderTargetsRenderTime) {
  90216. _this._renderTargetsRenderTime.fetchNewFrame();
  90217. }
  90218. if (_this._captureFrameTime) {
  90219. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  90220. _this._frameTime.beginMonitoring();
  90221. }
  90222. if (_this._captureInterFrameTime) {
  90223. _this._interFrameTime.endMonitoring();
  90224. }
  90225. if (_this._captureParticlesRenderTime) {
  90226. _this._particlesRenderTime.fetchNewFrame();
  90227. }
  90228. if (_this._captureSpritesRenderTime) {
  90229. _this._spritesRenderTime.fetchNewFrame();
  90230. }
  90231. if (_this._captureAnimationsTime) {
  90232. _this._animationsTime.beginMonitoring();
  90233. }
  90234. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  90235. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  90236. });
  90237. // After render
  90238. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  90239. if (_this._captureFrameTime) {
  90240. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  90241. _this._frameTime.endMonitoring();
  90242. }
  90243. if (_this._captureRenderTime) {
  90244. _this._renderTime.endMonitoring(false);
  90245. }
  90246. if (_this._captureInterFrameTime) {
  90247. _this._interFrameTime.beginMonitoring();
  90248. }
  90249. });
  90250. }
  90251. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  90252. // Properties
  90253. /**
  90254. * Gets the perf counter used for active meshes evaluation time
  90255. */
  90256. get: function () {
  90257. return this._activeMeshesEvaluationTime;
  90258. },
  90259. enumerable: true,
  90260. configurable: true
  90261. });
  90262. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  90263. /**
  90264. * Gets the active meshes evaluation time capture status
  90265. */
  90266. get: function () {
  90267. return this._captureActiveMeshesEvaluationTime;
  90268. },
  90269. /**
  90270. * Enable or disable the active meshes evaluation time capture
  90271. */
  90272. set: function (value) {
  90273. var _this = this;
  90274. if (value === this._captureActiveMeshesEvaluationTime) {
  90275. return;
  90276. }
  90277. this._captureActiveMeshesEvaluationTime = value;
  90278. if (value) {
  90279. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  90280. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  90281. _this._activeMeshesEvaluationTime.beginMonitoring();
  90282. });
  90283. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  90284. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  90285. _this._activeMeshesEvaluationTime.endMonitoring();
  90286. });
  90287. }
  90288. else {
  90289. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  90290. this._onBeforeActiveMeshesEvaluationObserver = null;
  90291. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  90292. this._onAfterActiveMeshesEvaluationObserver = null;
  90293. }
  90294. },
  90295. enumerable: true,
  90296. configurable: true
  90297. });
  90298. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  90299. /**
  90300. * Gets the perf counter used for render targets render time
  90301. */
  90302. get: function () {
  90303. return this._renderTargetsRenderTime;
  90304. },
  90305. enumerable: true,
  90306. configurable: true
  90307. });
  90308. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  90309. /**
  90310. * Gets the render targets render time capture status
  90311. */
  90312. get: function () {
  90313. return this._captureRenderTargetsRenderTime;
  90314. },
  90315. /**
  90316. * Enable or disable the render targets render time capture
  90317. */
  90318. set: function (value) {
  90319. var _this = this;
  90320. if (value === this._captureRenderTargetsRenderTime) {
  90321. return;
  90322. }
  90323. this._captureRenderTargetsRenderTime = value;
  90324. if (value) {
  90325. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  90326. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  90327. _this._renderTargetsRenderTime.beginMonitoring();
  90328. });
  90329. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  90330. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  90331. _this._renderTargetsRenderTime.endMonitoring(false);
  90332. });
  90333. }
  90334. else {
  90335. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  90336. this._onBeforeRenderTargetsRenderObserver = null;
  90337. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  90338. this._onAfterRenderTargetsRenderObserver = null;
  90339. }
  90340. },
  90341. enumerable: true,
  90342. configurable: true
  90343. });
  90344. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  90345. /**
  90346. * Gets the perf counter used for particles render time
  90347. */
  90348. get: function () {
  90349. return this._particlesRenderTime;
  90350. },
  90351. enumerable: true,
  90352. configurable: true
  90353. });
  90354. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  90355. /**
  90356. * Gets the particles render time capture status
  90357. */
  90358. get: function () {
  90359. return this._captureParticlesRenderTime;
  90360. },
  90361. /**
  90362. * Enable or disable the particles render time capture
  90363. */
  90364. set: function (value) {
  90365. var _this = this;
  90366. if (value === this._captureParticlesRenderTime) {
  90367. return;
  90368. }
  90369. this._captureParticlesRenderTime = value;
  90370. if (value) {
  90371. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  90372. BABYLON.Tools.StartPerformanceCounter("Particles");
  90373. _this._particlesRenderTime.beginMonitoring();
  90374. });
  90375. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  90376. BABYLON.Tools.EndPerformanceCounter("Particles");
  90377. _this._particlesRenderTime.endMonitoring(false);
  90378. });
  90379. }
  90380. else {
  90381. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  90382. this._onBeforeParticlesRenderingObserver = null;
  90383. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  90384. this._onAfterParticlesRenderingObserver = null;
  90385. }
  90386. },
  90387. enumerable: true,
  90388. configurable: true
  90389. });
  90390. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  90391. /**
  90392. * Gets the perf counter used for sprites render time
  90393. */
  90394. get: function () {
  90395. return this._spritesRenderTime;
  90396. },
  90397. enumerable: true,
  90398. configurable: true
  90399. });
  90400. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  90401. /**
  90402. * Gets the sprites render time capture status
  90403. */
  90404. get: function () {
  90405. return this._captureSpritesRenderTime;
  90406. },
  90407. /**
  90408. * Enable or disable the sprites render time capture
  90409. */
  90410. set: function (value) {
  90411. var _this = this;
  90412. if (value === this._captureSpritesRenderTime) {
  90413. return;
  90414. }
  90415. this._captureSpritesRenderTime = value;
  90416. if (value) {
  90417. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  90418. BABYLON.Tools.StartPerformanceCounter("Sprites");
  90419. _this._spritesRenderTime.beginMonitoring();
  90420. });
  90421. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  90422. BABYLON.Tools.EndPerformanceCounter("Sprites");
  90423. _this._spritesRenderTime.endMonitoring(false);
  90424. });
  90425. }
  90426. else {
  90427. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  90428. this._onBeforeSpritesRenderingObserver = null;
  90429. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  90430. this._onAfterSpritesRenderingObserver = null;
  90431. }
  90432. },
  90433. enumerable: true,
  90434. configurable: true
  90435. });
  90436. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  90437. /**
  90438. * Gets the perf counter used for physics time
  90439. */
  90440. get: function () {
  90441. return this._physicsTime;
  90442. },
  90443. enumerable: true,
  90444. configurable: true
  90445. });
  90446. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  90447. /**
  90448. * Gets the physics time capture status
  90449. */
  90450. get: function () {
  90451. return this._capturePhysicsTime;
  90452. },
  90453. /**
  90454. * Enable or disable the physics time capture
  90455. */
  90456. set: function (value) {
  90457. var _this = this;
  90458. if (value === this._capturePhysicsTime) {
  90459. return;
  90460. }
  90461. this._capturePhysicsTime = value;
  90462. if (value) {
  90463. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  90464. BABYLON.Tools.StartPerformanceCounter("Physics");
  90465. _this._physicsTime.beginMonitoring();
  90466. });
  90467. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  90468. BABYLON.Tools.EndPerformanceCounter("Physics");
  90469. _this._physicsTime.endMonitoring();
  90470. });
  90471. }
  90472. else {
  90473. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  90474. this._onBeforePhysicsObserver = null;
  90475. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  90476. this._onAfterPhysicsObserver = null;
  90477. }
  90478. },
  90479. enumerable: true,
  90480. configurable: true
  90481. });
  90482. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  90483. /**
  90484. * Gets the perf counter used for animations time
  90485. */
  90486. get: function () {
  90487. return this._animationsTime;
  90488. },
  90489. enumerable: true,
  90490. configurable: true
  90491. });
  90492. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  90493. /**
  90494. * Gets the animations time capture status
  90495. */
  90496. get: function () {
  90497. return this._captureAnimationsTime;
  90498. },
  90499. /**
  90500. * Enable or disable the animations time capture
  90501. */
  90502. set: function (value) {
  90503. var _this = this;
  90504. if (value === this._captureAnimationsTime) {
  90505. return;
  90506. }
  90507. this._captureAnimationsTime = value;
  90508. if (value) {
  90509. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  90510. _this._animationsTime.endMonitoring();
  90511. });
  90512. }
  90513. else {
  90514. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  90515. this._onAfterAnimationsObserver = null;
  90516. }
  90517. },
  90518. enumerable: true,
  90519. configurable: true
  90520. });
  90521. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  90522. /**
  90523. * Gets the perf counter used for frame time capture
  90524. */
  90525. get: function () {
  90526. return this._frameTime;
  90527. },
  90528. enumerable: true,
  90529. configurable: true
  90530. });
  90531. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  90532. /**
  90533. * Gets the frame time capture status
  90534. */
  90535. get: function () {
  90536. return this._captureFrameTime;
  90537. },
  90538. /**
  90539. * Enable or disable the frame time capture
  90540. */
  90541. set: function (value) {
  90542. this._captureFrameTime = value;
  90543. },
  90544. enumerable: true,
  90545. configurable: true
  90546. });
  90547. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  90548. /**
  90549. * Gets the perf counter used for inter-frames time capture
  90550. */
  90551. get: function () {
  90552. return this._interFrameTime;
  90553. },
  90554. enumerable: true,
  90555. configurable: true
  90556. });
  90557. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  90558. /**
  90559. * Gets the inter-frames time capture status
  90560. */
  90561. get: function () {
  90562. return this._captureInterFrameTime;
  90563. },
  90564. /**
  90565. * Enable or disable the inter-frames time capture
  90566. */
  90567. set: function (value) {
  90568. this._captureInterFrameTime = value;
  90569. },
  90570. enumerable: true,
  90571. configurable: true
  90572. });
  90573. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  90574. /**
  90575. * Gets the perf counter used for render time capture
  90576. */
  90577. get: function () {
  90578. return this._renderTime;
  90579. },
  90580. enumerable: true,
  90581. configurable: true
  90582. });
  90583. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  90584. /**
  90585. * Gets the render time capture status
  90586. */
  90587. get: function () {
  90588. return this._captureRenderTime;
  90589. },
  90590. /**
  90591. * Enable or disable the render time capture
  90592. */
  90593. set: function (value) {
  90594. var _this = this;
  90595. if (value === this._captureRenderTime) {
  90596. return;
  90597. }
  90598. this._captureRenderTime = value;
  90599. if (value) {
  90600. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  90601. _this._renderTime.beginMonitoring();
  90602. BABYLON.Tools.StartPerformanceCounter("Main render");
  90603. });
  90604. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  90605. _this._renderTime.endMonitoring(false);
  90606. BABYLON.Tools.EndPerformanceCounter("Main render");
  90607. });
  90608. }
  90609. else {
  90610. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  90611. this._onBeforeDrawPhaseObserver = null;
  90612. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  90613. this._onAfterDrawPhaseObserver = null;
  90614. }
  90615. },
  90616. enumerable: true,
  90617. configurable: true
  90618. });
  90619. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  90620. /**
  90621. * Gets the perf counter used for draw calls
  90622. */
  90623. get: function () {
  90624. return this.scene.getEngine()._drawCalls;
  90625. },
  90626. enumerable: true,
  90627. configurable: true
  90628. });
  90629. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  90630. /**
  90631. * Gets the perf counter used for texture collisions
  90632. */
  90633. get: function () {
  90634. return this.scene.getEngine()._textureCollisions;
  90635. },
  90636. enumerable: true,
  90637. configurable: true
  90638. });
  90639. SceneInstrumentation.prototype.dispose = function () {
  90640. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  90641. this._onAfterRenderObserver = null;
  90642. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  90643. this._onBeforeActiveMeshesEvaluationObserver = null;
  90644. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  90645. this._onAfterActiveMeshesEvaluationObserver = null;
  90646. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  90647. this._onBeforeRenderTargetsRenderObserver = null;
  90648. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  90649. this._onAfterRenderTargetsRenderObserver = null;
  90650. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  90651. this._onBeforeAnimationsObserver = null;
  90652. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  90653. this._onBeforeParticlesRenderingObserver = null;
  90654. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  90655. this._onAfterParticlesRenderingObserver = null;
  90656. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  90657. this._onBeforeSpritesRenderingObserver = null;
  90658. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  90659. this._onAfterSpritesRenderingObserver = null;
  90660. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  90661. this._onBeforeDrawPhaseObserver = null;
  90662. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  90663. this._onAfterDrawPhaseObserver = null;
  90664. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  90665. this._onBeforePhysicsObserver = null;
  90666. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  90667. this._onAfterPhysicsObserver = null;
  90668. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  90669. this._onAfterAnimationsObserver = null;
  90670. this.scene = null;
  90671. };
  90672. return SceneInstrumentation;
  90673. }());
  90674. BABYLON.SceneInstrumentation = SceneInstrumentation;
  90675. })(BABYLON || (BABYLON = {}));
  90676. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  90677. "use strict";
  90678. var BABYLON;
  90679. (function (BABYLON) {
  90680. var _TimeToken = /** @class */ (function () {
  90681. function _TimeToken() {
  90682. this._timeElapsedQueryEnded = false;
  90683. }
  90684. return _TimeToken;
  90685. }());
  90686. BABYLON._TimeToken = _TimeToken;
  90687. })(BABYLON || (BABYLON = {}));
  90688. //# sourceMappingURL=babylon.timeToken.js.map
  90689. "use strict";
  90690. var BABYLON;
  90691. (function (BABYLON) {
  90692. /**
  90693. * Background material defines definition.
  90694. * @ignore Mainly internal Use
  90695. */
  90696. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  90697. __extends(BackgroundMaterialDefines, _super);
  90698. /**
  90699. * Constructor of the defines.
  90700. */
  90701. function BackgroundMaterialDefines() {
  90702. var _this = _super.call(this) || this;
  90703. /**
  90704. * True if the diffuse texture is in use.
  90705. */
  90706. _this.DIFFUSE = false;
  90707. /**
  90708. * The direct UV channel to use.
  90709. */
  90710. _this.DIFFUSEDIRECTUV = 0;
  90711. /**
  90712. * True if the diffuse texture is in gamma space.
  90713. */
  90714. _this.GAMMADIFFUSE = false;
  90715. /**
  90716. * True if the diffuse texture has opacity in the alpha channel.
  90717. */
  90718. _this.DIFFUSEHASALPHA = false;
  90719. /**
  90720. * True if you want the material to fade to transparent at grazing angle.
  90721. */
  90722. _this.OPACITYFRESNEL = false;
  90723. /**
  90724. * True if an extra blur needs to be added in the reflection.
  90725. */
  90726. _this.REFLECTIONBLUR = false;
  90727. /**
  90728. * True if you want the material to fade to reflection at grazing angle.
  90729. */
  90730. _this.REFLECTIONFRESNEL = false;
  90731. /**
  90732. * True if you want the material to falloff as far as you move away from the scene center.
  90733. */
  90734. _this.REFLECTIONFALLOFF = false;
  90735. /**
  90736. * False if the current Webgl implementation does not support the texture lod extension.
  90737. */
  90738. _this.TEXTURELODSUPPORT = false;
  90739. /**
  90740. * True to ensure the data are premultiplied.
  90741. */
  90742. _this.PREMULTIPLYALPHA = false;
  90743. /**
  90744. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  90745. */
  90746. _this.USERGBCOLOR = false;
  90747. /**
  90748. * True to add noise in order to reduce the banding effect.
  90749. */
  90750. _this.NOISE = false;
  90751. /**
  90752. * is the reflection texture in BGR color scheme?
  90753. * Mainly used to solve a bug in ios10 video tag
  90754. */
  90755. _this.REFLECTIONBGR = false;
  90756. _this.IMAGEPROCESSING = false;
  90757. _this.VIGNETTE = false;
  90758. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  90759. _this.VIGNETTEBLENDMODEOPAQUE = false;
  90760. _this.TONEMAPPING = false;
  90761. _this.CONTRAST = false;
  90762. _this.COLORCURVES = false;
  90763. _this.COLORGRADING = false;
  90764. _this.COLORGRADING3D = false;
  90765. _this.SAMPLER3DGREENDEPTH = false;
  90766. _this.SAMPLER3DBGRMAP = false;
  90767. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  90768. _this.EXPOSURE = false;
  90769. // Reflection.
  90770. _this.REFLECTION = false;
  90771. _this.REFLECTIONMAP_3D = false;
  90772. _this.REFLECTIONMAP_SPHERICAL = false;
  90773. _this.REFLECTIONMAP_PLANAR = false;
  90774. _this.REFLECTIONMAP_CUBIC = false;
  90775. _this.REFLECTIONMAP_PROJECTION = false;
  90776. _this.REFLECTIONMAP_SKYBOX = false;
  90777. _this.REFLECTIONMAP_EXPLICIT = false;
  90778. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  90779. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  90780. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  90781. _this.INVERTCUBICMAP = false;
  90782. _this.REFLECTIONMAP_OPPOSITEZ = false;
  90783. _this.LODINREFLECTIONALPHA = false;
  90784. _this.GAMMAREFLECTION = false;
  90785. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  90786. // Default BJS.
  90787. _this.MAINUV1 = false;
  90788. _this.MAINUV2 = false;
  90789. _this.UV1 = false;
  90790. _this.UV2 = false;
  90791. _this.CLIPPLANE = false;
  90792. _this.POINTSIZE = false;
  90793. _this.FOG = false;
  90794. _this.NORMAL = false;
  90795. _this.NUM_BONE_INFLUENCERS = 0;
  90796. _this.BonesPerMesh = 0;
  90797. _this.INSTANCES = false;
  90798. _this.SHADOWFLOAT = false;
  90799. _this.rebuild();
  90800. return _this;
  90801. }
  90802. return BackgroundMaterialDefines;
  90803. }(BABYLON.MaterialDefines));
  90804. /**
  90805. * Background material used to create an efficient environement around your scene.
  90806. */
  90807. var BackgroundMaterial = /** @class */ (function (_super) {
  90808. __extends(BackgroundMaterial, _super);
  90809. /**
  90810. * Instantiates a Background Material in the given scene
  90811. * @param name The friendly name of the material
  90812. * @param scene The scene to add the material to
  90813. */
  90814. function BackgroundMaterial(name, scene) {
  90815. var _this = _super.call(this, name, scene) || this;
  90816. /**
  90817. * Key light Color (multiply against the R channel of the environement texture)
  90818. */
  90819. _this.primaryColor = BABYLON.Color3.White();
  90820. /**
  90821. * Key light Level (allowing HDR output of the background)
  90822. */
  90823. _this.primaryLevel = 1;
  90824. /**
  90825. * Secondary light Color (multiply against the G channel of the environement texture)
  90826. */
  90827. _this.secondaryColor = BABYLON.Color3.Gray();
  90828. /**
  90829. * Secondary light Level (allowing HDR output of the background)
  90830. */
  90831. _this.secondaryLevel = 1;
  90832. /**
  90833. * Tertiary light Color (multiply against the B channel of the environement texture)
  90834. */
  90835. _this.tertiaryColor = BABYLON.Color3.Black();
  90836. /**
  90837. * Tertiary light Level (allowing HDR output of the background)
  90838. */
  90839. _this.tertiaryLevel = 1;
  90840. /**
  90841. * Reflection Texture used in the material.
  90842. * Should be author in a specific way for the best result (refer to the documentation).
  90843. */
  90844. _this.reflectionTexture = null;
  90845. /**
  90846. * Reflection Texture level of blur.
  90847. *
  90848. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  90849. * texture twice.
  90850. */
  90851. _this.reflectionBlur = 0;
  90852. /**
  90853. * Diffuse Texture used in the material.
  90854. * Should be author in a specific way for the best result (refer to the documentation).
  90855. */
  90856. _this.diffuseTexture = null;
  90857. _this._shadowLights = null;
  90858. /**
  90859. * Specify the list of lights casting shadow on the material.
  90860. * All scene shadow lights will be included if null.
  90861. */
  90862. _this.shadowLights = null;
  90863. /**
  90864. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  90865. * soft lighting on the background.
  90866. */
  90867. _this.shadowBlurScale = 1;
  90868. /**
  90869. * Helps adjusting the shadow to a softer level if required.
  90870. * 0 means black shadows and 1 means no shadows.
  90871. */
  90872. _this.shadowLevel = 0;
  90873. /**
  90874. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  90875. * It is usually zero but might be interesting to modify according to your setup.
  90876. */
  90877. _this.sceneCenter = BABYLON.Vector3.Zero();
  90878. /**
  90879. * This helps specifying that the material is falling off to the sky box at grazing angle.
  90880. * This helps ensuring a nice transition when the camera goes under the ground.
  90881. */
  90882. _this.opacityFresnel = true;
  90883. /**
  90884. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  90885. * This helps adding a mirror texture on the ground.
  90886. */
  90887. _this.reflectionFresnel = false;
  90888. /**
  90889. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  90890. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  90891. */
  90892. _this.reflectionFalloffDistance = 0.0;
  90893. /**
  90894. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  90895. */
  90896. _this.reflectionAmount = 1.0;
  90897. /**
  90898. * This specifies the weight of the reflection at grazing angle.
  90899. */
  90900. _this.reflectionReflectance0 = 0.05;
  90901. /**
  90902. * This specifies the weight of the reflection at a perpendicular point of view.
  90903. */
  90904. _this.reflectionReflectance90 = 0.5;
  90905. /**
  90906. * Helps to directly use the maps channels instead of their level.
  90907. */
  90908. _this.useRGBColor = true;
  90909. /**
  90910. * This helps reducing the banding effect that could occur on the background.
  90911. */
  90912. _this.enableNoise = false;
  90913. _this._fovMultiplier = 1.0;
  90914. /**
  90915. * Enable the FOV adjustment feature controlled by fovMultiplier.
  90916. */
  90917. _this.useEquirectangularFOV = false;
  90918. _this._maxSimultaneousLights = 4;
  90919. /**
  90920. * Number of Simultaneous lights allowed on the material.
  90921. */
  90922. _this.maxSimultaneousLights = 4;
  90923. /**
  90924. * Keep track of the image processing observer to allow dispose and replace.
  90925. */
  90926. _this._imageProcessingObserver = null;
  90927. /**
  90928. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  90929. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  90930. */
  90931. _this.switchToBGR = false;
  90932. // Temp values kept as cache in the material.
  90933. _this._renderTargets = new BABYLON.SmartArray(16);
  90934. _this._reflectionControls = BABYLON.Vector4.Zero();
  90935. // Setup the default processing configuration to the scene.
  90936. _this._attachImageProcessingConfiguration(null);
  90937. _this.getRenderTargetTextures = function () {
  90938. _this._renderTargets.reset();
  90939. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  90940. _this._renderTargets.push(_this._diffuseTexture);
  90941. }
  90942. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  90943. _this._renderTargets.push(_this._reflectionTexture);
  90944. }
  90945. return _this._renderTargets;
  90946. };
  90947. return _this;
  90948. }
  90949. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  90950. /**
  90951. * Sets the reflection reflectance fresnel values according to the default standard
  90952. * empirically know to work well :-)
  90953. */
  90954. set: function (value) {
  90955. var reflectionWeight = value;
  90956. if (reflectionWeight < 0.5) {
  90957. reflectionWeight = reflectionWeight * 2.0;
  90958. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  90959. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  90960. }
  90961. else {
  90962. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  90963. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  90964. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  90965. }
  90966. },
  90967. enumerable: true,
  90968. configurable: true
  90969. });
  90970. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  90971. /**
  90972. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  90973. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  90974. * Recommended to be keep at 1.0 except for special cases.
  90975. */
  90976. get: function () {
  90977. return this._fovMultiplier;
  90978. },
  90979. set: function (value) {
  90980. if (isNaN(value)) {
  90981. value = 1.0;
  90982. }
  90983. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  90984. },
  90985. enumerable: true,
  90986. configurable: true
  90987. });
  90988. /**
  90989. * Attaches a new image processing configuration to the PBR Material.
  90990. * @param configuration (if null the scene configuration will be use)
  90991. */
  90992. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  90993. var _this = this;
  90994. if (configuration === this._imageProcessingConfiguration) {
  90995. return;
  90996. }
  90997. // Detaches observer.
  90998. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  90999. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  91000. }
  91001. // Pick the scene configuration if needed.
  91002. if (!configuration) {
  91003. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  91004. }
  91005. else {
  91006. this._imageProcessingConfiguration = configuration;
  91007. }
  91008. // Attaches observer.
  91009. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  91010. _this._markAllSubMeshesAsImageProcessingDirty();
  91011. });
  91012. };
  91013. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  91014. /**
  91015. * Gets the image processing configuration used either in this material.
  91016. */
  91017. get: function () {
  91018. return this._imageProcessingConfiguration;
  91019. },
  91020. /**
  91021. * Sets the Default image processing configuration used either in the this material.
  91022. *
  91023. * If sets to null, the scene one is in use.
  91024. */
  91025. set: function (value) {
  91026. this._attachImageProcessingConfiguration(value);
  91027. // Ensure the effect will be rebuilt.
  91028. this._markAllSubMeshesAsTexturesDirty();
  91029. },
  91030. enumerable: true,
  91031. configurable: true
  91032. });
  91033. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  91034. /**
  91035. * Gets wether the color curves effect is enabled.
  91036. */
  91037. get: function () {
  91038. return this.imageProcessingConfiguration.colorCurvesEnabled;
  91039. },
  91040. /**
  91041. * Sets wether the color curves effect is enabled.
  91042. */
  91043. set: function (value) {
  91044. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  91045. },
  91046. enumerable: true,
  91047. configurable: true
  91048. });
  91049. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  91050. /**
  91051. * Gets wether the color grading effect is enabled.
  91052. */
  91053. get: function () {
  91054. return this.imageProcessingConfiguration.colorGradingEnabled;
  91055. },
  91056. /**
  91057. * Gets wether the color grading effect is enabled.
  91058. */
  91059. set: function (value) {
  91060. this.imageProcessingConfiguration.colorGradingEnabled = value;
  91061. },
  91062. enumerable: true,
  91063. configurable: true
  91064. });
  91065. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  91066. /**
  91067. * Gets wether tonemapping is enabled or not.
  91068. */
  91069. get: function () {
  91070. return this._imageProcessingConfiguration.toneMappingEnabled;
  91071. },
  91072. /**
  91073. * Sets wether tonemapping is enabled or not
  91074. */
  91075. set: function (value) {
  91076. this._imageProcessingConfiguration.toneMappingEnabled = value;
  91077. },
  91078. enumerable: true,
  91079. configurable: true
  91080. });
  91081. ;
  91082. ;
  91083. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  91084. /**
  91085. * The camera exposure used on this material.
  91086. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  91087. * This corresponds to a photographic exposure.
  91088. */
  91089. get: function () {
  91090. return this._imageProcessingConfiguration.exposure;
  91091. },
  91092. /**
  91093. * The camera exposure used on this material.
  91094. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  91095. * This corresponds to a photographic exposure.
  91096. */
  91097. set: function (value) {
  91098. this._imageProcessingConfiguration.exposure = value;
  91099. },
  91100. enumerable: true,
  91101. configurable: true
  91102. });
  91103. ;
  91104. ;
  91105. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  91106. /**
  91107. * Gets The camera contrast used on this material.
  91108. */
  91109. get: function () {
  91110. return this._imageProcessingConfiguration.contrast;
  91111. },
  91112. /**
  91113. * Sets The camera contrast used on this material.
  91114. */
  91115. set: function (value) {
  91116. this._imageProcessingConfiguration.contrast = value;
  91117. },
  91118. enumerable: true,
  91119. configurable: true
  91120. });
  91121. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  91122. /**
  91123. * Gets the Color Grading 2D Lookup Texture.
  91124. */
  91125. get: function () {
  91126. return this._imageProcessingConfiguration.colorGradingTexture;
  91127. },
  91128. /**
  91129. * Sets the Color Grading 2D Lookup Texture.
  91130. */
  91131. set: function (value) {
  91132. this.imageProcessingConfiguration.colorGradingTexture = value;
  91133. },
  91134. enumerable: true,
  91135. configurable: true
  91136. });
  91137. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  91138. /**
  91139. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  91140. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  91141. * 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;
  91142. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  91143. */
  91144. get: function () {
  91145. return this.imageProcessingConfiguration.colorCurves;
  91146. },
  91147. /**
  91148. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  91149. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  91150. * 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;
  91151. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  91152. */
  91153. set: function (value) {
  91154. this.imageProcessingConfiguration.colorCurves = value;
  91155. },
  91156. enumerable: true,
  91157. configurable: true
  91158. });
  91159. /**
  91160. * The entire material has been created in order to prevent overdraw.
  91161. * @returns false
  91162. */
  91163. BackgroundMaterial.prototype.needAlphaTesting = function () {
  91164. return true;
  91165. };
  91166. /**
  91167. * The entire material has been created in order to prevent overdraw.
  91168. * @returns true if blending is enable
  91169. */
  91170. BackgroundMaterial.prototype.needAlphaBlending = function () {
  91171. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  91172. };
  91173. /**
  91174. * Checks wether the material is ready to be rendered for a given mesh.
  91175. * @param mesh The mesh to render
  91176. * @param subMesh The submesh to check against
  91177. * @param useInstances Specify wether or not the material is used with instances
  91178. * @returns true if all the dependencies are ready (Textures, Effects...)
  91179. */
  91180. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  91181. var _this = this;
  91182. if (useInstances === void 0) { useInstances = false; }
  91183. if (subMesh.effect && this.isFrozen) {
  91184. if (this._wasPreviouslyReady) {
  91185. return true;
  91186. }
  91187. }
  91188. if (!subMesh._materialDefines) {
  91189. subMesh._materialDefines = new BackgroundMaterialDefines();
  91190. }
  91191. var scene = this.getScene();
  91192. var defines = subMesh._materialDefines;
  91193. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  91194. if (defines._renderId === scene.getRenderId()) {
  91195. return true;
  91196. }
  91197. }
  91198. var engine = scene.getEngine();
  91199. // Lights
  91200. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  91201. defines._needNormals = true;
  91202. // Textures
  91203. if (defines._areTexturesDirty) {
  91204. defines._needUVs = false;
  91205. if (scene.texturesEnabled) {
  91206. if (scene.getEngine().getCaps().textureLOD) {
  91207. defines.TEXTURELODSUPPORT = true;
  91208. }
  91209. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  91210. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  91211. return false;
  91212. }
  91213. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  91214. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  91215. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  91216. defines.OPACITYFRESNEL = this._opacityFresnel;
  91217. }
  91218. else {
  91219. defines.DIFFUSE = false;
  91220. defines.DIFFUSEHASALPHA = false;
  91221. defines.GAMMADIFFUSE = false;
  91222. defines.OPACITYFRESNEL = false;
  91223. }
  91224. var reflectionTexture = this._reflectionTexture;
  91225. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  91226. if (!reflectionTexture.isReadyOrNotBlocking()) {
  91227. return false;
  91228. }
  91229. defines.REFLECTION = true;
  91230. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  91231. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  91232. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  91233. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  91234. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  91235. defines.REFLECTIONBGR = this.switchToBGR;
  91236. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  91237. defines.INVERTCUBICMAP = true;
  91238. }
  91239. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  91240. switch (reflectionTexture.coordinatesMode) {
  91241. case BABYLON.Texture.CUBIC_MODE:
  91242. case BABYLON.Texture.INVCUBIC_MODE:
  91243. defines.REFLECTIONMAP_CUBIC = true;
  91244. break;
  91245. case BABYLON.Texture.EXPLICIT_MODE:
  91246. defines.REFLECTIONMAP_EXPLICIT = true;
  91247. break;
  91248. case BABYLON.Texture.PLANAR_MODE:
  91249. defines.REFLECTIONMAP_PLANAR = true;
  91250. break;
  91251. case BABYLON.Texture.PROJECTION_MODE:
  91252. defines.REFLECTIONMAP_PROJECTION = true;
  91253. break;
  91254. case BABYLON.Texture.SKYBOX_MODE:
  91255. defines.REFLECTIONMAP_SKYBOX = true;
  91256. break;
  91257. case BABYLON.Texture.SPHERICAL_MODE:
  91258. defines.REFLECTIONMAP_SPHERICAL = true;
  91259. break;
  91260. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  91261. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  91262. break;
  91263. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  91264. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  91265. break;
  91266. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  91267. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  91268. break;
  91269. }
  91270. if (this.reflectionFresnel) {
  91271. defines.REFLECTIONFRESNEL = true;
  91272. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  91273. this._reflectionControls.x = this.reflectionAmount;
  91274. this._reflectionControls.y = this.reflectionReflectance0;
  91275. this._reflectionControls.z = this.reflectionReflectance90;
  91276. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  91277. }
  91278. else {
  91279. defines.REFLECTIONFRESNEL = false;
  91280. defines.REFLECTIONFALLOFF = false;
  91281. }
  91282. }
  91283. else {
  91284. defines.REFLECTION = false;
  91285. defines.REFLECTIONFALLOFF = false;
  91286. defines.REFLECTIONBLUR = false;
  91287. defines.REFLECTIONMAP_3D = false;
  91288. defines.REFLECTIONMAP_SPHERICAL = false;
  91289. defines.REFLECTIONMAP_PLANAR = false;
  91290. defines.REFLECTIONMAP_CUBIC = false;
  91291. defines.REFLECTIONMAP_PROJECTION = false;
  91292. defines.REFLECTIONMAP_SKYBOX = false;
  91293. defines.REFLECTIONMAP_EXPLICIT = false;
  91294. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  91295. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  91296. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  91297. defines.INVERTCUBICMAP = false;
  91298. defines.REFLECTIONMAP_OPPOSITEZ = false;
  91299. defines.LODINREFLECTIONALPHA = false;
  91300. defines.GAMMAREFLECTION = false;
  91301. }
  91302. }
  91303. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  91304. defines.USERGBCOLOR = this._useRGBColor;
  91305. defines.NOISE = this._enableNoise;
  91306. }
  91307. if (defines._areImageProcessingDirty) {
  91308. if (!this._imageProcessingConfiguration.isReady()) {
  91309. return false;
  91310. }
  91311. this._imageProcessingConfiguration.prepareDefines(defines);
  91312. }
  91313. // Misc.
  91314. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  91315. // Values that need to be evaluated on every frame
  91316. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  91317. // Attribs
  91318. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  91319. if (mesh) {
  91320. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  91321. mesh.createNormals(true);
  91322. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  91323. }
  91324. }
  91325. }
  91326. // Get correct effect
  91327. if (defines.isDirty) {
  91328. defines.markAsProcessed();
  91329. scene.resetCachedMaterial();
  91330. // Fallbacks
  91331. var fallbacks = new BABYLON.EffectFallbacks();
  91332. if (defines.FOG) {
  91333. fallbacks.addFallback(0, "FOG");
  91334. }
  91335. if (defines.POINTSIZE) {
  91336. fallbacks.addFallback(1, "POINTSIZE");
  91337. }
  91338. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  91339. if (defines.NUM_BONE_INFLUENCERS > 0) {
  91340. fallbacks.addCPUSkinningFallback(0, mesh);
  91341. }
  91342. //Attributes
  91343. var attribs = [BABYLON.VertexBuffer.PositionKind];
  91344. if (defines.NORMAL) {
  91345. attribs.push(BABYLON.VertexBuffer.NormalKind);
  91346. }
  91347. if (defines.UV1) {
  91348. attribs.push(BABYLON.VertexBuffer.UVKind);
  91349. }
  91350. if (defines.UV2) {
  91351. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91352. }
  91353. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  91354. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  91355. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  91356. "vFogInfos", "vFogColor", "pointSize",
  91357. "vClipPlane", "mBones",
  91358. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  91359. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  91360. "shadowLevel", "alpha",
  91361. "vBackgroundCenter", "vReflectionControl",
  91362. "vDiffuseInfos", "diffuseMatrix",
  91363. ];
  91364. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  91365. var uniformBuffers = ["Material", "Scene"];
  91366. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  91367. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  91368. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  91369. uniformsNames: uniforms,
  91370. uniformBuffersNames: uniformBuffers,
  91371. samplers: samplers,
  91372. defines: defines,
  91373. maxSimultaneousLights: this._maxSimultaneousLights
  91374. });
  91375. var onCompiled = function (effect) {
  91376. if (_this.onCompiled) {
  91377. _this.onCompiled(effect);
  91378. }
  91379. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  91380. };
  91381. var join = defines.toString();
  91382. subMesh.setEffect(scene.getEngine().createEffect("background", {
  91383. attributes: attribs,
  91384. uniformsNames: uniforms,
  91385. uniformBuffersNames: uniformBuffers,
  91386. samplers: samplers,
  91387. defines: join,
  91388. fallbacks: fallbacks,
  91389. onCompiled: onCompiled,
  91390. onError: this.onError,
  91391. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  91392. }, engine), defines);
  91393. this.buildUniformLayout();
  91394. }
  91395. if (!subMesh.effect || !subMesh.effect.isReady()) {
  91396. return false;
  91397. }
  91398. defines._renderId = scene.getRenderId();
  91399. this._wasPreviouslyReady = true;
  91400. return true;
  91401. };
  91402. /**
  91403. * Build the uniform buffer used in the material.
  91404. */
  91405. BackgroundMaterial.prototype.buildUniformLayout = function () {
  91406. // Order is important !
  91407. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  91408. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  91409. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  91410. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  91411. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  91412. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  91413. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  91414. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  91415. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  91416. this._uniformBuffer.addUniform("pointSize", 1);
  91417. this._uniformBuffer.addUniform("shadowLevel", 1);
  91418. this._uniformBuffer.addUniform("alpha", 1);
  91419. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  91420. this._uniformBuffer.addUniform("vReflectionControl", 4);
  91421. this._uniformBuffer.create();
  91422. };
  91423. /**
  91424. * Unbind the material.
  91425. */
  91426. BackgroundMaterial.prototype.unbind = function () {
  91427. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  91428. this._uniformBuffer.setTexture("diffuseSampler", null);
  91429. }
  91430. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  91431. this._uniformBuffer.setTexture("reflectionSampler", null);
  91432. }
  91433. _super.prototype.unbind.call(this);
  91434. };
  91435. /**
  91436. * Bind only the world matrix to the material.
  91437. * @param world The world matrix to bind.
  91438. */
  91439. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  91440. this._activeEffect.setMatrix("world", world);
  91441. };
  91442. /**
  91443. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  91444. * @param world The world matrix to bind.
  91445. * @param subMesh The submesh to bind for.
  91446. */
  91447. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  91448. var scene = this.getScene();
  91449. var defines = subMesh._materialDefines;
  91450. if (!defines) {
  91451. return;
  91452. }
  91453. var effect = subMesh.effect;
  91454. if (!effect) {
  91455. return;
  91456. }
  91457. this._activeEffect = effect;
  91458. // Matrices
  91459. this.bindOnlyWorldMatrix(world);
  91460. // Bones
  91461. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  91462. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  91463. if (mustRebind) {
  91464. this._uniformBuffer.bindToEffect(effect, "Material");
  91465. this.bindViewProjection(effect);
  91466. var reflectionTexture = this._reflectionTexture;
  91467. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  91468. // Texture uniforms
  91469. if (scene.texturesEnabled) {
  91470. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  91471. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  91472. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  91473. }
  91474. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  91475. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  91476. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  91477. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  91478. }
  91479. }
  91480. if (this.shadowLevel > 0) {
  91481. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  91482. }
  91483. this._uniformBuffer.updateFloat("alpha", this.alpha);
  91484. // Point size
  91485. if (this.pointsCloud) {
  91486. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  91487. }
  91488. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  91489. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  91490. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  91491. }
  91492. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  91493. // Textures
  91494. if (scene.texturesEnabled) {
  91495. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  91496. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  91497. }
  91498. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  91499. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  91500. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  91501. }
  91502. else if (!defines.REFLECTIONBLUR) {
  91503. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  91504. }
  91505. else {
  91506. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  91507. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  91508. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  91509. }
  91510. if (defines.REFLECTIONFRESNEL) {
  91511. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  91512. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  91513. }
  91514. }
  91515. }
  91516. // Clip plane
  91517. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  91518. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  91519. }
  91520. if (mustRebind || !this.isFrozen) {
  91521. if (scene.lightsEnabled) {
  91522. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  91523. }
  91524. // View
  91525. this.bindView(effect);
  91526. // Fog
  91527. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  91528. // image processing
  91529. this._imageProcessingConfiguration.bind(this._activeEffect);
  91530. }
  91531. this._uniformBuffer.update();
  91532. this._afterBind(mesh);
  91533. };
  91534. /**
  91535. * Dispose the material.
  91536. * @param forceDisposeEffect Force disposal of the associated effect.
  91537. * @param forceDisposeTextures Force disposal of the associated textures.
  91538. */
  91539. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  91540. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  91541. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  91542. if (forceDisposeTextures) {
  91543. if (this.diffuseTexture) {
  91544. this.diffuseTexture.dispose();
  91545. }
  91546. if (this.reflectionTexture) {
  91547. this.reflectionTexture.dispose();
  91548. }
  91549. }
  91550. this._renderTargets.dispose();
  91551. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  91552. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  91553. }
  91554. _super.prototype.dispose.call(this, forceDisposeEffect);
  91555. };
  91556. /**
  91557. * Clones the material.
  91558. * @param name The cloned name.
  91559. * @returns The cloned material.
  91560. */
  91561. BackgroundMaterial.prototype.clone = function (name) {
  91562. var _this = this;
  91563. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  91564. };
  91565. /**
  91566. * Serializes the current material to its JSON representation.
  91567. * @returns The JSON representation.
  91568. */
  91569. BackgroundMaterial.prototype.serialize = function () {
  91570. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  91571. serializationObject.customType = "BABYLON.BackgroundMaterial";
  91572. return serializationObject;
  91573. };
  91574. /**
  91575. * Gets the class name of the material
  91576. * @returns "BackgroundMaterial"
  91577. */
  91578. BackgroundMaterial.prototype.getClassName = function () {
  91579. return "BackgroundMaterial";
  91580. };
  91581. /**
  91582. * Parse a JSON input to create back a background material.
  91583. * @param source The JSON data to parse
  91584. * @param scene The scene to create the parsed material in
  91585. * @param rootUrl The root url of the assets the material depends upon
  91586. * @returns the instantiated BackgroundMaterial.
  91587. */
  91588. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  91589. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  91590. };
  91591. /**
  91592. * Standard reflectance value at parallel view angle.
  91593. */
  91594. BackgroundMaterial.StandardReflectance0 = 0.05;
  91595. /**
  91596. * Standard reflectance value at grazing angle.
  91597. */
  91598. BackgroundMaterial.StandardReflectance90 = 0.5;
  91599. __decorate([
  91600. BABYLON.serializeAsColor3()
  91601. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  91602. __decorate([
  91603. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91604. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  91605. __decorate([
  91606. BABYLON.serialize()
  91607. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  91608. __decorate([
  91609. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91610. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  91611. __decorate([
  91612. BABYLON.serializeAsColor3()
  91613. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  91614. __decorate([
  91615. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91616. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  91617. __decorate([
  91618. BABYLON.serialize()
  91619. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  91620. __decorate([
  91621. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91622. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  91623. __decorate([
  91624. BABYLON.serializeAsColor3()
  91625. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  91626. __decorate([
  91627. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91628. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  91629. __decorate([
  91630. BABYLON.serialize()
  91631. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  91632. __decorate([
  91633. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91634. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  91635. __decorate([
  91636. BABYLON.serializeAsTexture()
  91637. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  91638. __decorate([
  91639. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91640. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  91641. __decorate([
  91642. BABYLON.serialize()
  91643. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  91644. __decorate([
  91645. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91646. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  91647. __decorate([
  91648. BABYLON.serializeAsTexture()
  91649. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  91650. __decorate([
  91651. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91652. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  91653. __decorate([
  91654. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91655. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  91656. __decorate([
  91657. BABYLON.serialize()
  91658. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  91659. __decorate([
  91660. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91661. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  91662. __decorate([
  91663. BABYLON.serialize()
  91664. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  91665. __decorate([
  91666. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91667. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  91668. __decorate([
  91669. BABYLON.serializeAsVector3()
  91670. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  91671. __decorate([
  91672. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91673. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  91674. __decorate([
  91675. BABYLON.serialize()
  91676. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  91677. __decorate([
  91678. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91679. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  91680. __decorate([
  91681. BABYLON.serialize()
  91682. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  91683. __decorate([
  91684. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91685. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  91686. __decorate([
  91687. BABYLON.serialize()
  91688. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  91689. __decorate([
  91690. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91691. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  91692. __decorate([
  91693. BABYLON.serialize()
  91694. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  91695. __decorate([
  91696. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91697. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  91698. __decorate([
  91699. BABYLON.serialize()
  91700. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  91701. __decorate([
  91702. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91703. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  91704. __decorate([
  91705. BABYLON.serialize()
  91706. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  91707. __decorate([
  91708. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91709. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  91710. __decorate([
  91711. BABYLON.serialize()
  91712. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  91713. __decorate([
  91714. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91715. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  91716. __decorate([
  91717. BABYLON.serialize()
  91718. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  91719. __decorate([
  91720. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91721. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  91722. __decorate([
  91723. BABYLON.serialize()
  91724. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  91725. __decorate([
  91726. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91727. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  91728. __decorate([
  91729. BABYLON.serializeAsImageProcessingConfiguration()
  91730. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  91731. return BackgroundMaterial;
  91732. }(BABYLON.PushMaterial));
  91733. BABYLON.BackgroundMaterial = BackgroundMaterial;
  91734. })(BABYLON || (BABYLON = {}));
  91735. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  91736. "use strict";
  91737. var __assign = (this && this.__assign) || Object.assign || function(t) {
  91738. for (var s, i = 1, n = arguments.length; i < n; i++) {
  91739. s = arguments[i];
  91740. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  91741. t[p] = s[p];
  91742. }
  91743. return t;
  91744. };
  91745. var BABYLON;
  91746. (function (BABYLON) {
  91747. /**
  91748. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  91749. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  91750. * It also helps with the default setup of your imageProcessing configuration.
  91751. */
  91752. var EnvironmentHelper = /** @class */ (function () {
  91753. /**
  91754. * constructor
  91755. * @param options
  91756. * @param scene The scene to add the material to
  91757. */
  91758. function EnvironmentHelper(options, scene) {
  91759. var _this = this;
  91760. this._errorHandler = function (message, exception) {
  91761. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  91762. };
  91763. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  91764. this._scene = scene;
  91765. this.onErrorObservable = new BABYLON.Observable();
  91766. this._setupBackground();
  91767. this._setupImageProcessing();
  91768. }
  91769. /**
  91770. * Creates the default options for the helper.
  91771. */
  91772. EnvironmentHelper._getDefaultOptions = function () {
  91773. return {
  91774. createGround: true,
  91775. groundSize: 15,
  91776. groundTexture: this._groundTextureCDNUrl,
  91777. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  91778. groundOpacity: 0.9,
  91779. enableGroundShadow: true,
  91780. groundShadowLevel: 0.5,
  91781. enableGroundMirror: false,
  91782. groundMirrorSizeRatio: 0.3,
  91783. groundMirrorBlurKernel: 64,
  91784. groundMirrorAmount: 1,
  91785. groundMirrorFresnelWeight: 1,
  91786. groundMirrorFallOffDistance: 0,
  91787. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  91788. groundYBias: 0.00001,
  91789. createSkybox: true,
  91790. skyboxSize: 20,
  91791. skyboxTexture: this._skyboxTextureCDNUrl,
  91792. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  91793. backgroundYRotation: 0,
  91794. sizeAuto: true,
  91795. rootPosition: BABYLON.Vector3.Zero(),
  91796. setupImageProcessing: true,
  91797. environmentTexture: this._environmentTextureCDNUrl,
  91798. cameraExposure: 0.8,
  91799. cameraContrast: 1.2,
  91800. toneMappingEnabled: true,
  91801. };
  91802. };
  91803. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  91804. /**
  91805. * Gets the root mesh created by the helper.
  91806. */
  91807. get: function () {
  91808. return this._rootMesh;
  91809. },
  91810. enumerable: true,
  91811. configurable: true
  91812. });
  91813. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  91814. /**
  91815. * Gets the skybox created by the helper.
  91816. */
  91817. get: function () {
  91818. return this._skybox;
  91819. },
  91820. enumerable: true,
  91821. configurable: true
  91822. });
  91823. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  91824. /**
  91825. * Gets the skybox texture created by the helper.
  91826. */
  91827. get: function () {
  91828. return this._skyboxTexture;
  91829. },
  91830. enumerable: true,
  91831. configurable: true
  91832. });
  91833. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  91834. /**
  91835. * Gets the skybox material created by the helper.
  91836. */
  91837. get: function () {
  91838. return this._skyboxMaterial;
  91839. },
  91840. enumerable: true,
  91841. configurable: true
  91842. });
  91843. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  91844. /**
  91845. * Gets the ground mesh created by the helper.
  91846. */
  91847. get: function () {
  91848. return this._ground;
  91849. },
  91850. enumerable: true,
  91851. configurable: true
  91852. });
  91853. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  91854. /**
  91855. * Gets the ground texture created by the helper.
  91856. */
  91857. get: function () {
  91858. return this._groundTexture;
  91859. },
  91860. enumerable: true,
  91861. configurable: true
  91862. });
  91863. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  91864. /**
  91865. * Gets the ground mirror created by the helper.
  91866. */
  91867. get: function () {
  91868. return this._groundMirror;
  91869. },
  91870. enumerable: true,
  91871. configurable: true
  91872. });
  91873. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  91874. /**
  91875. * Gets the ground mirror render list to helps pushing the meshes
  91876. * you wish in the ground reflection.
  91877. */
  91878. get: function () {
  91879. if (this._groundMirror) {
  91880. return this._groundMirror.renderList;
  91881. }
  91882. return null;
  91883. },
  91884. enumerable: true,
  91885. configurable: true
  91886. });
  91887. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  91888. /**
  91889. * Gets the ground material created by the helper.
  91890. */
  91891. get: function () {
  91892. return this._groundMaterial;
  91893. },
  91894. enumerable: true,
  91895. configurable: true
  91896. });
  91897. /**
  91898. * Updates the background according to the new options
  91899. * @param options
  91900. */
  91901. EnvironmentHelper.prototype.updateOptions = function (options) {
  91902. var newOptions = __assign({}, this._options, options);
  91903. if (this._ground && !newOptions.createGround) {
  91904. this._ground.dispose();
  91905. this._ground = null;
  91906. }
  91907. if (this._groundMaterial && !newOptions.createGround) {
  91908. this._groundMaterial.dispose();
  91909. this._groundMaterial = null;
  91910. }
  91911. if (this._groundTexture) {
  91912. if (this._options.groundTexture != newOptions.groundTexture) {
  91913. this._groundTexture.dispose();
  91914. this._groundTexture = null;
  91915. }
  91916. }
  91917. if (this._skybox && !newOptions.createSkybox) {
  91918. this._skybox.dispose();
  91919. this._skybox = null;
  91920. }
  91921. if (this._skyboxMaterial && !newOptions.createSkybox) {
  91922. this._skyboxMaterial.dispose();
  91923. this._skyboxMaterial = null;
  91924. }
  91925. if (this._skyboxTexture) {
  91926. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  91927. this._skyboxTexture.dispose();
  91928. this._skyboxTexture = null;
  91929. }
  91930. }
  91931. if (this._groundMirror && !newOptions.enableGroundMirror) {
  91932. this._groundMirror.dispose();
  91933. this._groundMirror = null;
  91934. }
  91935. if (this._scene.environmentTexture) {
  91936. if (this._options.environmentTexture != newOptions.environmentTexture) {
  91937. this._scene.environmentTexture.dispose();
  91938. }
  91939. }
  91940. this._options = newOptions;
  91941. this._setupBackground();
  91942. this._setupImageProcessing();
  91943. };
  91944. /**
  91945. * Sets the primary color of all the available elements.
  91946. * @param color
  91947. */
  91948. EnvironmentHelper.prototype.setMainColor = function (color) {
  91949. if (this.groundMaterial) {
  91950. this.groundMaterial.primaryColor = color;
  91951. }
  91952. if (this.skyboxMaterial) {
  91953. this.skyboxMaterial.primaryColor = color;
  91954. }
  91955. if (this.groundMirror) {
  91956. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  91957. }
  91958. };
  91959. /**
  91960. * Setup the image processing according to the specified options.
  91961. */
  91962. EnvironmentHelper.prototype._setupImageProcessing = function () {
  91963. if (this._options.setupImageProcessing) {
  91964. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  91965. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  91966. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  91967. this._setupEnvironmentTexture();
  91968. }
  91969. };
  91970. /**
  91971. * Setup the environment texture according to the specified options.
  91972. */
  91973. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  91974. if (this._scene.environmentTexture) {
  91975. return;
  91976. }
  91977. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  91978. this._scene.environmentTexture = this._options.environmentTexture;
  91979. return;
  91980. }
  91981. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  91982. this._scene.environmentTexture = environmentTexture;
  91983. };
  91984. /**
  91985. * Setup the background according to the specified options.
  91986. */
  91987. EnvironmentHelper.prototype._setupBackground = function () {
  91988. if (!this._rootMesh) {
  91989. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  91990. }
  91991. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  91992. var sceneSize = this._getSceneSize();
  91993. if (this._options.createGround) {
  91994. this._setupGround(sceneSize);
  91995. this._setupGroundMaterial();
  91996. this._setupGroundDiffuseTexture();
  91997. if (this._options.enableGroundMirror) {
  91998. this._setupGroundMirrorTexture(sceneSize);
  91999. }
  92000. this._setupMirrorInGroundMaterial();
  92001. }
  92002. if (this._options.createSkybox) {
  92003. this._setupSkybox(sceneSize);
  92004. this._setupSkyboxMaterial();
  92005. this._setupSkyboxReflectionTexture();
  92006. }
  92007. this._rootMesh.position.x = sceneSize.rootPosition.x;
  92008. this._rootMesh.position.z = sceneSize.rootPosition.z;
  92009. this._rootMesh.position.y = sceneSize.rootPosition.y;
  92010. };
  92011. /**
  92012. * Get the scene sizes according to the setup.
  92013. */
  92014. EnvironmentHelper.prototype._getSceneSize = function () {
  92015. var _this = this;
  92016. var groundSize = this._options.groundSize;
  92017. var skyboxSize = this._options.skyboxSize;
  92018. var rootPosition = this._options.rootPosition;
  92019. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  92020. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  92021. }
  92022. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  92023. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  92024. });
  92025. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  92026. if (this._options.sizeAuto) {
  92027. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  92028. this._scene.activeCamera.upperRadiusLimit) {
  92029. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  92030. skyboxSize = groundSize;
  92031. }
  92032. var sceneDiagonalLenght = sceneDiagonal.length();
  92033. if (sceneDiagonalLenght > groundSize) {
  92034. groundSize = sceneDiagonalLenght * 2;
  92035. skyboxSize = groundSize;
  92036. }
  92037. // 10 % bigger.
  92038. groundSize *= 1.1;
  92039. skyboxSize *= 1.5;
  92040. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  92041. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  92042. }
  92043. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  92044. };
  92045. /**
  92046. * Setup the ground according to the specified options.
  92047. */
  92048. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  92049. var _this = this;
  92050. if (!this._ground) {
  92051. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  92052. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  92053. this._ground.parent = this._rootMesh;
  92054. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  92055. }
  92056. this._ground.receiveShadows = this._options.enableGroundShadow;
  92057. };
  92058. /**
  92059. * Setup the ground material according to the specified options.
  92060. */
  92061. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  92062. if (!this._groundMaterial) {
  92063. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  92064. }
  92065. this._groundMaterial.alpha = this._options.groundOpacity;
  92066. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  92067. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  92068. this._groundMaterial.primaryLevel = 1;
  92069. this._groundMaterial.primaryColor = this._options.groundColor;
  92070. this._groundMaterial.secondaryLevel = 0;
  92071. this._groundMaterial.tertiaryLevel = 0;
  92072. this._groundMaterial.useRGBColor = false;
  92073. this._groundMaterial.enableNoise = true;
  92074. if (this._ground) {
  92075. this._ground.material = this._groundMaterial;
  92076. }
  92077. };
  92078. /**
  92079. * Setup the ground diffuse texture according to the specified options.
  92080. */
  92081. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  92082. if (!this._groundMaterial) {
  92083. return;
  92084. }
  92085. if (this._groundTexture) {
  92086. return;
  92087. }
  92088. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  92089. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  92090. return;
  92091. }
  92092. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  92093. diffuseTexture.gammaSpace = false;
  92094. diffuseTexture.hasAlpha = true;
  92095. this._groundMaterial.diffuseTexture = diffuseTexture;
  92096. };
  92097. /**
  92098. * Setup the ground mirror texture according to the specified options.
  92099. */
  92100. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  92101. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92102. if (!this._groundMirror) {
  92103. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  92104. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  92105. this._groundMirror.anisotropicFilteringLevel = 1;
  92106. this._groundMirror.wrapU = wrapping;
  92107. this._groundMirror.wrapV = wrapping;
  92108. this._groundMirror.gammaSpace = false;
  92109. if (this._groundMirror.renderList) {
  92110. for (var i = 0; i < this._scene.meshes.length; i++) {
  92111. var mesh = this._scene.meshes[i];
  92112. if (mesh !== this._ground &&
  92113. mesh !== this._skybox &&
  92114. mesh !== this._rootMesh) {
  92115. this._groundMirror.renderList.push(mesh);
  92116. }
  92117. }
  92118. }
  92119. }
  92120. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  92121. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  92122. };
  92123. /**
  92124. * Setup the ground to receive the mirror texture.
  92125. */
  92126. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  92127. if (this._groundMaterial) {
  92128. this._groundMaterial.reflectionTexture = this._groundMirror;
  92129. this._groundMaterial.reflectionFresnel = true;
  92130. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  92131. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  92132. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  92133. }
  92134. };
  92135. /**
  92136. * Setup the skybox according to the specified options.
  92137. */
  92138. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  92139. var _this = this;
  92140. if (!this._skybox) {
  92141. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  92142. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  92143. }
  92144. this._skybox.parent = this._rootMesh;
  92145. };
  92146. /**
  92147. * Setup the skybox material according to the specified options.
  92148. */
  92149. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  92150. if (!this._skybox) {
  92151. return;
  92152. }
  92153. if (!this._skyboxMaterial) {
  92154. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  92155. }
  92156. this._skyboxMaterial.useRGBColor = false;
  92157. this._skyboxMaterial.primaryLevel = 1;
  92158. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  92159. this._skyboxMaterial.secondaryLevel = 0;
  92160. this._skyboxMaterial.tertiaryLevel = 0;
  92161. this._skyboxMaterial.enableNoise = true;
  92162. this._skybox.material = this._skyboxMaterial;
  92163. };
  92164. /**
  92165. * Setup the skybox reflection texture according to the specified options.
  92166. */
  92167. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  92168. if (!this._skyboxMaterial) {
  92169. return;
  92170. }
  92171. if (this._skyboxTexture) {
  92172. return;
  92173. }
  92174. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  92175. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  92176. return;
  92177. }
  92178. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  92179. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  92180. this._skyboxTexture.gammaSpace = false;
  92181. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  92182. };
  92183. /**
  92184. * Dispose all the elements created by the Helper.
  92185. */
  92186. EnvironmentHelper.prototype.dispose = function () {
  92187. if (this._groundMaterial) {
  92188. this._groundMaterial.dispose(true, true);
  92189. }
  92190. if (this._skyboxMaterial) {
  92191. this._skyboxMaterial.dispose(true, true);
  92192. }
  92193. this._rootMesh.dispose(false);
  92194. };
  92195. /**
  92196. * Default ground texture URL.
  92197. */
  92198. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  92199. /**
  92200. * Default skybox texture URL.
  92201. */
  92202. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  92203. /**
  92204. * Default environment texture URL.
  92205. */
  92206. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  92207. return EnvironmentHelper;
  92208. }());
  92209. BABYLON.EnvironmentHelper = EnvironmentHelper;
  92210. })(BABYLON || (BABYLON = {}));
  92211. //# sourceMappingURL=babylon.environmentHelper.js.map
  92212. "use strict";
  92213. var BABYLON;
  92214. (function (BABYLON) {
  92215. /**
  92216. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  92217. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  92218. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  92219. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  92220. */
  92221. var VideoDome = /** @class */ (function (_super) {
  92222. __extends(VideoDome, _super);
  92223. /**
  92224. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  92225. * @param name Element's name, child elements will append suffixes for their own names.
  92226. * @param urlsOrVideo
  92227. * @param options An object containing optional or exposed sub element properties:
  92228. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  92229. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  92230. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  92231. * @param options **loop=true** Automatically loop video on end.
  92232. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  92233. */
  92234. function VideoDome(name, urlsOrVideo, options, scene) {
  92235. var _this = _super.call(this, name, scene) || this;
  92236. // set defaults and manage values
  92237. name = name || "videoDome";
  92238. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  92239. options.clickToPlay = Boolean(options.clickToPlay);
  92240. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  92241. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  92242. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  92243. // create
  92244. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  92245. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  92246. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  92247. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  92248. flat: false,
  92249. radius: options.size,
  92250. subdivisions: options.resolution,
  92251. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  92252. }, scene);
  92253. // configure material
  92254. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  92255. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  92256. material.reflectionTexture = _this._videoTexture;
  92257. material.useEquirectangularFOV = true;
  92258. material.fovMultiplier = 1.0;
  92259. // configure mesh
  92260. _this._mesh.material = material;
  92261. _this._mesh.parent = _this;
  92262. // optional configuration
  92263. if (options.clickToPlay) {
  92264. scene.onPointerUp = function () {
  92265. _this._videoTexture.video.play();
  92266. };
  92267. }
  92268. return _this;
  92269. }
  92270. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  92271. /**
  92272. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  92273. * Also see the options.resolution property.
  92274. */
  92275. get: function () {
  92276. return this._material.fovMultiplier;
  92277. },
  92278. set: function (value) {
  92279. this._material.fovMultiplier = value;
  92280. },
  92281. enumerable: true,
  92282. configurable: true
  92283. });
  92284. /**
  92285. * Releases resources associated with this node.
  92286. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  92287. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  92288. */
  92289. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  92290. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  92291. this._videoTexture.dispose();
  92292. this._mesh.dispose();
  92293. this._material.dispose();
  92294. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  92295. };
  92296. return VideoDome;
  92297. }(BABYLON.Node));
  92298. BABYLON.VideoDome = VideoDome;
  92299. })(BABYLON || (BABYLON = {}));
  92300. //# sourceMappingURL=babylon.videoDome.js.map
  92301. 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\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<0.4)\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)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\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*vRefractionInfos.x;\n#endif\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*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\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*vReflectionInfos.x;\n#endif\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)\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#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\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform vec4 colorDead;\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin float size;\nin vec4 color;\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\nvoid main() {\nvUV=uv;\nfloat ratio=age/life;\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+vec4(offset*size,0.,0.));\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform vec3 generalRandoms;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform float radius;\nuniform float angle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin float size;\nin vec4 color;\nin vec3 direction;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\noutColor=vec4(0.,0.,0.,0.);\noutSize=0.;\noutDirection=direction;\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(generalRandoms.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n\noutColor=color1+(color2-color1)*randoms.b;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=PI*randoms2.y;\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius*randoms2.z)*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (angle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(generalRandoms.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\noutDirection=(emitterWM*vec4(direction*power,0.)).xyz;\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction+gravity*timeDelta;\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\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}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\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}\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{\n#ifdef DOF\nfloat sumOfWeights=0.0; \nfloat sampleDepth=0.0;\nfloat factor=0.0;\nfloat centerSampleDepth=sampleDistance(sampleCenter);\n#endif\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\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\n\nif(sumOfWeights == 0.0){\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\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{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(textureSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\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;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn (cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \n}\nvoid main(void)\n{\nfloat pixelDistance=sampleDistance(vUV);\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,texture2D(depthSampler,vUV).r,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n"};
  92302. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\n#ifdef PBR\ntextureColor=toLinearSpace(textureColor);\n#endif\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,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,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,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)\n{\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 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\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,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);\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,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);\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,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);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","kernelBlurFragment":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\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\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\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;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\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 vSecondaryColor;\nuniform vec4 vTertiaryColor;\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};"};
  92303. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  92304. globalObject["BABYLON"] = BABYLON;
  92305. //backwards compatibility
  92306. if(typeof earcut !== 'undefined') {
  92307. globalObject["Earcut"] = {
  92308. earcut: earcut
  92309. };
  92310. }
  92311. return BABYLON;
  92312. });
  92313. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(19)))
  92314. /***/ }),
  92315. /* 1 */
  92316. /***/ (function(module, exports, __webpack_require__) {
  92317. "use strict";
  92318. Object.defineProperty(exports, "__esModule", { value: true });
  92319. var babylonjs_1 = __webpack_require__(0);
  92320. var helper_1 = __webpack_require__(3);
  92321. var HTMLMapper = (function () {
  92322. function HTMLMapper() {
  92323. }
  92324. HTMLMapper.prototype.map = function (element) {
  92325. var config = {};
  92326. var _loop_1 = function (attrIdx) {
  92327. var attr = element.attributes.item(attrIdx);
  92328. var split = attr.nodeName.split('.');
  92329. split.reduce(function (currentConfig, key, idx) {
  92330. var camelKey = helper_1.kebabToCamel(key);
  92331. if (idx === split.length - 1) {
  92332. var val = attr.nodeValue;
  92333. if (val === "true") {
  92334. val = true;
  92335. }
  92336. else if (val === "false") {
  92337. val = false;
  92338. }
  92339. else {
  92340. var isnum = /^\d+$/.test(val);
  92341. if (isnum) {
  92342. var number = parseFloat(val);
  92343. if (!isNaN(number)) {
  92344. val = number;
  92345. }
  92346. }
  92347. }
  92348. currentConfig[camelKey] = val;
  92349. }
  92350. else {
  92351. currentConfig[camelKey] = currentConfig[camelKey] || {};
  92352. }
  92353. return currentConfig[camelKey];
  92354. }, config);
  92355. };
  92356. for (var attrIdx = 0; attrIdx < element.attributes.length; ++attrIdx) {
  92357. _loop_1(attrIdx);
  92358. }
  92359. return config;
  92360. };
  92361. return HTMLMapper;
  92362. }());
  92363. var JSONMapper = (function () {
  92364. function JSONMapper() {
  92365. }
  92366. JSONMapper.prototype.map = function (rawSource) {
  92367. return JSON.parse(rawSource);
  92368. };
  92369. return JSONMapper;
  92370. }());
  92371. var DOMMapper = (function () {
  92372. function DOMMapper() {
  92373. }
  92374. DOMMapper.prototype.map = function (baseElement) {
  92375. var htmlMapper = new HTMLMapper();
  92376. var config = htmlMapper.map(baseElement);
  92377. var traverseChildren = function (element, partConfig) {
  92378. var children = element.children;
  92379. if (children.length) {
  92380. for (var i = 0; i < children.length; ++i) {
  92381. var item = children.item(i);
  92382. var configMapped = htmlMapper.map(item);
  92383. var key = helper_1.kebabToCamel(item.nodeName.toLowerCase());
  92384. if (item.attributes.getNamedItem('array') && item.attributes.getNamedItem('array').nodeValue === 'true') {
  92385. partConfig[key] = [];
  92386. }
  92387. else {
  92388. if (element.attributes.getNamedItem('array') && element.attributes.getNamedItem('array').nodeValue === 'true') {
  92389. partConfig.push(configMapped);
  92390. }
  92391. else if (partConfig[key]) {
  92392. element.setAttribute('array', 'true');
  92393. var oldItem = partConfig[key];
  92394. partConfig = [oldItem, configMapped];
  92395. }
  92396. else {
  92397. partConfig[key] = configMapped;
  92398. }
  92399. }
  92400. traverseChildren(item, partConfig[key] || configMapped);
  92401. }
  92402. }
  92403. return partConfig;
  92404. };
  92405. traverseChildren(baseElement, config);
  92406. return config;
  92407. };
  92408. return DOMMapper;
  92409. }());
  92410. var MapperManager = (function () {
  92411. function MapperManager() {
  92412. this._mappers = {
  92413. "html": new HTMLMapper(),
  92414. "json": new JSONMapper(),
  92415. "dom": new DOMMapper()
  92416. };
  92417. }
  92418. MapperManager.prototype.getMapper = function (type) {
  92419. if (!this._mappers[type]) {
  92420. babylonjs_1.Tools.Error("No mapper defined for " + type);
  92421. }
  92422. return this._mappers[type] || this._mappers[MapperManager.DefaultMapper];
  92423. };
  92424. MapperManager.prototype.registerMapper = function (type, mapper) {
  92425. this._mappers[type] = mapper;
  92426. };
  92427. MapperManager.prototype.dispose = function () {
  92428. this._mappers = {};
  92429. };
  92430. MapperManager.DefaultMapper = 'json';
  92431. return MapperManager;
  92432. }());
  92433. exports.MapperManager = MapperManager;
  92434. exports.mapperManager = new MapperManager();
  92435. /***/ }),
  92436. /* 2 */
  92437. /***/ (function(module, exports, __webpack_require__) {
  92438. (function (global, factory) {
  92439. true ? module.exports = factory() :
  92440. typeof define === 'function' && define.amd ? define(factory) :
  92441. (global.deepmerge = factory());
  92442. }(this, (function () { 'use strict';
  92443. var isMergeableObject = function isMergeableObject(value) {
  92444. return isNonNullObject(value)
  92445. && !isSpecial(value)
  92446. };
  92447. function isNonNullObject(value) {
  92448. return !!value && typeof value === 'object'
  92449. }
  92450. function isSpecial(value) {
  92451. var stringValue = Object.prototype.toString.call(value);
  92452. return stringValue === '[object RegExp]'
  92453. || stringValue === '[object Date]'
  92454. || isReactElement(value)
  92455. }
  92456. // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
  92457. var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
  92458. var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
  92459. function isReactElement(value) {
  92460. return value.$$typeof === REACT_ELEMENT_TYPE
  92461. }
  92462. function emptyTarget(val) {
  92463. return Array.isArray(val) ? [] : {}
  92464. }
  92465. function cloneUnlessOtherwiseSpecified(value, optionsArgument) {
  92466. var clone = !optionsArgument || optionsArgument.clone !== false;
  92467. return (clone && isMergeableObject(value))
  92468. ? deepmerge(emptyTarget(value), value, optionsArgument)
  92469. : value
  92470. }
  92471. function defaultArrayMerge(target, source, optionsArgument) {
  92472. return target.concat(source).map(function(element) {
  92473. return cloneUnlessOtherwiseSpecified(element, optionsArgument)
  92474. })
  92475. }
  92476. function mergeObject(target, source, optionsArgument) {
  92477. var destination = {};
  92478. if (isMergeableObject(target)) {
  92479. Object.keys(target).forEach(function(key) {
  92480. destination[key] = cloneUnlessOtherwiseSpecified(target[key], optionsArgument);
  92481. });
  92482. }
  92483. Object.keys(source).forEach(function(key) {
  92484. if (!isMergeableObject(source[key]) || !target[key]) {
  92485. destination[key] = cloneUnlessOtherwiseSpecified(source[key], optionsArgument);
  92486. } else {
  92487. destination[key] = deepmerge(target[key], source[key], optionsArgument);
  92488. }
  92489. });
  92490. return destination
  92491. }
  92492. function deepmerge(target, source, optionsArgument) {
  92493. var sourceIsArray = Array.isArray(source);
  92494. var targetIsArray = Array.isArray(target);
  92495. var options = optionsArgument || { arrayMerge: defaultArrayMerge };
  92496. var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
  92497. if (!sourceAndTargetTypesMatch) {
  92498. return cloneUnlessOtherwiseSpecified(source, optionsArgument)
  92499. } else if (sourceIsArray) {
  92500. var arrayMerge = options.arrayMerge || defaultArrayMerge;
  92501. return arrayMerge(target, source, optionsArgument)
  92502. } else {
  92503. return mergeObject(target, source, optionsArgument)
  92504. }
  92505. }
  92506. deepmerge.all = function deepmergeAll(array, optionsArgument) {
  92507. if (!Array.isArray(array)) {
  92508. throw new Error('first argument should be an array')
  92509. }
  92510. return array.reduce(function(prev, next) {
  92511. return deepmerge(prev, next, optionsArgument)
  92512. }, {})
  92513. };
  92514. var deepmerge_1 = deepmerge;
  92515. return deepmerge_1;
  92516. })));
  92517. /***/ }),
  92518. /* 3 */
  92519. /***/ (function(module, exports, __webpack_require__) {
  92520. "use strict";
  92521. Object.defineProperty(exports, "__esModule", { value: true });
  92522. function isUrl(urlToCheck) {
  92523. if (urlToCheck.indexOf('http') === 0 || urlToCheck.indexOf('/') === 0 || urlToCheck.indexOf('./') === 0 || urlToCheck.indexOf('../') === 0) {
  92524. return true;
  92525. }
  92526. return false;
  92527. }
  92528. exports.isUrl = isUrl;
  92529. function kebabToCamel(s) {
  92530. return s.replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); });
  92531. }
  92532. exports.kebabToCamel = kebabToCamel;
  92533. function camelToKebab(str) {
  92534. return !str ? null : str.replace(/([A-Z])/g, function (g) { return '-' + g[0].toLowerCase(); });
  92535. }
  92536. exports.camelToKebab = camelToKebab;
  92537. /***/ }),
  92538. /* 4 */
  92539. /***/ (function(module, exports, __webpack_require__) {
  92540. "use strict";
  92541. Object.defineProperty(exports, "__esModule", { value: true });
  92542. var babylonjs_1 = __webpack_require__(0);
  92543. var ViewerManager = (function () {
  92544. function ViewerManager() {
  92545. this._viewers = {};
  92546. this.onViewerAddedObservable = new babylonjs_1.Observable();
  92547. this.onViewerRemovedObservable = new babylonjs_1.Observable();
  92548. }
  92549. ViewerManager.prototype.addViewer = function (viewer) {
  92550. this._viewers[viewer.getBaseId()] = viewer;
  92551. this._onViewerAdded(viewer);
  92552. };
  92553. ViewerManager.prototype.removeViewer = function (viewer) {
  92554. var id = viewer.getBaseId();
  92555. delete this._viewers[id];
  92556. this.onViewerRemovedObservable.notifyObservers(id);
  92557. };
  92558. ViewerManager.prototype.getViewerById = function (id) {
  92559. return this._viewers[id];
  92560. };
  92561. ViewerManager.prototype.getViewerByHTMLElement = function (element) {
  92562. for (var id in this._viewers) {
  92563. if (this._viewers[id].containerElement === element) {
  92564. return this.getViewerById(id);
  92565. }
  92566. }
  92567. };
  92568. ViewerManager.prototype.getViewerPromiseById = function (id) {
  92569. var _this = this;
  92570. return new Promise(function (resolve, reject) {
  92571. var localViewer = _this.getViewerById(id);
  92572. if (localViewer) {
  92573. return resolve(localViewer);
  92574. }
  92575. var viewerFunction = function (viewer) {
  92576. if (viewer.getBaseId() === id) {
  92577. resolve(viewer);
  92578. _this.onViewerAddedObservable.removeCallback(viewerFunction);
  92579. }
  92580. };
  92581. _this.onViewerAddedObservable.add(viewerFunction);
  92582. });
  92583. };
  92584. ViewerManager.prototype._onViewerAdded = function (viewer) {
  92585. this.onViewerAdded && this.onViewerAdded(viewer);
  92586. this.onViewerAddedObservable.notifyObservers(viewer);
  92587. };
  92588. ViewerManager.prototype.dispose = function () {
  92589. for (var id in this._viewers) {
  92590. this._viewers[id].dispose();
  92591. }
  92592. };
  92593. return ViewerManager;
  92594. }());
  92595. exports.ViewerManager = ViewerManager;
  92596. exports.viewerManager = new ViewerManager();
  92597. /***/ }),
  92598. /* 5 */
  92599. /***/ (function(module, exports, __webpack_require__) {
  92600. "use strict";
  92601. var __extends = (this && this.__extends) || (function () {
  92602. var extendStatics = Object.setPrototypeOf ||
  92603. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  92604. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  92605. return function (d, b) {
  92606. extendStatics(d, b);
  92607. function __() { this.constructor = d; }
  92608. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  92609. };
  92610. })();
  92611. Object.defineProperty(exports, "__esModule", { value: true });
  92612. var viewer_1 = __webpack_require__(6);
  92613. var babylonjs_1 = __webpack_require__(0);
  92614. var DefaultViewer = (function (_super) {
  92615. __extends(DefaultViewer, _super);
  92616. function DefaultViewer(containerElement, initialConfiguration) {
  92617. if (initialConfiguration === void 0) { initialConfiguration = { extends: 'default' }; }
  92618. var _this = _super.call(this, containerElement, initialConfiguration) || this;
  92619. _this.containerElement = containerElement;
  92620. _this._onModelLoaded = function (model) {
  92621. _this._configureTemplate(model);
  92622. var hideLoadingDelay = 500;
  92623. if (_this._configuration.lab && _this._configuration.lab.hideLoadingDelay !== undefined) {
  92624. hideLoadingDelay = _this._configuration.lab.hideLoadingDelay;
  92625. }
  92626. setTimeout(function () {
  92627. _this.hideLoadingScreen();
  92628. }, hideLoadingDelay);
  92629. return;
  92630. };
  92631. _this.onModelLoadedObservable.add(_this._onModelLoaded);
  92632. return _this;
  92633. }
  92634. DefaultViewer.prototype._initScene = function () {
  92635. var _this = this;
  92636. return _super.prototype._initScene.call(this).then(function () {
  92637. _this._extendClassWithConfig(_this.scene, _this._configuration.scene);
  92638. return _this.scene;
  92639. });
  92640. };
  92641. DefaultViewer.prototype._onTemplatesLoaded = function () {
  92642. var _this = this;
  92643. this.showLoadingScreen();
  92644. this._initNavbar();
  92645. var closeButton = document.getElementById('close-button');
  92646. if (closeButton) {
  92647. closeButton.addEventListener('pointerdown', function () {
  92648. _this.hideOverlayScreen();
  92649. });
  92650. }
  92651. return _super.prototype._onTemplatesLoaded.call(this);
  92652. };
  92653. DefaultViewer.prototype._initNavbar = function () {
  92654. var navbar = this.templateManager.getTemplate('navBar');
  92655. if (navbar) {
  92656. var navbarHeight_1 = navbar.parent.clientHeight + 'px';
  92657. var navbarShown_1 = true;
  92658. var timeoutCancel_1;
  92659. var triggerNavbar = function (show, evt) {
  92660. if (show === void 0) { show = false; }
  92661. if (!navbar || evt.button > 0)
  92662. return;
  92663. timeoutCancel_1 && clearTimeout(timeoutCancel_1);
  92664. if (show === navbarShown_1)
  92665. return;
  92666. if (show) {
  92667. navbar.parent.style.bottom = show ? '0px' : '-' + navbarHeight_1;
  92668. navbarShown_1 = show;
  92669. }
  92670. else {
  92671. var visibilityTimeout = 2000;
  92672. if (navbar.configuration.params && navbar.configuration.params.visibilityTimeout !== undefined) {
  92673. visibilityTimeout = navbar.configuration.params.visibilityTimeout;
  92674. }
  92675. timeoutCancel_1 = setTimeout(function () {
  92676. if (navbar) {
  92677. navbar.parent.style.bottom = '-' + navbarHeight_1;
  92678. }
  92679. navbarShown_1 = show;
  92680. }, visibilityTimeout);
  92681. }
  92682. };
  92683. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, false), 'pointerout');
  92684. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, true), 'pointerdown');
  92685. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, false), 'pointerup');
  92686. this.templateManager.eventManager.registerCallback('navBar', triggerNavbar.bind(this, true), 'pointerover');
  92687. var viewerTemplate = this.templateManager.getTemplate('viewer');
  92688. var viewerElement_1 = viewerTemplate && viewerTemplate.parent;
  92689. var triggerFullscren = function (eventData) {
  92690. if (viewerElement_1) {
  92691. var fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  92692. if (!fullscreenElement) {
  92693. var requestFullScreen = viewerElement_1.requestFullscreen || viewerElement_1.webkitRequestFullscreen || viewerElement_1.msRequestFullscreen || viewerElement_1.mozRequestFullScreen;
  92694. requestFullScreen.call(viewerElement_1);
  92695. }
  92696. else {
  92697. var exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.msExitFullscreen || document.mozCancelFullScreen;
  92698. exitFullscreen.call(document);
  92699. }
  92700. }
  92701. };
  92702. this.templateManager.eventManager.registerCallback('navBar', triggerFullscren, 'pointerdown', '#fullscreen-button');
  92703. }
  92704. };
  92705. DefaultViewer.prototype._prepareContainerElement = function () {
  92706. this.containerElement.style.position = 'relative';
  92707. this.containerElement.style.display = 'flex';
  92708. };
  92709. DefaultViewer.prototype._configureTemplate = function (model) {
  92710. var navbar = this.templateManager.getTemplate('navBar');
  92711. if (!navbar)
  92712. return;
  92713. var modelConfiguration = model.configuration;
  92714. var metadataContainer = navbar.parent.querySelector('#model-metadata');
  92715. if (metadataContainer) {
  92716. if (modelConfiguration.title !== undefined) {
  92717. var element = metadataContainer.querySelector('span.model-title');
  92718. if (element) {
  92719. element.innerHTML = modelConfiguration.title;
  92720. }
  92721. }
  92722. if (modelConfiguration.subtitle !== undefined) {
  92723. var element = metadataContainer.querySelector('span.model-subtitle');
  92724. if (element) {
  92725. element.innerHTML = modelConfiguration.subtitle;
  92726. }
  92727. }
  92728. if (modelConfiguration.thumbnail !== undefined) {
  92729. metadataContainer.querySelector('.thumbnail').style.backgroundImage = "url('" + modelConfiguration.thumbnail + "')";
  92730. }
  92731. }
  92732. };
  92733. DefaultViewer.prototype.loadModel = function (model) {
  92734. var _this = this;
  92735. if (model === void 0) { model = this._configuration.model; }
  92736. this.showLoadingScreen();
  92737. return _super.prototype.loadModel.call(this, model, true).catch(function (error) {
  92738. console.log(error);
  92739. _this.hideLoadingScreen();
  92740. _this.showOverlayScreen('error');
  92741. return Promise.reject(error);
  92742. });
  92743. };
  92744. DefaultViewer.prototype.showOverlayScreen = function (subScreen) {
  92745. var _this = this;
  92746. var template = this.templateManager.getTemplate('overlay');
  92747. if (!template)
  92748. return Promise.resolve('Overlay template not found');
  92749. return template.show((function (template) {
  92750. var canvasRect = _this.containerElement.getBoundingClientRect();
  92751. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  92752. template.parent.style.display = 'flex';
  92753. template.parent.style.width = canvasRect.width + "px";
  92754. template.parent.style.height = canvasRect.height + "px";
  92755. template.parent.style.opacity = "1";
  92756. var subTemplate = _this.templateManager.getTemplate(subScreen);
  92757. if (!subTemplate) {
  92758. return Promise.reject(subScreen + ' template not found');
  92759. }
  92760. return subTemplate.show((function (template) {
  92761. template.parent.style.display = 'flex';
  92762. return Promise.resolve(template);
  92763. }));
  92764. }));
  92765. };
  92766. DefaultViewer.prototype.hideOverlayScreen = function () {
  92767. var template = this.templateManager.getTemplate('overlay');
  92768. if (!template)
  92769. return Promise.resolve('Overlay template not found');
  92770. return template.hide((function (template) {
  92771. template.parent.style.opacity = "0";
  92772. var onTransitionEnd = function () {
  92773. template.parent.removeEventListener("transitionend", onTransitionEnd);
  92774. template.parent.style.display = 'none';
  92775. };
  92776. template.parent.addEventListener("transitionend", onTransitionEnd);
  92777. var overlays = template.parent.querySelectorAll('.overlay');
  92778. if (overlays) {
  92779. for (var i = 0; i < overlays.length; ++i) {
  92780. var htmlElement = overlays.item(i);
  92781. htmlElement.style.display = 'none';
  92782. }
  92783. }
  92784. return Promise.resolve(template);
  92785. }));
  92786. };
  92787. DefaultViewer.prototype.showLoadingScreen = function () {
  92788. var _this = this;
  92789. var template = this.templateManager.getTemplate('loadingScreen');
  92790. if (!template)
  92791. return Promise.resolve('Loading Screen template not found');
  92792. return template.show((function (template) {
  92793. var canvasRect = _this.containerElement.getBoundingClientRect();
  92794. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  92795. template.parent.style.display = 'flex';
  92796. template.parent.style.width = canvasRect.width + "px";
  92797. template.parent.style.height = canvasRect.height + "px";
  92798. template.parent.style.opacity = "1";
  92799. template.parent.style.backgroundColor = "black";
  92800. return Promise.resolve(template);
  92801. }));
  92802. };
  92803. DefaultViewer.prototype.hideLoadingScreen = function () {
  92804. var template = this.templateManager.getTemplate('loadingScreen');
  92805. if (!template)
  92806. return Promise.resolve('Loading Screen template not found');
  92807. return template.hide((function (template) {
  92808. template.parent.style.opacity = "0";
  92809. var onTransitionEnd = function () {
  92810. template.parent.removeEventListener("transitionend", onTransitionEnd);
  92811. template.parent.style.display = 'none';
  92812. };
  92813. template.parent.addEventListener("transitionend", onTransitionEnd);
  92814. return Promise.resolve(template);
  92815. }));
  92816. };
  92817. DefaultViewer.prototype._configureLights = function (lightsConfiguration, model) {
  92818. var _this = this;
  92819. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  92820. _super.prototype._configureLights.call(this, lightsConfiguration, model);
  92821. if (this._configuration.lab && this._configuration.lab.flashlight) {
  92822. var pointerPosition = babylonjs_1.Vector3.Zero();
  92823. var lightTarget_1;
  92824. var angle = 0.5;
  92825. var exponent = Math.PI / 2;
  92826. if (typeof this._configuration.lab.flashlight === "object") {
  92827. exponent = this._configuration.lab.flashlight.exponent || exponent;
  92828. angle = this._configuration.lab.flashlight.angle || angle;
  92829. }
  92830. var flashlight = new babylonjs_1.SpotLight("flashlight", babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Zero(), exponent, angle, this.scene);
  92831. if (typeof this._configuration.lab.flashlight === "object") {
  92832. flashlight.intensity = this._configuration.lab.flashlight.intensity || flashlight.intensity;
  92833. if (this._configuration.lab.flashlight.diffuse) {
  92834. flashlight.diffuse.r = this._configuration.lab.flashlight.diffuse.r;
  92835. flashlight.diffuse.g = this._configuration.lab.flashlight.diffuse.g;
  92836. flashlight.diffuse.b = this._configuration.lab.flashlight.diffuse.b;
  92837. }
  92838. if (this._configuration.lab.flashlight.specular) {
  92839. flashlight.specular.r = this._configuration.lab.flashlight.specular.r;
  92840. flashlight.specular.g = this._configuration.lab.flashlight.specular.g;
  92841. flashlight.specular.b = this._configuration.lab.flashlight.specular.b;
  92842. }
  92843. }
  92844. this.scene.constantlyUpdateMeshUnderPointer = true;
  92845. this.scene.onPointerObservable.add(function (eventData, eventState) {
  92846. if (eventData.type === 4 && eventData.pickInfo) {
  92847. lightTarget_1 = (eventData.pickInfo.pickedPoint);
  92848. }
  92849. else {
  92850. lightTarget_1 = undefined;
  92851. }
  92852. });
  92853. var updateFlashlightFunction = function () {
  92854. if (_this.camera && flashlight) {
  92855. flashlight.position.copyFrom(_this.camera.position);
  92856. if (lightTarget_1) {
  92857. lightTarget_1.subtractToRef(flashlight.position, flashlight.direction);
  92858. }
  92859. }
  92860. };
  92861. this.scene.registerBeforeRender(updateFlashlightFunction);
  92862. this._registeredOnBeforeRenderFunctions.push(updateFlashlightFunction);
  92863. }
  92864. };
  92865. return DefaultViewer;
  92866. }(viewer_1.AbstractViewer));
  92867. exports.DefaultViewer = DefaultViewer;
  92868. /***/ }),
  92869. /* 6 */
  92870. /***/ (function(module, exports, __webpack_require__) {
  92871. "use strict";
  92872. Object.defineProperty(exports, "__esModule", { value: true });
  92873. var viewerManager_1 = __webpack_require__(4);
  92874. var templateManager_1 = __webpack_require__(23);
  92875. var loader_1 = __webpack_require__(26);
  92876. var babylonjs_1 = __webpack_require__(0);
  92877. var deepmerge = __webpack_require__(2);
  92878. var modelLoader_1 = __webpack_require__(14);
  92879. var AbstractViewer = (function () {
  92880. function AbstractViewer(containerElement, initialConfiguration) {
  92881. if (initialConfiguration === void 0) { initialConfiguration = {}; }
  92882. var _this = this;
  92883. this.containerElement = containerElement;
  92884. this._isDisposed = false;
  92885. this._resize = function () {
  92886. if (!_this.isCanvasInDOM()) {
  92887. return;
  92888. }
  92889. if (_this.canvas.clientWidth <= 0 || _this.canvas.clientHeight <= 0) {
  92890. return;
  92891. }
  92892. _this.engine.resize();
  92893. };
  92894. this._render = function () {
  92895. _this.scene && _this.scene.activeCamera && _this.scene.render();
  92896. };
  92897. if (containerElement.id) {
  92898. this.baseId = containerElement.id;
  92899. }
  92900. else {
  92901. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  92902. }
  92903. this.onSceneInitObservable = new babylonjs_1.Observable();
  92904. this.onEngineInitObservable = new babylonjs_1.Observable();
  92905. this.onModelLoadedObservable = new babylonjs_1.Observable();
  92906. this.onModelLoadProgressObservable = new babylonjs_1.Observable();
  92907. this.onModelLoadErrorObservable = new babylonjs_1.Observable();
  92908. this.onInitDoneObservable = new babylonjs_1.Observable();
  92909. this.onLoaderInitObservable = new babylonjs_1.Observable();
  92910. this._registeredOnBeforeRenderFunctions = [];
  92911. this.models = [];
  92912. this.modelLoader = new modelLoader_1.ModelLoader(this);
  92913. viewerManager_1.viewerManager.addViewer(this);
  92914. this.templateManager = new templateManager_1.TemplateManager(containerElement);
  92915. this._prepareContainerElement();
  92916. this._configurationLoader = new loader_1.ConfigurationLoader();
  92917. this._configurationLoader.loadConfiguration(initialConfiguration, function (configuration) {
  92918. _this._configuration = deepmerge(_this._configuration || {}, configuration);
  92919. if (_this._configuration.observers) {
  92920. _this._configureObservers(_this._configuration.observers);
  92921. }
  92922. var templateConfiguration = _this._configuration.templates || {};
  92923. _this.templateManager.initTemplate(templateConfiguration);
  92924. _this.templateManager.onAllLoaded.add(function () {
  92925. var canvas = _this.templateManager.getCanvas();
  92926. if (canvas) {
  92927. _this._canvas = canvas;
  92928. }
  92929. _this._onTemplateLoaded();
  92930. });
  92931. });
  92932. }
  92933. Object.defineProperty(AbstractViewer.prototype, "isHdrSupported", {
  92934. get: function () {
  92935. return this._hdrSupport;
  92936. },
  92937. enumerable: true,
  92938. configurable: true
  92939. });
  92940. Object.defineProperty(AbstractViewer.prototype, "canvas", {
  92941. get: function () {
  92942. return this._canvas;
  92943. },
  92944. enumerable: true,
  92945. configurable: true
  92946. });
  92947. AbstractViewer.prototype.getBaseId = function () {
  92948. return this.baseId;
  92949. };
  92950. AbstractViewer.prototype.isCanvasInDOM = function () {
  92951. return !!this._canvas && !!this._canvas.parentElement;
  92952. };
  92953. AbstractViewer.prototype.updateConfiguration = function (newConfiguration) {
  92954. if (newConfiguration === void 0) { newConfiguration = this._configuration; }
  92955. this._configuration = deepmerge(this._configuration || {}, newConfiguration);
  92956. if (newConfiguration.scene) {
  92957. this._configureScene(newConfiguration.scene);
  92958. }
  92959. if (newConfiguration.optimizer) {
  92960. this._configureOptimizer(newConfiguration.optimizer);
  92961. }
  92962. if (newConfiguration.observers) {
  92963. this._configureObservers(newConfiguration.observers);
  92964. }
  92965. if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  92966. this._configureModel(newConfiguration.model);
  92967. }
  92968. if (newConfiguration.lights) {
  92969. this._configureLights(newConfiguration.lights);
  92970. }
  92971. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  92972. this._configureEnvironment(newConfiguration.skybox, newConfiguration.ground);
  92973. }
  92974. if (newConfiguration.camera) {
  92975. this._configureCamera(newConfiguration.camera);
  92976. }
  92977. };
  92978. AbstractViewer.prototype._configureEnvironment = function (skyboxConifguration, groundConfiguration) {
  92979. if (!skyboxConifguration && !groundConfiguration) {
  92980. if (this.environmentHelper) {
  92981. this.environmentHelper.dispose();
  92982. delete this.environmentHelper;
  92983. }
  92984. ;
  92985. return Promise.resolve(this.scene);
  92986. }
  92987. var options = {
  92988. createGround: !!groundConfiguration,
  92989. createSkybox: !!skyboxConifguration,
  92990. setupImageProcessing: false
  92991. };
  92992. if (groundConfiguration) {
  92993. var groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  92994. var groundSize = groundConfig.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  92995. if (groundSize) {
  92996. options.groundSize = groundSize;
  92997. }
  92998. options.enableGroundShadow = groundConfig === true || groundConfig.receiveShadows;
  92999. if (groundConfig.shadowLevel !== undefined) {
  93000. options.groundShadowLevel = groundConfig.shadowLevel;
  93001. }
  93002. options.enableGroundMirror = !!groundConfig.mirror;
  93003. if (groundConfig.texture) {
  93004. options.groundTexture = groundConfig.texture;
  93005. }
  93006. if (groundConfig.color) {
  93007. options.groundColor = new babylonjs_1.Color3(groundConfig.color.r, groundConfig.color.g, groundConfig.color.b);
  93008. }
  93009. if (groundConfig.opacity !== undefined) {
  93010. options.groundOpacity = groundConfig.opacity;
  93011. }
  93012. if (groundConfig.mirror) {
  93013. options.enableGroundMirror = true;
  93014. if (typeof groundConfig.mirror === "object") {
  93015. if (groundConfig.mirror.amount !== undefined)
  93016. options.groundMirrorAmount = groundConfig.mirror.amount;
  93017. if (groundConfig.mirror.sizeRatio !== undefined)
  93018. options.groundMirrorSizeRatio = groundConfig.mirror.sizeRatio;
  93019. if (groundConfig.mirror.blurKernel !== undefined)
  93020. options.groundMirrorBlurKernel = groundConfig.mirror.blurKernel;
  93021. if (groundConfig.mirror.fresnelWeight !== undefined)
  93022. options.groundMirrorFresnelWeight = groundConfig.mirror.fresnelWeight;
  93023. if (groundConfig.mirror.fallOffDistance !== undefined)
  93024. options.groundMirrorFallOffDistance = groundConfig.mirror.fallOffDistance;
  93025. if (this._defaultPipelineTextureType !== undefined)
  93026. options.groundMirrorTextureType = this._defaultPipelineTextureType;
  93027. }
  93028. }
  93029. }
  93030. var postInitSkyboxMaterial = false;
  93031. if (skyboxConifguration) {
  93032. var conf = skyboxConifguration === true ? {} : skyboxConifguration;
  93033. if (conf.material && conf.material.imageProcessingConfiguration) {
  93034. options.setupImageProcessing = false;
  93035. }
  93036. var skyboxSize = conf.scale;
  93037. if (skyboxSize) {
  93038. options.skyboxSize = skyboxSize;
  93039. }
  93040. options.sizeAuto = !options.skyboxSize;
  93041. if (conf.color) {
  93042. options.skyboxColor = new babylonjs_1.Color3(conf.color.r, conf.color.g, conf.color.b);
  93043. }
  93044. if (conf.cubeTexture && conf.cubeTexture.url) {
  93045. if (typeof conf.cubeTexture.url === "string") {
  93046. options.skyboxTexture = conf.cubeTexture.url;
  93047. }
  93048. else {
  93049. postInitSkyboxMaterial = true;
  93050. }
  93051. }
  93052. if (conf.material && conf.material.imageProcessingConfiguration) {
  93053. postInitSkyboxMaterial = true;
  93054. }
  93055. }
  93056. options.setupImageProcessing = false;
  93057. if (!this.environmentHelper) {
  93058. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  93059. }
  93060. else {
  93061. var scene = this.environmentHelper.rootMesh.getScene();
  93062. if (scene !== this.scene) {
  93063. this.environmentHelper.dispose();
  93064. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  93065. }
  93066. else {
  93067. this.environmentHelper.updateOptions(options);
  93068. }
  93069. }
  93070. if (postInitSkyboxMaterial) {
  93071. var skyboxMaterial = this.environmentHelper.skyboxMaterial;
  93072. if (skyboxMaterial) {
  93073. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material && skyboxConifguration.material.imageProcessingConfiguration) {
  93074. this._extendClassWithConfig(skyboxMaterial.imageProcessingConfiguration, skyboxConifguration.material.imageProcessingConfiguration);
  93075. }
  93076. }
  93077. }
  93078. };
  93079. AbstractViewer.prototype._configureScene = function (sceneConfig) {
  93080. if (!this.scene) {
  93081. return;
  93082. }
  93083. if (sceneConfig.debug) {
  93084. this.scene.debugLayer.show();
  93085. }
  93086. else {
  93087. if (this.scene.debugLayer.isVisible()) {
  93088. this.scene.debugLayer.hide();
  93089. }
  93090. }
  93091. if (sceneConfig.clearColor) {
  93092. var cc = sceneConfig.clearColor;
  93093. var oldcc = this.scene.clearColor;
  93094. if (cc.r !== undefined) {
  93095. oldcc.r = cc.r;
  93096. }
  93097. if (cc.g !== undefined) {
  93098. oldcc.g = cc.g;
  93099. }
  93100. if (cc.b !== undefined) {
  93101. oldcc.b = cc.b;
  93102. }
  93103. if (cc.a !== undefined) {
  93104. oldcc.a = cc.a;
  93105. }
  93106. }
  93107. if (sceneConfig.imageProcessingConfiguration) {
  93108. this._extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  93109. }
  93110. if (sceneConfig.environmentTexture) {
  93111. if (this.scene.environmentTexture) {
  93112. this.scene.environmentTexture.dispose();
  93113. }
  93114. var environmentTexture = babylonjs_1.CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  93115. this.scene.environmentTexture = environmentTexture;
  93116. }
  93117. if (sceneConfig.autoRotate) {
  93118. this.camera.useAutoRotationBehavior = true;
  93119. }
  93120. };
  93121. AbstractViewer.prototype._configureOptimizer = function (optimizerConfig) {
  93122. if (typeof optimizerConfig === 'boolean') {
  93123. if (this.sceneOptimizer) {
  93124. this.sceneOptimizer.stop();
  93125. this.sceneOptimizer.dispose();
  93126. delete this.sceneOptimizer;
  93127. }
  93128. if (optimizerConfig) {
  93129. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene);
  93130. this.sceneOptimizer.start();
  93131. }
  93132. }
  93133. else {
  93134. var optimizerOptions = new babylonjs_1.SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  93135. if (optimizerConfig.degradation) {
  93136. switch (optimizerConfig.degradation) {
  93137. case "low":
  93138. optimizerOptions = babylonjs_1.SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  93139. break;
  93140. case "moderate":
  93141. optimizerOptions = babylonjs_1.SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  93142. break;
  93143. case "hight":
  93144. optimizerOptions = babylonjs_1.SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  93145. break;
  93146. }
  93147. }
  93148. if (this.sceneOptimizer) {
  93149. this.sceneOptimizer.stop();
  93150. this.sceneOptimizer.dispose();
  93151. }
  93152. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  93153. this.sceneOptimizer.start();
  93154. }
  93155. };
  93156. AbstractViewer.prototype._configureObservers = function (observersConfiguration) {
  93157. if (observersConfiguration.onEngineInit) {
  93158. this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]);
  93159. }
  93160. else {
  93161. if (observersConfiguration.onEngineInit === '' && this._configuration.observers && this._configuration.observers.onEngineInit) {
  93162. this.onEngineInitObservable.removeCallback(window[this._configuration.observers.onEngineInit]);
  93163. }
  93164. }
  93165. if (observersConfiguration.onSceneInit) {
  93166. this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]);
  93167. }
  93168. else {
  93169. if (observersConfiguration.onSceneInit === '' && this._configuration.observers && this._configuration.observers.onSceneInit) {
  93170. this.onSceneInitObservable.removeCallback(window[this._configuration.observers.onSceneInit]);
  93171. }
  93172. }
  93173. if (observersConfiguration.onModelLoaded) {
  93174. this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]);
  93175. }
  93176. else {
  93177. if (observersConfiguration.onModelLoaded === '' && this._configuration.observers && this._configuration.observers.onModelLoaded) {
  93178. this.onModelLoadedObservable.removeCallback(window[this._configuration.observers.onModelLoaded]);
  93179. }
  93180. }
  93181. };
  93182. AbstractViewer.prototype._configureCamera = function (cameraConfig, model) {
  93183. var _this = this;
  93184. var focusMeshes = model ? model.meshes : this.scene.meshes;
  93185. if (!this.scene.activeCamera) {
  93186. this.scene.createDefaultCamera(true, true, true);
  93187. this.camera = this.scene.activeCamera;
  93188. }
  93189. if (cameraConfig.position) {
  93190. this.camera.position.copyFromFloats(cameraConfig.position.x || 0, cameraConfig.position.y || 0, cameraConfig.position.z || 0);
  93191. }
  93192. if (cameraConfig.rotation) {
  93193. this.camera.rotationQuaternion = new babylonjs_1.Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0);
  93194. }
  93195. this._extendClassWithConfig(this.camera, cameraConfig);
  93196. this.camera.minZ = cameraConfig.minZ || this.camera.minZ;
  93197. this.camera.maxZ = cameraConfig.maxZ || this.camera.maxZ;
  93198. if (cameraConfig.behaviors) {
  93199. for (var name_1 in cameraConfig.behaviors) {
  93200. this._setCameraBehavior(cameraConfig.behaviors[name_1], focusMeshes);
  93201. }
  93202. }
  93203. ;
  93204. var sceneExtends = this.scene.getWorldExtends(function (mesh) {
  93205. return !_this.environmentHelper || (mesh !== _this.environmentHelper.ground && mesh !== _this.environmentHelper.rootMesh && mesh !== _this.environmentHelper.skybox);
  93206. });
  93207. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  93208. var sceneDiagonalLenght = sceneDiagonal.length();
  93209. if (isFinite(sceneDiagonalLenght))
  93210. this.camera.upperRadiusLimit = sceneDiagonalLenght * 3;
  93211. };
  93212. AbstractViewer.prototype._configureLights = function (lightsConfiguration, model) {
  93213. var _this = this;
  93214. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  93215. var focusMeshes = model ? model.meshes : this.scene.meshes;
  93216. if (!Object.keys(lightsConfiguration).length)
  93217. return;
  93218. var lightsAvailable = this.scene.lights.map(function (light) { return light.name; });
  93219. var lightsToConfigure = Object.keys(this._configuration.lights || []);
  93220. if (Object.keys(lightsToConfigure).length !== lightsAvailable.length) {
  93221. lightsAvailable.forEach(function (lName) {
  93222. if (lightsToConfigure.indexOf(lName) === -1) {
  93223. _this.scene.getLightByName(lName).dispose();
  93224. }
  93225. });
  93226. }
  93227. Object.keys(lightsConfiguration).forEach(function (name, idx) {
  93228. var lightConfig = { type: 0 };
  93229. if (typeof lightsConfiguration[name] === 'object') {
  93230. lightConfig = lightsConfiguration[name];
  93231. }
  93232. lightConfig.name = name;
  93233. var light;
  93234. if (lightsAvailable.indexOf(name) === -1) {
  93235. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  93236. if (!constructor)
  93237. return;
  93238. light = constructor();
  93239. }
  93240. else {
  93241. light = _this.scene.getLightByName(name);
  93242. lightsAvailable = lightsAvailable.filter(function (ln) { return ln !== name; });
  93243. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  93244. light.dispose();
  93245. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  93246. if (!constructor)
  93247. return;
  93248. light = constructor();
  93249. }
  93250. }
  93251. if (lightsConfiguration[name] === false) {
  93252. light.dispose();
  93253. return;
  93254. }
  93255. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  93256. light.setEnabled(enabled);
  93257. _this._extendClassWithConfig(light, lightConfig);
  93258. if (light instanceof babylonjs_1.ShadowLight) {
  93259. if (lightConfig.target) {
  93260. if (light.setDirectionToTarget) {
  93261. var target = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.target);
  93262. light.setDirectionToTarget(target);
  93263. }
  93264. }
  93265. else if (lightConfig.direction) {
  93266. var direction = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.direction);
  93267. light.direction = direction;
  93268. }
  93269. var shadowGenerator = light.getShadowGenerator();
  93270. if (lightConfig.shadowEnabled && _this._maxShadows) {
  93271. if (!shadowGenerator) {
  93272. shadowGenerator = new babylonjs_1.ShadowGenerator(512, light);
  93273. }
  93274. _this._extendClassWithConfig(shadowGenerator, lightConfig.shadowConfig || {});
  93275. var shadownMap = shadowGenerator.getShadowMap();
  93276. if (!shadownMap)
  93277. return;
  93278. var renderList = shadownMap.renderList;
  93279. for (var index = 0; index < focusMeshes.length; index++) {
  93280. if (babylonjs_1.Tags.MatchesQuery(focusMeshes[index], 'castShadow')) {
  93281. renderList && renderList.push(focusMeshes[index]);
  93282. }
  93283. }
  93284. }
  93285. else if (shadowGenerator) {
  93286. shadowGenerator.dispose();
  93287. }
  93288. }
  93289. });
  93290. };
  93291. AbstractViewer.prototype._configureModel = function (modelConfiguration) {
  93292. this.models.forEach(function (model) {
  93293. model.updateConfiguration(modelConfiguration);
  93294. });
  93295. };
  93296. AbstractViewer.prototype.dispose = function () {
  93297. if (this._isDisposed) {
  93298. return;
  93299. }
  93300. window.removeEventListener('resize', this._resize);
  93301. if (this.sceneOptimizer) {
  93302. this.sceneOptimizer.stop();
  93303. this.sceneOptimizer.dispose();
  93304. }
  93305. if (this.environmentHelper) {
  93306. this.environmentHelper.dispose();
  93307. }
  93308. if (this._configurationLoader) {
  93309. this._configurationLoader.dispose();
  93310. }
  93311. this.onEngineInitObservable.clear();
  93312. delete this.onEngineInitObservable;
  93313. this.onInitDoneObservable.clear();
  93314. delete this.onInitDoneObservable;
  93315. this.onLoaderInitObservable.clear();
  93316. delete this.onLoaderInitObservable;
  93317. this.onModelLoadedObservable.clear();
  93318. delete this.onModelLoadedObservable;
  93319. this.onModelLoadErrorObservable.clear();
  93320. delete this.onModelLoadErrorObservable;
  93321. this.onModelLoadProgressObservable.clear();
  93322. delete this.onModelLoadProgressObservable;
  93323. this.onSceneInitObservable.clear();
  93324. delete this.onSceneInitObservable;
  93325. if (this.scene.activeCamera) {
  93326. this.scene.activeCamera.detachControl(this.canvas);
  93327. }
  93328. this.modelLoader.dispose();
  93329. this.models.forEach(function (model) {
  93330. model.dispose();
  93331. });
  93332. this.models.length = 0;
  93333. this.scene.dispose();
  93334. this.engine.dispose();
  93335. this.templateManager.dispose();
  93336. viewerManager_1.viewerManager.removeViewer(this);
  93337. this._isDisposed = true;
  93338. };
  93339. AbstractViewer.prototype._onTemplatesLoaded = function () {
  93340. return Promise.resolve(this);
  93341. };
  93342. AbstractViewer.prototype._onTemplateLoaded = function () {
  93343. var _this = this;
  93344. return this._onTemplatesLoaded().then(function () {
  93345. var autoLoadModel = _this._configuration.model;
  93346. return _this._initEngine().then(function (engine) {
  93347. return _this.onEngineInitObservable.notifyObserversWithPromise(engine);
  93348. }).then(function () {
  93349. if (autoLoadModel) {
  93350. return _this.loadModel().catch(function (e) { }).then(function () { return _this.scene; });
  93351. }
  93352. else {
  93353. return _this.scene || _this._initScene();
  93354. }
  93355. }).then(function (scene) {
  93356. return _this.onSceneInitObservable.notifyObserversWithPromise(scene);
  93357. }).then(function () {
  93358. return _this.onInitDoneObservable.notifyObserversWithPromise(_this);
  93359. }).catch(function (e) {
  93360. babylonjs_1.Tools.Warn(e.toString());
  93361. return _this;
  93362. });
  93363. });
  93364. };
  93365. AbstractViewer.prototype._initEngine = function () {
  93366. this._injectCustomShaders();
  93367. var canvasElement = this.templateManager.getCanvas();
  93368. if (!canvasElement) {
  93369. return Promise.reject('Canvas element not found!');
  93370. }
  93371. var config = this._configuration.engine || {};
  93372. this.engine = new babylonjs_1.Engine(canvasElement, !!config.antialiasing, config.engineOptions);
  93373. babylonjs_1.Database.IDBStorageEnabled = false;
  93374. if (!config.disableResize) {
  93375. window.addEventListener('resize', this._resize);
  93376. }
  93377. this.engine.runRenderLoop(this._render);
  93378. if (this._configuration.engine && this._configuration.engine.adaptiveQuality) {
  93379. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  93380. this.engine.setHardwareScalingLevel(scale);
  93381. }
  93382. this._handleHardwareLimitations();
  93383. return Promise.resolve(this.engine);
  93384. };
  93385. AbstractViewer.prototype._initScene = function () {
  93386. if (this.scene) {
  93387. this.scene.dispose();
  93388. }
  93389. this.scene = new babylonjs_1.Scene(this.engine);
  93390. this.scene.createDefaultLight(true);
  93391. if (this._configuration.scene) {
  93392. this._configureScene(this._configuration.scene);
  93393. if (this._configuration.optimizer) {
  93394. this._configureOptimizer(this._configuration.optimizer);
  93395. }
  93396. }
  93397. return Promise.resolve(this.scene);
  93398. };
  93399. AbstractViewer.prototype.initModel = function (modelConfig, clearScene) {
  93400. var _this = this;
  93401. if (clearScene === void 0) { clearScene = true; }
  93402. if (clearScene) {
  93403. this.models.forEach(function (m) { return m.dispose(); });
  93404. this.models.length = 0;
  93405. }
  93406. var model = this.modelLoader.load(modelConfig);
  93407. this.lastUsedLoader = model.loader;
  93408. model.onLoadErrorObservable.add(function (errorObject) {
  93409. _this.onModelLoadErrorObservable.notifyObserversWithPromise(errorObject);
  93410. });
  93411. model.onLoadProgressObservable.add(function (progressEvent) {
  93412. return _this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  93413. });
  93414. this.onLoaderInitObservable.notifyObserversWithPromise(this.lastUsedLoader);
  93415. model.onLoadedObservable.add(function () {
  93416. _this.onModelLoadedObservable.notifyObserversWithPromise(model)
  93417. .then(function () {
  93418. _this._configureLights(_this._configuration.lights);
  93419. if (_this._configuration.camera || !_this.scene.activeCamera) {
  93420. _this._configureCamera(_this._configuration.camera || {}, model);
  93421. }
  93422. return _this._initEnvironment(model);
  93423. }).then(function () {
  93424. _this._isLoading = false;
  93425. return model;
  93426. });
  93427. });
  93428. return model;
  93429. };
  93430. AbstractViewer.prototype.loadModel = function (modelConfig, clearScene) {
  93431. var _this = this;
  93432. if (modelConfig === void 0) { modelConfig = this._configuration.model; }
  93433. if (clearScene === void 0) { clearScene = true; }
  93434. var modelUrl = (typeof modelConfig === 'string') ? modelConfig : modelConfig.url;
  93435. if (!modelUrl) {
  93436. return Promise.reject("no model configuration found");
  93437. }
  93438. if (this._isLoading) {
  93439. return Promise.reject("another model is curently being loaded.");
  93440. }
  93441. this._isLoading = true;
  93442. if ((typeof modelConfig === 'string')) {
  93443. if (this._configuration.model && typeof this._configuration.model === 'object') {
  93444. this._configuration.model.url = modelConfig;
  93445. }
  93446. }
  93447. else {
  93448. if (this._configuration.model) {
  93449. deepmerge(this._configuration.model, modelConfig);
  93450. }
  93451. else {
  93452. this._configuration.model = modelConfig;
  93453. }
  93454. }
  93455. return Promise.resolve(this.scene).then(function (scene) {
  93456. if (!scene)
  93457. return _this._initScene();
  93458. return scene;
  93459. }).then(function () {
  93460. return new Promise(function (resolve, reject) {
  93461. return _this.initModel(modelConfig, clearScene);
  93462. });
  93463. });
  93464. };
  93465. AbstractViewer.prototype._initEnvironment = function (model) {
  93466. this._configureEnvironment(this._configuration.skybox, this._configuration.ground);
  93467. return Promise.resolve(this.scene);
  93468. };
  93469. AbstractViewer.prototype._handleHardwareLimitations = function (enableHDR) {
  93470. if (enableHDR === void 0) { enableHDR = true; }
  93471. var maxVaryingRows = this.engine.getCaps().maxVaryingVectors;
  93472. var maxFragmentSamplers = this.engine.getCaps().maxTexturesImageUnits;
  93473. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  93474. this._maxShadows = 0;
  93475. }
  93476. else {
  93477. this._maxShadows = 3;
  93478. }
  93479. var caps = this.engine.getCaps();
  93480. var linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  93481. var linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  93482. this._hdrSupport = enableHDR && !!(linearFloatTargets || linearHalfFloatTargets);
  93483. if (linearHalfFloatTargets) {
  93484. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_HALF_FLOAT;
  93485. this._shadowGeneratorBias = 0.002;
  93486. }
  93487. else if (linearFloatTargets) {
  93488. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_FLOAT;
  93489. this._shadowGeneratorBias = 0.001;
  93490. }
  93491. else {
  93492. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  93493. this._shadowGeneratorBias = 0.001;
  93494. }
  93495. this._defaultPipelineTextureType = this._hdrSupport ? this._defaultHighpTextureType : babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  93496. };
  93497. AbstractViewer.prototype._injectCustomShaders = function () {
  93498. var customShaders = this._configuration.customShaders;
  93499. if (!customShaders) {
  93500. return;
  93501. }
  93502. if (customShaders.shaders) {
  93503. Object.keys(customShaders.shaders).forEach(function (key) {
  93504. babylonjs_1.Effect.ShadersStore[key] = customShaders.shaders[key];
  93505. });
  93506. }
  93507. if (customShaders.includes) {
  93508. Object.keys(customShaders.includes).forEach(function (key) {
  93509. babylonjs_1.Effect.IncludesShadersStore[key] = customShaders.includes[key];
  93510. });
  93511. }
  93512. };
  93513. AbstractViewer.prototype._extendClassWithConfig = function (object, config) {
  93514. var _this = this;
  93515. if (!config)
  93516. return;
  93517. Object.keys(config).forEach(function (key) {
  93518. if (key in object && typeof object[key] !== 'function') {
  93519. if (typeof object[key] === 'object') {
  93520. _this._extendClassWithConfig(object[key], config[key]);
  93521. }
  93522. else {
  93523. if (config[key] !== undefined) {
  93524. object[key] = config[key];
  93525. }
  93526. }
  93527. }
  93528. });
  93529. };
  93530. AbstractViewer.prototype._setCameraBehavior = function (behaviorConfig, payload) {
  93531. var behavior;
  93532. var type = (typeof behaviorConfig !== "object") ? behaviorConfig : behaviorConfig.type;
  93533. var config = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  93534. switch (type) {
  93535. case 0:
  93536. this.camera.useAutoRotationBehavior = true;
  93537. behavior = this.camera.autoRotationBehavior;
  93538. break;
  93539. case 1:
  93540. this.camera.useBouncingBehavior = true;
  93541. behavior = this.camera.bouncingBehavior;
  93542. break;
  93543. case 2:
  93544. this.camera.useFramingBehavior = true;
  93545. behavior = this.camera.framingBehavior;
  93546. break;
  93547. default:
  93548. behavior = null;
  93549. break;
  93550. }
  93551. if (behavior) {
  93552. if (typeof behaviorConfig === "object") {
  93553. this._extendClassWithConfig(behavior, behaviorConfig);
  93554. }
  93555. }
  93556. switch (type) {
  93557. case 0:
  93558. break;
  93559. case 1:
  93560. break;
  93561. case 2:
  93562. if (config.zoomOnBoundingInfo) {
  93563. var meshes = payload;
  93564. var bounding = meshes[0].getHierarchyBoundingVectors();
  93565. behavior.zoomOnBoundingInfo(bounding.min, bounding.max);
  93566. }
  93567. break;
  93568. }
  93569. };
  93570. return AbstractViewer;
  93571. }());
  93572. exports.AbstractViewer = AbstractViewer;
  93573. /***/ }),
  93574. /* 7 */
  93575. /***/ (function(module, exports) {
  93576. module.exports = "<viewer></viewer> <loading-screen></loading-screen> <overlay></overlay>";
  93577. /***/ }),
  93578. /* 8 */
  93579. /***/ (function(module, exports) {
  93580. 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 2s ease;-moz-transition:opacity 2s ease;transition:opacity 2s 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}}>";
  93581. /***/ }),
  93582. /* 9 */
  93583. /***/ (function(module, exports) {
  93584. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAStUlEQVR42uyaA7TrShiFn23btm3btm3btm3btm372LWd9+318nSRNk2mtz3trLXX5PbmZOafPT9nxmq1VmuKFggEZs1ms0uVSqUj8vn8Q/SP5nK5lRpMjFYLh8NTZTKZhSBxi2KxeDlEPgh+BQVrhKbfwDNgZf45QZ2J0mrxeHxGtHJRCDoUQm+FpLd4joKc5aKJaDbDNzxuZT3yyLg1FqPVWPip0un0PBCxMUScD+6wtTJr+dz49hdsmh14nMiAKK0WiUSmgbjFC4XCYSz2VeB9/p2wyaxJK9EY93set+dxwhYr1QU9U7B4s4CNIfMM+pvAzyBm1VFjPl+D3cDELdacyVy4kMsdLBMrX0kf4beM1QCt9Ff7hY14nGRpWiIHBgYmU+BDwLMRi3EMJN4KpJUBa5g05OlHthORc4amIJXgZ30EPtXWyiHITFtN0JBziDz6DB6nHtYEI+i04BZQtJqwIfcAOBXM0hCEdXR0TM1k5ydV2Iv+CLTyeXbqgWeeeeY4DmnMOGjxTrw/aDVpkxtirW7Bos09xkns6+ublAlNA3Gr4S+3JCe4ksk9YOeWsdH4nkcTicTMZfLVuXjvrQYmKS54/EZaRReqaQvzz7FrZUYXBocz8BV2tWcQpEDR5eR7mPjGTmP98ssvEyra5N1CnZNZBL+Dp9mUF7A2a0W7u6dlE8/E82Ve0zVlCHz3HhFtnGAmfJWPC5Nm4pfSO6YLWIdVee/bOiFTiz1A/zL9xSpJqjLmpGHJZHJW9sDlvB/yul7gHlze4sY0Wr7UQLrwierA5fJf7eISrcaE9jHuh/TXsLk3j0aj81dbepRbUkXND40Gz7Hx1/SdaIRcz9BCxjDHh/A4nlMAxvjbKa0wZGaDKmeCO5nLAQoQOzs7fa86pVKpOfj2lSDsdc60N5Reat380uD5DfuyZ5KBwGzOc0jNiWCvet1QfONH+ushcz/M6AoqIUojapgWzgauBTEfiP6QzS+ix/E0qW6CB9MFCL7/G5Pd1DGd+uyz8SHmKB0eVPC9KAvwA3iK56Py6fTasVhseoMnVuMrs6h0seWelFnI9PqgIG+DTT2dSSsFsgw3+1z1ZpUsyyzOMrz7+QgH77+CB9gAp/HTWqFQaEqZMMOp4hKMd7hN1DcgxfMzLiLfsZFlMf7mScngA9Gfqp7w3XffuSe6WCi8Y9WufUYwsUKZY0EVVA5FoB3wR3MZNquTg3mxMNvSXw0+Bn1OrgBcid+ds9IxkHc51ljWJuNDAPsb67I/j5O5EfKaGkeyaSZ5hEktdEhxZrGs3GqMfxKL9aYCPJCtYqET4BIep6zQzI9N1L20rIA02geiO5HhYKunZ5JKdtgpNThSCzGpt+2z3YN0N8rkOaoW1K7Iicy9Gfs2HeuBrM+ytWuh3WiULvQxn2d90uh2OmUIkzpp8MZ+ayj4lcFvl6ZiznRxbRKTEe0j3JdizPkYb3fGvUim1n1FzptG4XP3rjQQ03tgWeW/oFBlPv8s8h6tG6GO1tBOKYoeKkFt4HmdhbI7V+F7Rk9P2traJlKRoZTP6x7WOeAl5tFZJyXOt3Xm/eabb47nwkWuCl4YHQf8nheh4BkgQpfWGrjxwdOAlEsNvR/sh6ldsJbXShlrXDbSyfV8tmznse/SL+ZCrnGUSvJ3X/6toUAaeowIVbXNa1rQ78IcfaCc1s+bkWj+ijKvCvjoj6Sf0Mm/5jOZbXinrc4PLdJQfbdSKzeuxkjFTSdJbs43qw2QtFNtX7mrTmr+c1+5OMIYz5VLRfj/2XnvlQa4ypMBCi6nMW7hwmFdI553VDXpB1wQHKyEYL0DZrHvLJ8LXnbjK2WmdCb9iMOF88+cK2D1d8MD96Kqm5+ZAlgHKBZ5Q8rHml3i6VRJGlfJDUI7Oo/4UAG7tdx4mPhlHSpy9Ub0oA4/qvGryrsVlOmuG/37IDniiZy4HOkPC9nsTm4miXlcrZIJ4X82gaA/2zvneNmdHoz/bNu2bdu2bdu2bdu2bdu2fbz3zfe9+eOizelMs93uns7n08uz0+48nUzwJPnFyQO2QAZi/IXNwgGTdXlTgFrfMnH4P9mRS6m18GgWFio/7xFVWiJAS59aHu5Tj7MMBQyxbIktFo1d0kS86mmMtZsmNGYOlknB6wkCTA8mWS5EtPz888+cxXc6vfkPmAqYcsAMxbFUmvZX77wzlhF82SqU4Pf++++PmjeqhBg4OS1QYCldAs4NTgvzrTzDWuxY435wwPYtMweMNXdk3NjzYd8GTHRWyhyE1xboxUzaS47JLieHwhmcvb0oYIvJz35Z0nP4o14YNxcEznenGVXKCTAi5VYCC3CnrXOS//dKJiP4j7entxCk/Bzet1rJAL463D9h42K9LSdmnUhE3yuWSNFA/f6WQsROh9HoyAHbRz1glptzh/JkKdqAqFfrjZD5RFrtZ+3glcNlvX1mCIA3GvYegQ54TM85Ltg9YsNNZu0KAXmz8uzgrtMss0/W7z8v64YdvKQHwElaL1xiK4dJFv2RvPYrURe513dynfYtgXD/8Kj7YFM5BoG6xEs2kyXvx8k6IYFzWcRxEjIKt0/5eezgqSzxqYVRahFsymc06jKHIaJLCLC94zr//XcBXno3F3I/IbOxYHkMalnk2SzfMp4t68yBSmP5lTVH6HUB9VxscXljxzGwLDXA7DjJJZ7F6znVmTRsb1/+qTwA828Z+FjbWvYrGQcDShICFPLw10C9wSHDbrchbBqArR3HZtk2cL779aOmAnJ/1gnZjSbAtv16ouWDVc7WHvIzM1iaeCsDjIYduIOvyPLl9wh4wF0Tio1NEVCt5lZxYY5arzpZcovV5Zq8rAALlfZdi9pDFC3whdktyw7ekLWPnZBzNDDm+xxi12FXjkbylizKkfLnxwZgTy5R4h18fy9YvB8yn4j0DTMFkUkBzaLN4hjxyJTAr2x5ogwxPp0sws4Q/nCypzxzmQG+1yHjxNCJjBik/PDFGWT+fV6pMMpEWNPSsDUBey2lv3xoBhHKDzAb5AS7XEaQRdPz66+/Tpp5dzwnpK/u7p7HI0QMouWDyDf6scQXpn+Nj5fCmZSl38G7eWV94meIKB3YDwf9s4HsSgC+JeYLy+e+I7nK1iZbB2Ap/radEQGbP3Dt3o4uwZvmK64JFQd6pxcgmgg+Qh8BmO87vaFg7Ro41zl5CppN2dNT+96w43wA1vn6EMDTegX6SYTLaVeS61r7KQu7Um52pifAHW1tJ7cawCiIkn4ygbGDbwqcb+nsaBrnAmJ0EHblwoaLzQNg5tu6BQH+2DERoSbYLBiUfZDmK2Yi3j7/BTRF9Ip9CWAUTfn/DwLm+o30o6BkNHKG0/KP2jq6t+Kl0cmXcwT4b1HaxuoLAFPawTEODCtmhKD0TBK7RI0/PM3b1dnZvSM7OSFNggdcIfaLy73nbH2AbaqOUpjbA+Z6MCoZTQt0pXqXNCfojATTas5IdgZn+mJ9ZAefYYRLlwt8We4MhBfwOm8bIBd4rbSzuo00CUvEOAAiZZKWazWAKfriFc4kyz9XicP+jS+6Vg34rCvAYoot0GoAW1Qd6EeBO3iXGJNop0GZGAT4iwPY4Iq1AMBSI3Mhr0C/YDVvzA6eNYngJl4tRLI5cF/KGfO9IyBjtRLAOIgsogME/ZD5BJNpggHmQykP959c0+WqGGAHrTdtOYDDqTofhSTJx1CaACiVmaEPMJU3wPo2Ht/qAFvsR0zQkNojYFGXGpY8BEEIb4ApJ9jqAFtUHanDOXkIN7ynq+uaaIDxtvTyJn6QlqcrovYOLwcA+a5yr7+bGWCtoUU9MbrQLO4U6AeDs/Ls4LMy3OBjkrttdmY+gHGZQnZvNoAV1E9kjc6jQFyGemI4OZYOtIHXjQZYPnxQxrfoLbp9ebQKAGBb5JcZYC3P39PzBlWFtIDZUHVusbBEIQRxrVc1Ql8EWIn8b9IEC8J+niq6pO6EBGfylGTCVFoy8IvejPqfI4aL0X53MwDM4mrVm508a1ozp3e9svBsQ/umt5LhB98oCuD29rfKCrD65R+mRieZE57Vc2uSXgvHO6CuGEfjO5izeQCGm/tv6EJop7SZPQPhnZ0d9xcNcK3/+EELr64FqJ5FVXEmAaoIeM3E8DO37OGgvVJ63hFgRP5ZRQGsvQavFY12JepcOye+TUoNbfn9BUDNGZE6x+OBHi+eymJrl94Aaz3mD4hty6Kt4pkQp1ki0xLxYS0B1ZU473DoH9mqAJMNoHlYmDPh/ly7itDMslP3o/J8LlDt9N1V/FvftQDA+NFlvnm1iq3LoPEmJSQE1MPpy1iTUTyvOmLwlmTl+cr4yuGhO+67777R/AH2HzgxKFkhgB4TkAzn1joQgmJhre+0edW4ohG+m/fhP/3008kSCAg7lwFgCIk07+LokuvdRhRW0w42l7n1GeLNzLLznn766THFszKjgPyTt+gRE2XDRgGMKEf8yqIeX8RONepmP6/tDsb27g72cpaHkMJdU+nPL8Bb5gkw/1YkwLhdaXujlerfb9BORbt/n3omBmsj/yDCgRcnABjs1o1565oJYJwPKn5P1CZa3Q3s+X8Jz2Jo975Dazz2hACjBn1XmQHWvhLzyoIeS3y7iJ1q+LZvo8oBzTfrCqZBJTkzBBit93F22QBWX/lSBN8bulO1kRat6SS3aLzi0LSTwV8KAYa+wFqQNPMQhWr9pNL2eQCmtyANl2lxC1GtwU2z3tR48cwR+tDwHX//PXNAnDmcbSkPl9iSXTTotQ0x+EwA8W6HQed4/fXXJ470iZ+tjSl/LkT82r0GLxSrZIGYeDFVeeXIO1S1+Hvr3cp8Wbk6E2K5OxsPODH+3lgfqzg/EKse3VuKtldvr0mTENI7I9Z5XMS3xp07jIp2/ucxiWehzm91EX4bDnBxncod7dXdJHth7BgRLEfJalQBxFsVsj7u7VxpsBF4Y0Q8u//vpgXYtldPoK1cjM0NKY+MQ/oRZwgTLlOUZj0KpkXom6U1JNuaHWC1Vy+CXBdjr2rA/2BAlaun0CBDgEiZEgUiVHRQQcDol7tXWQFWe/VW+eMaFKAJPdrQRQTUrRDjkY2hvyq8NT5Bcs0+vCThv4c0amKekqTZtv377/Up93m3gabNk/Qb/O6778aNad9L02iZ4344bjnTXj50BS9gRx4u5XHvShFFU6SxHeQztw36JVLm4R6PNMBePepvsTtjzlWZY0FKAnva3dQQbQjAGN7yhu+SIloBcYyUlnej0kUzC5kMznRR9iolo2JEIbxo+iLXy0OGS3WIRo201Ayp1PIeIKa0vQO48eXBv2kQwCza/+3V7nh7dXL57E4yhw/nymZ5LjZE2YZU67lHF/LWNBebiMFZ8TYVBbDaq8/J7xvHdOZGwULRkjnuqHdzavQbuQ987JU0F7iBwwBGz7VT08jaND7my9QLYOxVje0eGGOv0otJRPeisCkwkQoIRKADHGk/a4kAZtRkiEZ5jGEbbk32QIoWfUZsa3WaZckf5yD4EXGuTq89nb50az5t94G6VV6khQs3h7zSUMnAs6q7S87xRoiiBH/2UYF+YMjra8ifR40IjeLc30vmeAlxXoAn7AV6L9r9K0oOcELVnhUD51k5w1mForNtjB8YjV4WeWOZ4yG52gryhF0K30uPraYciNZT076gXFPnSWfVanxvYK/WpElHxMs3IpXlWOgi4sQ8L1IBp4laFc0/iO/WZKR84c9EJE8WCrDaqxfI2z976FlFzhWfG4B7VSvIvj5ZpNaMTbpbbda/fLknDDv09Sz2p9JsbqPYKRptRCLd1Dhj5Pe3CgL1P7ke1V5UfL/WHXiy5HrFWAyAG763EGXwfYVmhANDbd6Ogsokfaahw6k0h7hvDNEQ58KZYcQ5r7HFbbBz/wbO+YJZkavri9o3hyzAyobZwULtmyPgMR9lhWx71d0Z8Q7FauTlnVB3azWIGxux4G4KoWYNcGiX0n1ELr7CZwssRXgpzAp1vVYjodv39cYCdspILRaGjUsf/gHJaAWdrW+QG0Rv/QrFbPHSBywngFzzDeiEkB2zovybktEch90C9wcI/zQjSelhUQ3DJTkpdrCxwD+IJroCvCdPXnMAg2PLfDU6qoF/eX6TZVl8Lclzax0dsyrVqBpO4pqAQHcDecz3EvxQwkI16kGkp9m0v2ljxoU/UGfElBUCxYCMK/HKejMj5LpRriWVx1yNIgfmhyz+83U4WzFvDsAZUa1yYwfcLAh4P3kwI+S6RMybBcrHjKg8XQshTiOZESR+bS+prONUK1niITtvezTcAGYEid2zasSpGUY1ekSztpgRcpHpsK5co1er1YRDu6DelsCMOL5d6DmVo78FBgRzcRy+pgTzFeiqVq1Ki43KZo0b/wP23paVqC/D3gAAAABJRU5ErkJggg=="
  93585. /***/ }),
  93586. /* 10 */
  93587. /***/ (function(module, exports) {
  93588. module.exports = "<style>viewer{position:relative;overflow:hidden;flex:1;z-index:1;justify-content:center;align-items:center;width:100%;height:100%}.babylonjs-canvas{flex:1;width:100%;height:100%;touch-action:none}</style> <canvas class=babylonjs-canvas id={{canvasId}}> </canvas> <nav-bar></nav-bar>";
  93589. /***/ }),
  93590. /* 11 */
  93591. /***/ (function(module, exports) {
  93592. module.exports = "<style>overlay{position:absolute;z-index:99;opacity:0;display:flex;justify-content:center;align-items:center;-webkit-transition:opacity 1s ease;-moz-transition:opacity 1s ease;transition:opacity 1s ease}.overlay-item{width:100%;height:100%;display:none;align-items:center;justify-content:center;background-color:rgba(121,121,121,.3)}error.overlay-item{background-color:rgba(121,121,121,1)}div#close-button{position:absolute;top:10px;right:10px;width:30px;height:30px;cursor:pointer}div#close-button img{width:100%}</style> <div id=close-button> <img src={{closeImage}} alt={{closeText}}> </div> <help class=overlay-item></help> <error class=overlay-item></error> <share class=overlay-item></share>";
  93593. /***/ }),
  93594. /* 12 */
  93595. /***/ (function(module, exports) {
  93596. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAAt0lEQVR42u2WAQbDQBBFQ9IbRtDcrrqK3LBbXrEH6OuHEPMBjPd2xHyZKtdNpcLMg11Pr7y4/YdvwIdd4jtw4BU0Rjrbz9mNzkjzgpU3wNhCvH5M3i1fKzzeK3K8V+R4r8jxTpHjlULhc0WOd8fU6e4I8y3y13tFjHel4GswwAvFSR/ZN6Zv2gjvmzbGhwqPzxUenys83is8Pld4vFac/9sy8/SVNrbgYJl8WGhsvkpoA1+pVK6ZLyLNXm2txsT5AAAAAElFTkSuQmCC"
  93597. /***/ }),
  93598. /* 13 */
  93599. /***/ (function(module, exports) {
  93600. module.exports = "Error loading the model";
  93601. /***/ }),
  93602. /* 14 */
  93603. /***/ (function(module, exports, __webpack_require__) {
  93604. "use strict";
  93605. Object.defineProperty(exports, "__esModule", { value: true });
  93606. var babylonjs_1 = __webpack_require__(0);
  93607. var viewerModel_1 = __webpack_require__(15);
  93608. var ModelLoader = (function () {
  93609. function ModelLoader(_viewer) {
  93610. this._viewer = _viewer;
  93611. this._disposed = false;
  93612. this._loaders = [];
  93613. this._loadId = 0;
  93614. }
  93615. ModelLoader.prototype.load = function (modelConfiguration) {
  93616. var model = new viewerModel_1.ViewerModel(this._viewer, modelConfiguration);
  93617. if (!modelConfiguration.url) {
  93618. model.state = viewerModel_1.ModelState.ERROR;
  93619. babylonjs_1.Tools.Error("No URL provided");
  93620. return model;
  93621. }
  93622. var filename = babylonjs_1.Tools.GetFilename(modelConfiguration.url) || modelConfiguration.url;
  93623. var base = modelConfiguration.root || babylonjs_1.Tools.GetFolderPath(modelConfiguration.url);
  93624. var plugin = modelConfiguration.loader;
  93625. model.loader = babylonjs_1.SceneLoader.ImportMesh(undefined, base, filename, this._viewer.scene, function (meshes, particleSystems, skeletons, animationGroups) {
  93626. meshes.forEach(function (mesh) {
  93627. babylonjs_1.Tags.AddTagsTo(mesh, "viewerMesh");
  93628. });
  93629. model.meshes = meshes;
  93630. model.particleSystems = particleSystems;
  93631. model.skeletons = skeletons;
  93632. for (var _i = 0, animationGroups_1 = animationGroups; _i < animationGroups_1.length; _i++) {
  93633. var animationGroup = animationGroups_1[_i];
  93634. model.addAnimationGroup(animationGroup);
  93635. }
  93636. model.initAnimations();
  93637. model.onLoadedObservable.notifyObserversWithPromise(model);
  93638. }, function (progressEvent) {
  93639. model.onLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  93640. }, function (e, m, exception) {
  93641. model.state = viewerModel_1.ModelState.ERROR;
  93642. babylonjs_1.Tools.Error("Load Error: There was an error loading the model. " + m);
  93643. model.onLoadErrorObservable.notifyObserversWithPromise({ message: m, exception: exception });
  93644. }, plugin);
  93645. if (model.loader.name === "gltf") {
  93646. var gltfLoader = model.loader;
  93647. gltfLoader.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.NONE;
  93648. }
  93649. model.loadId = this._loadId++;
  93650. this._loaders.push(model.loader);
  93651. return model;
  93652. };
  93653. ModelLoader.prototype.cancelLoad = function (model) {
  93654. var loader = model.loader || this._loaders[model.loadId];
  93655. if (loader && loader.name === "gltf") {
  93656. var gltfLoader = loader;
  93657. gltfLoader.dispose();
  93658. model.state = viewerModel_1.ModelState.CANCELED;
  93659. }
  93660. else {
  93661. babylonjs_1.Tools.Warn("This type of loader cannot cancel the request");
  93662. }
  93663. };
  93664. ModelLoader.prototype.dispose = function () {
  93665. this._loaders.forEach(function (loader) {
  93666. if (loader.name === "gltf") {
  93667. loader.dispose();
  93668. }
  93669. });
  93670. this._loaders.length = 0;
  93671. this._disposed = true;
  93672. };
  93673. return ModelLoader;
  93674. }());
  93675. exports.ModelLoader = ModelLoader;
  93676. /***/ }),
  93677. /* 15 */
  93678. /***/ (function(module, exports, __webpack_require__) {
  93679. "use strict";
  93680. Object.defineProperty(exports, "__esModule", { value: true });
  93681. var babylonjs_1 = __webpack_require__(0);
  93682. var modelAnimation_1 = __webpack_require__(16);
  93683. var deepmerge = __webpack_require__(2);
  93684. var ModelState;
  93685. (function (ModelState) {
  93686. ModelState[ModelState["INIT"] = 0] = "INIT";
  93687. ModelState[ModelState["LOADING"] = 1] = "LOADING";
  93688. ModelState[ModelState["LOADED"] = 2] = "LOADED";
  93689. ModelState[ModelState["CANCELED"] = 3] = "CANCELED";
  93690. ModelState[ModelState["ERROR"] = 4] = "ERROR";
  93691. })(ModelState = exports.ModelState || (exports.ModelState = {}));
  93692. var ViewerModel = (function () {
  93693. function ViewerModel(_viewer, modelConfiguration) {
  93694. this._viewer = _viewer;
  93695. this.meshes = [];
  93696. this.particleSystems = [];
  93697. this.skeletons = [];
  93698. this.onLoadedObservable = new babylonjs_1.Observable();
  93699. this.onLoadErrorObservable = new babylonjs_1.Observable();
  93700. this.onLoadProgressObservable = new babylonjs_1.Observable();
  93701. this.onAfterConfigure = new babylonjs_1.Observable();
  93702. this.state = ModelState.INIT;
  93703. this._animations = [];
  93704. this._modelConfiguration = deepmerge({}, modelConfiguration);
  93705. this._viewer.models.push(this);
  93706. }
  93707. Object.defineProperty(ViewerModel.prototype, "configuration", {
  93708. get: function () {
  93709. return this._modelConfiguration;
  93710. },
  93711. set: function (newConfiguration) {
  93712. this._modelConfiguration = newConfiguration;
  93713. this._configureModel();
  93714. },
  93715. enumerable: true,
  93716. configurable: true
  93717. });
  93718. ViewerModel.prototype.updateConfiguration = function (newConfiguration) {
  93719. this._modelConfiguration = deepmerge(this._modelConfiguration, newConfiguration);
  93720. this._configureModel();
  93721. };
  93722. ViewerModel.prototype.initAnimations = function () {
  93723. var _this = this;
  93724. this._animations.forEach(function (a) {
  93725. a.dispose();
  93726. });
  93727. this._animations.length = 0;
  93728. if (this.loader.name !== 'gltf') {
  93729. this.skeletons.forEach(function (skeleton, idx) {
  93730. var ag = new babylonjs_1.AnimationGroup("animation-" + idx, _this._viewer.scene);
  93731. skeleton.getAnimatables().forEach(function (a) {
  93732. if (a.animations[0]) {
  93733. ag.addTargetedAnimation(a.animations[0], a);
  93734. }
  93735. });
  93736. _this.addAnimationGroup(ag);
  93737. });
  93738. }
  93739. if (!this._modelConfiguration)
  93740. return;
  93741. if (this._modelConfiguration.animation) {
  93742. if (this._modelConfiguration.animation.playOnce) {
  93743. this._animations.forEach(function (a) {
  93744. a.playMode = modelAnimation_1.AnimationPlayMode.ONCE;
  93745. });
  93746. }
  93747. if (this._modelConfiguration.animation.autoStart && this._animations.length) {
  93748. var animationName = this._modelConfiguration.animation.autoStart === true ?
  93749. this._animations[0].name : this._modelConfiguration.animation.autoStart;
  93750. this.playAnimation(animationName);
  93751. }
  93752. }
  93753. };
  93754. ViewerModel.prototype.addAnimationGroup = function (animationGroup) {
  93755. this._animations.push(new modelAnimation_1.GroupModelAnimation(animationGroup));
  93756. };
  93757. ViewerModel.prototype.getAnimations = function () {
  93758. return this._animations;
  93759. };
  93760. ViewerModel.prototype.getAnimationNames = function () {
  93761. return this._animations.map(function (a) { return a.name; });
  93762. };
  93763. ViewerModel.prototype._getAnimationByName = function (name) {
  93764. var filtered = this._animations.filter(function (a) { return a.name === name; });
  93765. if (filtered.length === 1) {
  93766. return filtered[0];
  93767. }
  93768. else {
  93769. return null;
  93770. }
  93771. };
  93772. ViewerModel.prototype.playAnimation = function (name) {
  93773. var animation = this._getAnimationByName(name);
  93774. if (animation) {
  93775. if (this.currentAnimation) {
  93776. this.currentAnimation.stop();
  93777. }
  93778. this.currentAnimation = animation;
  93779. animation.start();
  93780. return animation;
  93781. }
  93782. else {
  93783. throw new Error("animation not found - " + name);
  93784. }
  93785. };
  93786. ViewerModel.prototype._configureModel = function () {
  93787. var meshesWithNoParent = this.meshes.filter(function (m) { return !m.parent; });
  93788. var updateMeshesWithNoParent = function (variable, value, param) {
  93789. meshesWithNoParent.forEach(function (mesh) {
  93790. if (param) {
  93791. mesh[variable][param] = value;
  93792. }
  93793. else {
  93794. mesh[variable] = value;
  93795. }
  93796. });
  93797. };
  93798. var updateXYZ = function (variable, configValues) {
  93799. if (configValues.x !== undefined) {
  93800. updateMeshesWithNoParent(variable, configValues.x, 'x');
  93801. }
  93802. if (configValues.y !== undefined) {
  93803. updateMeshesWithNoParent(variable, configValues.y, 'y');
  93804. }
  93805. if (configValues.z !== undefined) {
  93806. updateMeshesWithNoParent(variable, configValues.z, 'z');
  93807. }
  93808. if (configValues.w !== undefined) {
  93809. updateMeshesWithNoParent(variable, configValues.w, 'w');
  93810. }
  93811. };
  93812. if (this._modelConfiguration.position) {
  93813. updateXYZ('position', this._modelConfiguration.position);
  93814. }
  93815. if (this._modelConfiguration.rotation) {
  93816. if (this._modelConfiguration.rotation.w) {
  93817. meshesWithNoParent.forEach(function (mesh) {
  93818. if (!mesh.rotationQuaternion) {
  93819. mesh.rotationQuaternion = new babylonjs_1.Quaternion();
  93820. }
  93821. });
  93822. updateXYZ('rotationQuaternion', this._modelConfiguration.rotation);
  93823. }
  93824. else {
  93825. updateXYZ('rotation', this._modelConfiguration.rotation);
  93826. }
  93827. }
  93828. if (this._modelConfiguration.scaling) {
  93829. updateXYZ('scaling', this._modelConfiguration.scaling);
  93830. }
  93831. if (this._modelConfiguration.castShadow) {
  93832. this.meshes.forEach(function (mesh) {
  93833. babylonjs_1.Tags.AddTagsTo(mesh, 'castShadow');
  93834. });
  93835. }
  93836. if (this._modelConfiguration.normalize) {
  93837. var center = false;
  93838. var unitSize = false;
  93839. var parentIndex = void 0;
  93840. if (this._modelConfiguration.normalize === true) {
  93841. center = true;
  93842. unitSize = true;
  93843. parentIndex = 0;
  93844. }
  93845. else {
  93846. center = !!this._modelConfiguration.normalize.center;
  93847. unitSize = !!this._modelConfiguration.normalize.unitSize;
  93848. parentIndex = this._modelConfiguration.normalize.parentIndex;
  93849. }
  93850. var meshesToNormalize = [];
  93851. if (parentIndex !== undefined) {
  93852. meshesToNormalize.push(this.meshes[parentIndex]);
  93853. }
  93854. else {
  93855. meshesToNormalize = meshesWithNoParent;
  93856. }
  93857. if (unitSize) {
  93858. meshesToNormalize.forEach(function (mesh) {
  93859. mesh.normalizeToUnitCube(true);
  93860. mesh.computeWorldMatrix(true);
  93861. });
  93862. }
  93863. if (center) {
  93864. meshesToNormalize.forEach(function (mesh) {
  93865. var boundingInfo = mesh.getHierarchyBoundingVectors(true);
  93866. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  93867. var halfSizeVec = sizeVec.scale(0.5);
  93868. var center = boundingInfo.min.add(halfSizeVec);
  93869. mesh.position = center.scale(-1);
  93870. mesh.position.y += halfSizeVec.y;
  93871. mesh.computeWorldMatrix(true);
  93872. });
  93873. }
  93874. }
  93875. this.onAfterConfigure.notifyObservers(this);
  93876. };
  93877. ViewerModel.prototype.dispose = function () {
  93878. this.onAfterConfigure.clear();
  93879. this.onLoadedObservable.clear();
  93880. this.onLoadErrorObservable.clear();
  93881. this.onLoadProgressObservable.clear();
  93882. if (this.loader && this.loader.name === "gltf") {
  93883. this.loader.dispose();
  93884. }
  93885. this.particleSystems.forEach(function (ps) { return ps.dispose(); });
  93886. this.particleSystems.length = 0;
  93887. this.skeletons.forEach(function (s) { return s.dispose(); });
  93888. this.skeletons.length = 0;
  93889. this._animations.forEach(function (ag) { return ag.dispose(); });
  93890. this._animations.length = 0;
  93891. this.meshes.forEach(function (m) { return m.dispose(); });
  93892. this.meshes.length = 0;
  93893. this._viewer.models.splice(this._viewer.models.indexOf(this), 1);
  93894. };
  93895. return ViewerModel;
  93896. }());
  93897. exports.ViewerModel = ViewerModel;
  93898. /***/ }),
  93899. /* 16 */
  93900. /***/ (function(module, exports, __webpack_require__) {
  93901. "use strict";
  93902. Object.defineProperty(exports, "__esModule", { value: true });
  93903. var AnimationPlayMode;
  93904. (function (AnimationPlayMode) {
  93905. AnimationPlayMode[AnimationPlayMode["ONCE"] = 0] = "ONCE";
  93906. AnimationPlayMode[AnimationPlayMode["LOOP"] = 1] = "LOOP";
  93907. })(AnimationPlayMode = exports.AnimationPlayMode || (exports.AnimationPlayMode = {}));
  93908. var AnimationState;
  93909. (function (AnimationState) {
  93910. AnimationState[AnimationState["INIT"] = 0] = "INIT";
  93911. AnimationState[AnimationState["PLAYING"] = 1] = "PLAYING";
  93912. AnimationState[AnimationState["PAUSED"] = 2] = "PAUSED";
  93913. AnimationState[AnimationState["STOPPED"] = 3] = "STOPPED";
  93914. AnimationState[AnimationState["ENDED"] = 4] = "ENDED";
  93915. })(AnimationState = exports.AnimationState || (exports.AnimationState = {}));
  93916. var GroupModelAnimation = (function () {
  93917. function GroupModelAnimation(_animationGroup) {
  93918. var _this = this;
  93919. this._animationGroup = _animationGroup;
  93920. this._state = AnimationState.INIT;
  93921. this._playMode = AnimationPlayMode.LOOP;
  93922. this._animationGroup.onAnimationEndObservable.add(function () {
  93923. _this.stop();
  93924. _this._state = AnimationState.ENDED;
  93925. });
  93926. }
  93927. Object.defineProperty(GroupModelAnimation.prototype, "name", {
  93928. get: function () {
  93929. return this._animationGroup.name;
  93930. },
  93931. enumerable: true,
  93932. configurable: true
  93933. });
  93934. Object.defineProperty(GroupModelAnimation.prototype, "state", {
  93935. get: function () {
  93936. return this._state;
  93937. },
  93938. enumerable: true,
  93939. configurable: true
  93940. });
  93941. Object.defineProperty(GroupModelAnimation.prototype, "speedRatio", {
  93942. get: function () {
  93943. return this._animationGroup.speedRatio;
  93944. },
  93945. set: function (value) {
  93946. this._animationGroup.speedRatio = value;
  93947. },
  93948. enumerable: true,
  93949. configurable: true
  93950. });
  93951. Object.defineProperty(GroupModelAnimation.prototype, "frames", {
  93952. get: function () {
  93953. var animationFrames = this._animationGroup.targetedAnimations.map(function (ta) {
  93954. var keys = ta.animation.getKeys();
  93955. return keys[keys.length - 1].frame;
  93956. });
  93957. return Math.max.apply(null, animationFrames);
  93958. },
  93959. enumerable: true,
  93960. configurable: true
  93961. });
  93962. Object.defineProperty(GroupModelAnimation.prototype, "currentFrame", {
  93963. get: function () {
  93964. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  93965. var animatable = this._animationGroup.animatables[i];
  93966. var animations = animatable.getAnimations();
  93967. if (!animations || !animations.length) {
  93968. continue;
  93969. }
  93970. for (var idx = 0; idx < animations.length; ++idx) {
  93971. if (animations[idx].currentFrame) {
  93972. return animations[idx].currentFrame;
  93973. }
  93974. }
  93975. }
  93976. return 0;
  93977. },
  93978. enumerable: true,
  93979. configurable: true
  93980. });
  93981. Object.defineProperty(GroupModelAnimation.prototype, "fps", {
  93982. get: function () {
  93983. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  93984. var animatable = this._animationGroup.animatables[i];
  93985. var animations = animatable.getAnimations();
  93986. if (!animations || !animations.length) {
  93987. continue;
  93988. }
  93989. for (var idx = 0; idx < animations.length; ++idx) {
  93990. if (animations[idx].animation && animations[idx].animation.framePerSecond) {
  93991. return animations[idx].animation.framePerSecond;
  93992. }
  93993. }
  93994. }
  93995. return 0;
  93996. },
  93997. enumerable: true,
  93998. configurable: true
  93999. });
  94000. Object.defineProperty(GroupModelAnimation.prototype, "playMode", {
  94001. get: function () {
  94002. return this._playMode;
  94003. },
  94004. set: function (value) {
  94005. if (value === this._playMode) {
  94006. return;
  94007. }
  94008. this._playMode = value;
  94009. if (this.state === AnimationState.PLAYING) {
  94010. this._animationGroup.play(this._playMode === AnimationPlayMode.LOOP);
  94011. }
  94012. else {
  94013. this._animationGroup.reset();
  94014. this._state = AnimationState.INIT;
  94015. }
  94016. },
  94017. enumerable: true,
  94018. configurable: true
  94019. });
  94020. GroupModelAnimation.prototype.reset = function () {
  94021. this._animationGroup.reset();
  94022. };
  94023. GroupModelAnimation.prototype.restart = function () {
  94024. this._animationGroup.restart();
  94025. };
  94026. GroupModelAnimation.prototype.goToFrame = function (frameNumber) {
  94027. this._animationGroup['_animatables'].forEach(function (a) {
  94028. a.goToFrame(frameNumber);
  94029. });
  94030. };
  94031. GroupModelAnimation.prototype.start = function () {
  94032. this._animationGroup.start(this.playMode === AnimationPlayMode.LOOP, this.speedRatio);
  94033. if (this._animationGroup.isStarted) {
  94034. this._state = AnimationState.PLAYING;
  94035. }
  94036. };
  94037. GroupModelAnimation.prototype.pause = function () {
  94038. this._animationGroup.pause();
  94039. this._state = AnimationState.PAUSED;
  94040. };
  94041. GroupModelAnimation.prototype.stop = function () {
  94042. this._animationGroup.stop();
  94043. if (!this._animationGroup.isStarted) {
  94044. this._state = AnimationState.STOPPED;
  94045. }
  94046. };
  94047. GroupModelAnimation.prototype.dispose = function () {
  94048. this._animationGroup.dispose();
  94049. };
  94050. return GroupModelAnimation;
  94051. }());
  94052. exports.GroupModelAnimation = GroupModelAnimation;
  94053. /***/ }),
  94054. /* 17 */
  94055. /***/ (function(module, exports, __webpack_require__) {
  94056. module.exports = __webpack_require__(18);
  94057. /***/ }),
  94058. /* 18 */
  94059. /***/ (function(module, exports, __webpack_require__) {
  94060. "use strict";
  94061. Object.defineProperty(exports, "__esModule", { value: true });
  94062. var mappers_1 = __webpack_require__(1);
  94063. exports.mapperManager = mappers_1.mapperManager;
  94064. var viewerManager_1 = __webpack_require__(4);
  94065. exports.viewerManager = viewerManager_1.viewerManager;
  94066. var defaultViewer_1 = __webpack_require__(5);
  94067. exports.DefaultViewer = defaultViewer_1.DefaultViewer;
  94068. var viewer_1 = __webpack_require__(6);
  94069. exports.AbstractViewer = viewer_1.AbstractViewer;
  94070. var modelLoader_1 = __webpack_require__(14);
  94071. exports.ModelLoader = modelLoader_1.ModelLoader;
  94072. var viewerModel_1 = __webpack_require__(15);
  94073. exports.ViewerModel = viewerModel_1.ViewerModel;
  94074. exports.ModelState = viewerModel_1.ModelState;
  94075. var modelAnimation_1 = __webpack_require__(16);
  94076. exports.AnimationPlayMode = modelAnimation_1.AnimationPlayMode;
  94077. exports.AnimationState = modelAnimation_1.AnimationState;
  94078. var babylonjs_1 = __webpack_require__(0);
  94079. __webpack_require__(34);
  94080. __webpack_require__(35);
  94081. var initializer_1 = __webpack_require__(36);
  94082. exports.InitTags = initializer_1.InitTags;
  94083. babylonjs_1.PromisePolyfill.Apply();
  94084. exports.disableInit = false;
  94085. document.addEventListener("DOMContentLoaded", init);
  94086. function init(event) {
  94087. document.removeEventListener("DOMContentLoaded", init);
  94088. if (exports.disableInit)
  94089. return;
  94090. initializer_1.InitTags();
  94091. }
  94092. function disposeAll() {
  94093. viewerManager_1.viewerManager.dispose();
  94094. mappers_1.mapperManager.dispose();
  94095. }
  94096. exports.disposeAll = disposeAll;
  94097. /***/ }),
  94098. /* 19 */
  94099. /***/ (function(module, exports) {
  94100. var g;
  94101. // This works in non-strict mode
  94102. g = (function() {
  94103. return this;
  94104. })();
  94105. try {
  94106. // This works if eval is allowed (see CSP)
  94107. g = g || Function("return this")() || (1,eval)("this");
  94108. } catch(e) {
  94109. // This works if the window reference is available
  94110. if(typeof window === "object")
  94111. g = window;
  94112. }
  94113. // g can still be undefined, but nothing to do about it...
  94114. // We return undefined, instead of nothing here, so it's
  94115. // easier to handle this case. if(!global) { ...}
  94116. module.exports = g;
  94117. /***/ }),
  94118. /* 20 */
  94119. /***/ (function(module, exports) {
  94120. if(typeof CANNON === 'undefined') {var e = new Error("Cannot find module \"CANNON\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  94121. module.exports = CANNON;
  94122. /***/ }),
  94123. /* 21 */
  94124. /***/ (function(module, exports) {
  94125. if(typeof OIMO === 'undefined') {var e = new Error("Cannot find module \"OIMO\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  94126. module.exports = OIMO;
  94127. /***/ }),
  94128. /* 22 */
  94129. /***/ (function(module, exports) {
  94130. if(typeof earcut === 'undefined') {var e = new Error("Cannot find module \"earcut\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  94131. module.exports = earcut;
  94132. /***/ }),
  94133. /* 23 */
  94134. /***/ (function(module, exports, __webpack_require__) {
  94135. "use strict";
  94136. Object.defineProperty(exports, "__esModule", { value: true });
  94137. var babylonjs_1 = __webpack_require__(0);
  94138. var helper_1 = __webpack_require__(3);
  94139. var TemplateManager = (function () {
  94140. function TemplateManager(containerElement) {
  94141. this.containerElement = containerElement;
  94142. this.templates = {};
  94143. this.onTemplateInit = new babylonjs_1.Observable();
  94144. this.onTemplateLoaded = new babylonjs_1.Observable();
  94145. this.onTemplateStateChange = new babylonjs_1.Observable();
  94146. this.onAllLoaded = new babylonjs_1.Observable();
  94147. this.onEventTriggered = new babylonjs_1.Observable();
  94148. this.eventManager = new eventManager_1.EventManager(this);
  94149. }
  94150. TemplateManager.prototype.initTemplate = function (templates) {
  94151. var _this = this;
  94152. var internalInit = function (dependencyMap, name, parentTemplate) {
  94153. var template = _this.templates[name];
  94154. var childrenTemplates = Object.keys(dependencyMap).map(function (childName) {
  94155. return internalInit(dependencyMap[childName], childName, template);
  94156. });
  94157. var addToParent = function () {
  94158. var containingElement = parentTemplate && parentTemplate.parent.querySelector(helper_1.camelToKebab(name)) || _this.containerElement;
  94159. template.appendTo(containingElement);
  94160. _this._checkLoadedState();
  94161. };
  94162. if (parentTemplate && !parentTemplate.parent) {
  94163. parentTemplate.onAppended.add(function () {
  94164. addToParent();
  94165. });
  94166. }
  94167. else {
  94168. addToParent();
  94169. }
  94170. return template;
  94171. };
  94172. return this._buildHTMLTree(templates).then(function (htmlTree) {
  94173. if (_this.templates['main']) {
  94174. internalInit(htmlTree, 'main');
  94175. }
  94176. else {
  94177. _this._checkLoadedState();
  94178. }
  94179. return;
  94180. });
  94181. };
  94182. TemplateManager.prototype._buildHTMLTree = function (templates) {
  94183. var _this = this;
  94184. var promises = Object.keys(templates).map(function (name) {
  94185. if (!templates[name])
  94186. return Promise.resolve(false);
  94187. var template = new Template(name, templates[name]);
  94188. template.onLoaded.add(function () {
  94189. _this.onTemplateLoaded.notifyObservers(template);
  94190. });
  94191. template.onStateChange.add(function () {
  94192. _this.onTemplateStateChange.notifyObservers(template);
  94193. });
  94194. _this.onTemplateInit.notifyObservers(template);
  94195. template.onEventTriggered.add(function (eventData) { return _this.onEventTriggered.notifyObservers(eventData); });
  94196. _this.templates[name] = template;
  94197. return template.initPromise;
  94198. });
  94199. return Promise.all(promises).then(function () {
  94200. var templateStructure = {};
  94201. var buildTree = function (parentObject, name) {
  94202. _this.templates[name].isInHtmlTree = true;
  94203. var childNodes = _this.templates[name].getChildElements().filter(function (n) { return !!_this.templates[n]; });
  94204. childNodes.forEach(function (element) {
  94205. parentObject[element] = {};
  94206. buildTree(parentObject[element], element);
  94207. });
  94208. };
  94209. if (_this.templates['main']) {
  94210. buildTree(templateStructure, "main");
  94211. }
  94212. return templateStructure;
  94213. });
  94214. };
  94215. TemplateManager.prototype.getCanvas = function () {
  94216. return this.containerElement.querySelector('canvas');
  94217. };
  94218. TemplateManager.prototype.getTemplate = function (name) {
  94219. return this.templates[name];
  94220. };
  94221. TemplateManager.prototype._checkLoadedState = function () {
  94222. var _this = this;
  94223. var done = Object.keys(this.templates).length === 0 || Object.keys(this.templates).every(function (key) {
  94224. return (_this.templates[key].isLoaded && !!_this.templates[key].parent) || !_this.templates[key].isInHtmlTree;
  94225. });
  94226. if (done) {
  94227. this.onAllLoaded.notifyObservers(this);
  94228. }
  94229. };
  94230. TemplateManager.prototype.dispose = function () {
  94231. var _this = this;
  94232. Object.keys(this.templates).forEach(function (template) {
  94233. _this.templates[template].dispose();
  94234. });
  94235. this.templates = {};
  94236. this.eventManager.dispose();
  94237. this.onTemplateInit.clear();
  94238. this.onAllLoaded.clear();
  94239. this.onEventTriggered.clear();
  94240. this.onTemplateLoaded.clear();
  94241. this.onTemplateStateChange.clear();
  94242. };
  94243. return TemplateManager;
  94244. }());
  94245. exports.TemplateManager = TemplateManager;
  94246. var Handlebars = __webpack_require__(24);
  94247. var eventManager_1 = __webpack_require__(25);
  94248. Handlebars.registerHelper('eachInMap', function (map, block) {
  94249. var out = '';
  94250. Object.keys(map).map(function (prop) {
  94251. var data = map[prop];
  94252. if (typeof data === 'object') {
  94253. data.id = data.id || prop;
  94254. out += block.fn(data);
  94255. }
  94256. else {
  94257. out += block.fn({ id: prop, value: data });
  94258. }
  94259. });
  94260. return out;
  94261. });
  94262. var Template = (function () {
  94263. function Template(name, _configuration) {
  94264. var _this = this;
  94265. this.name = name;
  94266. this._configuration = _configuration;
  94267. this.onLoaded = new babylonjs_1.Observable();
  94268. this.onAppended = new babylonjs_1.Observable();
  94269. this.onStateChange = new babylonjs_1.Observable();
  94270. this.onEventTriggered = new babylonjs_1.Observable();
  94271. this.loadRequests = [];
  94272. this.isLoaded = false;
  94273. this.isShown = false;
  94274. this.isInHtmlTree = false;
  94275. var htmlContentPromise = this._getTemplateAsHtml(_configuration);
  94276. this.initPromise = htmlContentPromise.then(function (htmlTemplate) {
  94277. if (htmlTemplate) {
  94278. _this._htmlTemplate = htmlTemplate;
  94279. var compiledTemplate = Handlebars.compile(htmlTemplate);
  94280. var config = _this._configuration.params || {};
  94281. var rawHtml = compiledTemplate(config);
  94282. _this._fragment = document.createRange().createContextualFragment(rawHtml);
  94283. _this.isLoaded = true;
  94284. _this.isShown = true;
  94285. _this.onLoaded.notifyObservers(_this);
  94286. }
  94287. return _this;
  94288. });
  94289. }
  94290. Template.prototype.updateParams = function (params) {
  94291. this._configuration.params = params;
  94292. if (this.isLoaded) {
  94293. this.dispose();
  94294. }
  94295. var compiledTemplate = Handlebars.compile(this._htmlTemplate);
  94296. var config = this._configuration.params || {};
  94297. var rawHtml = compiledTemplate(config);
  94298. this._fragment = document.createRange().createContextualFragment(rawHtml);
  94299. if (this.parent) {
  94300. this.appendTo(this.parent, true);
  94301. }
  94302. };
  94303. Object.defineProperty(Template.prototype, "configuration", {
  94304. get: function () {
  94305. return this._configuration;
  94306. },
  94307. enumerable: true,
  94308. configurable: true
  94309. });
  94310. Template.prototype.getChildElements = function () {
  94311. var childrenArray = [];
  94312. var children = this._fragment.children;
  94313. if (!children) {
  94314. children = this._fragment.querySelectorAll('*');
  94315. }
  94316. for (var i = 0; i < children.length; ++i) {
  94317. childrenArray.push(helper_1.kebabToCamel(children.item(i).nodeName.toLowerCase()));
  94318. }
  94319. return childrenArray;
  94320. };
  94321. Template.prototype.appendTo = function (parent, forceRemove) {
  94322. var _this = this;
  94323. if (this.parent) {
  94324. if (forceRemove) {
  94325. this.parent.removeChild(this._fragment);
  94326. }
  94327. else {
  94328. return;
  94329. }
  94330. }
  94331. this.parent = parent;
  94332. if (this._configuration.id) {
  94333. this.parent.id = this._configuration.id;
  94334. }
  94335. this._fragment = this.parent.appendChild(this._fragment);
  94336. setTimeout(function () {
  94337. _this._registerEvents();
  94338. _this.onAppended.notifyObservers(_this);
  94339. });
  94340. };
  94341. Template.prototype.show = function (visibilityFunction) {
  94342. var _this = this;
  94343. if (this._isHiding)
  94344. return Promise.resolve(this);
  94345. return Promise.resolve().then(function () {
  94346. _this._isShowing = true;
  94347. if (visibilityFunction) {
  94348. return visibilityFunction(_this);
  94349. }
  94350. else {
  94351. _this.parent.style.display = 'flex';
  94352. return _this;
  94353. }
  94354. }).then(function () {
  94355. _this.isShown = true;
  94356. _this._isShowing = false;
  94357. _this.onStateChange.notifyObservers(_this);
  94358. return _this;
  94359. });
  94360. };
  94361. Template.prototype.hide = function (visibilityFunction) {
  94362. var _this = this;
  94363. if (this._isShowing)
  94364. return Promise.resolve(this);
  94365. return Promise.resolve().then(function () {
  94366. _this._isHiding = true;
  94367. if (visibilityFunction) {
  94368. return visibilityFunction(_this);
  94369. }
  94370. else {
  94371. _this.parent.style.display = 'hide';
  94372. return _this;
  94373. }
  94374. }).then(function () {
  94375. _this.isShown = false;
  94376. _this._isHiding = false;
  94377. _this.onStateChange.notifyObservers(_this);
  94378. return _this;
  94379. });
  94380. };
  94381. Template.prototype.dispose = function () {
  94382. this.onAppended.clear();
  94383. this.onEventTriggered.clear();
  94384. this.onLoaded.clear();
  94385. this.onStateChange.clear();
  94386. this.isLoaded = false;
  94387. try {
  94388. this.parent.removeChild(this._fragment);
  94389. }
  94390. catch (e) {
  94391. }
  94392. this.loadRequests.forEach(function (request) {
  94393. request.abort();
  94394. });
  94395. if (this._registeredEvents) {
  94396. this._registeredEvents.forEach(function (evt) {
  94397. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  94398. });
  94399. }
  94400. delete this._fragment;
  94401. };
  94402. Template.prototype._getTemplateAsHtml = function (templateConfig) {
  94403. var _this = this;
  94404. if (!templateConfig) {
  94405. return Promise.reject('No templateConfig provided');
  94406. }
  94407. else if (templateConfig.html !== undefined) {
  94408. return Promise.resolve(templateConfig.html);
  94409. }
  94410. else {
  94411. var location_1 = this._getTemplateLocation(templateConfig);
  94412. if (helper_1.isUrl(location_1)) {
  94413. return new Promise(function (resolve, reject) {
  94414. var fileRequest = babylonjs_1.Tools.LoadFile(location_1, function (data) {
  94415. resolve(data);
  94416. }, undefined, undefined, false, function (request, error) {
  94417. reject(error);
  94418. });
  94419. _this.loadRequests.push(fileRequest);
  94420. });
  94421. }
  94422. else {
  94423. location_1 = location_1.replace('#', '');
  94424. var element = document.getElementById(location_1);
  94425. if (element) {
  94426. return Promise.resolve(element.innerHTML);
  94427. }
  94428. else {
  94429. return Promise.reject('Template ID not found');
  94430. }
  94431. }
  94432. }
  94433. };
  94434. Template.prototype._registerEvents = function () {
  94435. var _this = this;
  94436. this._registeredEvents = this._registeredEvents || [];
  94437. if (this._registeredEvents.length) {
  94438. this._registeredEvents.forEach(function (evt) {
  94439. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  94440. });
  94441. }
  94442. if (this._configuration.events) {
  94443. var _loop_1 = function (eventName) {
  94444. if (this_1._configuration.events && this_1._configuration.events[eventName]) {
  94445. var functionToFire_1 = function (selector, event) {
  94446. _this.onEventTriggered.notifyObservers({ event: event, template: _this, selector: selector });
  94447. };
  94448. if (typeof this_1._configuration.events[eventName] === 'boolean') {
  94449. var binding = functionToFire_1.bind(this_1, '#' + this_1.parent.id);
  94450. this_1.parent.addEventListener(eventName, functionToFire_1.bind(this_1, '#' + this_1.parent.id), false);
  94451. this_1._registeredEvents.push({
  94452. htmlElement: this_1.parent,
  94453. eventName: eventName,
  94454. function: binding
  94455. });
  94456. }
  94457. else if (typeof this_1._configuration.events[eventName] === 'object') {
  94458. var selectorsArray = Object.keys(this_1._configuration.events[eventName] || {});
  94459. var event_1 = this_1._configuration.events[eventName] || {};
  94460. selectorsArray.filter(function (selector) { return event_1[selector]; }).forEach(function (selector) {
  94461. if (selector && selector.indexOf('#') !== 0) {
  94462. selector = '#' + selector;
  94463. }
  94464. var htmlElement = _this.parent.querySelector(selector);
  94465. if (htmlElement) {
  94466. var binding = functionToFire_1.bind(_this, selector);
  94467. htmlElement.addEventListener(eventName, binding, false);
  94468. _this._registeredEvents.push({
  94469. htmlElement: htmlElement,
  94470. eventName: eventName,
  94471. function: binding
  94472. });
  94473. }
  94474. });
  94475. }
  94476. }
  94477. };
  94478. var this_1 = this;
  94479. for (var eventName in this._configuration.events) {
  94480. _loop_1(eventName);
  94481. }
  94482. }
  94483. };
  94484. Template.prototype._getTemplateLocation = function (templateConfig) {
  94485. if (!templateConfig || typeof templateConfig === 'string') {
  94486. return templateConfig;
  94487. }
  94488. else {
  94489. return templateConfig.location;
  94490. }
  94491. };
  94492. return Template;
  94493. }());
  94494. exports.Template = Template;
  94495. /***/ }),
  94496. /* 24 */
  94497. /***/ (function(module, exports, __webpack_require__) {
  94498. /**!
  94499. @license
  94500. handlebars v4.0.11
  94501. Copyright (C) 2011-2017 by Yehuda Katz
  94502. Permission is hereby granted, free of charge, to any person obtaining a copy
  94503. of this software and associated documentation files (the "Software"), to deal
  94504. in the Software without restriction, including without limitation the rights
  94505. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  94506. copies of the Software, and to permit persons to whom the Software is
  94507. furnished to do so, subject to the following conditions:
  94508. The above copyright notice and this permission notice shall be included in
  94509. all copies or substantial portions of the Software.
  94510. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  94511. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  94512. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  94513. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  94514. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  94515. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  94516. THE SOFTWARE.
  94517. */
  94518. !function(a,b){ true?module.exports=b():"function"==typeof define&&define.amd?define([],b):"object"==typeof exports?exports.Handlebars=b():a.Handlebars=b()}(this,function(){return function(a){function b(d){if(c[d])return c[d].exports;var e=c[d]={exports:{},id:d,loaded:!1};return a[d].call(e.exports,e,e.exports,b),e.loaded=!0,e.exports}var c={};return b.m=a,b.c=c,b.p="",b(0)}([function(a,b,c){"use strict";function d(){var a=r();return a.compile=function(b,c){return k.compile(b,c,a)},a.precompile=function(b,c){return k.precompile(b,c,a)},a.AST=i["default"],a.Compiler=k.Compiler,a.JavaScriptCompiler=m["default"],a.Parser=j.parser,a.parse=j.parse,a}var e=c(1)["default"];b.__esModule=!0;var f=c(2),g=e(f),h=c(35),i=e(h),j=c(36),k=c(41),l=c(42),m=e(l),n=c(39),o=e(n),p=c(34),q=e(p),r=g["default"].create,s=d();s.create=d,q["default"](s),s.Visitor=o["default"],s["default"]=s,b["default"]=s,a.exports=b["default"]},function(a,b){"use strict";b["default"]=function(a){return a&&a.__esModule?a:{"default":a}},b.__esModule=!0},function(a,b,c){"use strict";function d(){var a=new h.HandlebarsEnvironment;return n.extend(a,h),a.SafeString=j["default"],a.Exception=l["default"],a.Utils=n,a.escapeExpression=n.escapeExpression,a.VM=p,a.template=function(b){return p.template(b,a)},a}var e=c(3)["default"],f=c(1)["default"];b.__esModule=!0;var g=c(4),h=e(g),i=c(21),j=f(i),k=c(6),l=f(k),m=c(5),n=e(m),o=c(22),p=e(o),q=c(34),r=f(q),s=d();s.create=d,r["default"](s),s["default"]=s,b["default"]=s,a.exports=b["default"]},function(a,b){"use strict";b["default"]=function(a){if(a&&a.__esModule)return a;var b={};if(null!=a)for(var c in a)Object.prototype.hasOwnProperty.call(a,c)&&(b[c]=a[c]);return b["default"]=a,b},b.__esModule=!0},function(a,b,c){"use strict";function d(a,b,c){this.helpers=a||{},this.partials=b||{},this.decorators=c||{},i.registerDefaultHelpers(this),j.registerDefaultDecorators(this)}var e=c(1)["default"];b.__esModule=!0,b.HandlebarsEnvironment=d;var f=c(5),g=c(6),h=e(g),i=c(10),j=c(18),k=c(20),l=e(k),m="4.0.11";b.VERSION=m;var n=7;b.COMPILER_REVISION=n;var o={1:"<= 1.0.rc.2",2:"== 1.0.0-rc.3",3:"== 1.0.0-rc.4",4:"== 1.x.x",5:"== 2.0.0-alpha.x",6:">= 2.0.0-beta.1",7:">= 4.0.0"};b.REVISION_CHANGES=o;var p="[object Object]";d.prototype={constructor:d,logger:l["default"],log:l["default"].log,registerHelper:function(a,b){if(f.toString.call(a)===p){if(b)throw new h["default"]("Arg not supported with multiple helpers");f.extend(this.helpers,a)}else this.helpers[a]=b},unregisterHelper:function(a){delete this.helpers[a]},registerPartial:function(a,b){if(f.toString.call(a)===p)f.extend(this.partials,a);else{if("undefined"==typeof b)throw new h["default"]('Attempting to register a partial called "'+a+'" as undefined');this.partials[a]=b}},unregisterPartial:function(a){delete this.partials[a]},registerDecorator:function(a,b){if(f.toString.call(a)===p){if(b)throw new h["default"]("Arg not supported with multiple decorators");f.extend(this.decorators,a)}else this.decorators[a]=b},unregisterDecorator:function(a){delete this.decorators[a]}};var q=l["default"].log;b.log=q,b.createFrame=f.createFrame,b.logger=l["default"]},function(a,b){"use strict";function c(a){return k[a]}function d(a){for(var b=1;b<arguments.length;b++)for(var c in arguments[b])Object.prototype.hasOwnProperty.call(arguments[b],c)&&(a[c]=arguments[b][c]);return a}function e(a,b){for(var c=0,d=a.length;c<d;c++)if(a[c]===b)return c;return-1}function f(a){if("string"!=typeof a){if(a&&a.toHTML)return a.toHTML();if(null==a)return"";if(!a)return a+"";a=""+a}return m.test(a)?a.replace(l,c):a}function g(a){return!a&&0!==a||!(!p(a)||0!==a.length)}function h(a){var b=d({},a);return b._parent=a,b}function i(a,b){return a.path=b,a}function j(a,b){return(a?a+".":"")+b}b.__esModule=!0,b.extend=d,b.indexOf=e,b.escapeExpression=f,b.isEmpty=g,b.createFrame=h,b.blockParams=i,b.appendContextPath=j;var k={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","`":"&#x60;","=":"&#x3D;"},l=/[&<>"'`=]/g,m=/[&<>"'`=]/,n=Object.prototype.toString;b.toString=n;var o=function(a){return"function"==typeof a};o(/x/)&&(b.isFunction=o=function(a){return"function"==typeof a&&"[object Function]"===n.call(a)}),b.isFunction=o;var p=Array.isArray||function(a){return!(!a||"object"!=typeof a)&&"[object Array]"===n.call(a)};b.isArray=p},function(a,b,c){"use strict";function d(a,b){var c=b&&b.loc,g=void 0,h=void 0;c&&(g=c.start.line,h=c.start.column,a+=" - "+g+":"+h);for(var i=Error.prototype.constructor.call(this,a),j=0;j<f.length;j++)this[f[j]]=i[f[j]];Error.captureStackTrace&&Error.captureStackTrace(this,d);try{c&&(this.lineNumber=g,e?Object.defineProperty(this,"column",{value:h,enumerable:!0}):this.column=h)}catch(k){}}var e=c(7)["default"];b.__esModule=!0;var f=["description","fileName","lineNumber","message","name","number","stack"];d.prototype=new Error,b["default"]=d,a.exports=b["default"]},function(a,b,c){a.exports={"default":c(8),__esModule:!0}},function(a,b,c){var d=c(9);a.exports=function(a,b,c){return d.setDesc(a,b,c)}},function(a,b){var c=Object;a.exports={create:c.create,getProto:c.getPrototypeOf,isEnum:{}.propertyIsEnumerable,getDesc:c.getOwnPropertyDescriptor,setDesc:c.defineProperty,setDescs:c.defineProperties,getKeys:c.keys,getNames:c.getOwnPropertyNames,getSymbols:c.getOwnPropertySymbols,each:[].forEach}},function(a,b,c){"use strict";function d(a){g["default"](a),i["default"](a),k["default"](a),m["default"](a),o["default"](a),q["default"](a),s["default"](a)}var e=c(1)["default"];b.__esModule=!0,b.registerDefaultHelpers=d;var f=c(11),g=e(f),h=c(12),i=e(h),j=c(13),k=e(j),l=c(14),m=e(l),n=c(15),o=e(n),p=c(16),q=e(p),r=c(17),s=e(r)},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5);b["default"]=function(a){a.registerHelper("blockHelperMissing",function(b,c){var e=c.inverse,f=c.fn;if(b===!0)return f(this);if(b===!1||null==b)return e(this);if(d.isArray(b))return b.length>0?(c.ids&&(c.ids=[c.name]),a.helpers.each(b,c)):e(this);if(c.data&&c.ids){var g=d.createFrame(c.data);g.contextPath=d.appendContextPath(c.data.contextPath,c.name),c={data:g}}return f(b,c)})},a.exports=b["default"]},function(a,b,c){"use strict";var d=c(1)["default"];b.__esModule=!0;var e=c(5),f=c(6),g=d(f);b["default"]=function(a){a.registerHelper("each",function(a,b){function c(b,c,f){j&&(j.key=b,j.index=c,j.first=0===c,j.last=!!f,k&&(j.contextPath=k+b)),i+=d(a[b],{data:j,blockParams:e.blockParams([a[b],b],[k+b,null])})}if(!b)throw new g["default"]("Must pass iterator to #each");var d=b.fn,f=b.inverse,h=0,i="",j=void 0,k=void 0;if(b.data&&b.ids&&(k=e.appendContextPath(b.data.contextPath,b.ids[0])+"."),e.isFunction(a)&&(a=a.call(this)),b.data&&(j=e.createFrame(b.data)),a&&"object"==typeof a)if(e.isArray(a))for(var l=a.length;h<l;h++)h in a&&c(h,h,h===a.length-1);else{var m=void 0;for(var n in a)a.hasOwnProperty(n)&&(void 0!==m&&c(m,h-1),m=n,h++);void 0!==m&&c(m,h-1,!0)}return 0===h&&(i=f(this)),i})},a.exports=b["default"]},function(a,b,c){"use strict";var d=c(1)["default"];b.__esModule=!0;var e=c(6),f=d(e);b["default"]=function(a){a.registerHelper("helperMissing",function(){if(1!==arguments.length)throw new f["default"]('Missing helper: "'+arguments[arguments.length-1].name+'"')})},a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5);b["default"]=function(a){a.registerHelper("if",function(a,b){return d.isFunction(a)&&(a=a.call(this)),!b.hash.includeZero&&!a||d.isEmpty(a)?b.inverse(this):b.fn(this)}),a.registerHelper("unless",function(b,c){return a.helpers["if"].call(this,b,{fn:c.inverse,inverse:c.fn,hash:c.hash})})},a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0,b["default"]=function(a){a.registerHelper("log",function(){for(var b=[void 0],c=arguments[arguments.length-1],d=0;d<arguments.length-1;d++)b.push(arguments[d]);var e=1;null!=c.hash.level?e=c.hash.level:c.data&&null!=c.data.level&&(e=c.data.level),b[0]=e,a.log.apply(a,b)})},a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0,b["default"]=function(a){a.registerHelper("lookup",function(a,b){return a&&a[b]})},a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5);b["default"]=function(a){a.registerHelper("with",function(a,b){d.isFunction(a)&&(a=a.call(this));var c=b.fn;if(d.isEmpty(a))return b.inverse(this);var e=b.data;return b.data&&b.ids&&(e=d.createFrame(b.data),e.contextPath=d.appendContextPath(b.data.contextPath,b.ids[0])),c(a,{data:e,blockParams:d.blockParams([a],[e&&e.contextPath])})})},a.exports=b["default"]},function(a,b,c){"use strict";function d(a){g["default"](a)}var e=c(1)["default"];b.__esModule=!0,b.registerDefaultDecorators=d;var f=c(19),g=e(f)},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5);b["default"]=function(a){a.registerDecorator("inline",function(a,b,c,e){var f=a;return b.partials||(b.partials={},f=function(e,f){var g=c.partials;c.partials=d.extend({},g,b.partials);var h=a(e,f);return c.partials=g,h}),b.partials[e.args[0]]=e.fn,f})},a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5),e={methodMap:["debug","info","warn","error"],level:"info",lookupLevel:function(a){if("string"==typeof a){var b=d.indexOf(e.methodMap,a.toLowerCase());a=b>=0?b:parseInt(a,10)}return a},log:function(a){if(a=e.lookupLevel(a),"undefined"!=typeof console&&e.lookupLevel(e.level)<=a){var b=e.methodMap[a];console[b]||(b="log");for(var c=arguments.length,d=Array(c>1?c-1:0),f=1;f<c;f++)d[f-1]=arguments[f];console[b].apply(console,d)}}};b["default"]=e,a.exports=b["default"]},function(a,b){"use strict";function c(a){this.string=a}b.__esModule=!0,c.prototype.toString=c.prototype.toHTML=function(){return""+this.string},b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";function d(a){var b=a&&a[0]||1,c=s.COMPILER_REVISION;if(b!==c){if(b<c){var d=s.REVISION_CHANGES[c],e=s.REVISION_CHANGES[b];throw new r["default"]("Template was precompiled with an older version of Handlebars than the current runtime. Please update your precompiler to a newer version ("+d+") or downgrade your runtime to an older version ("+e+").")}throw new r["default"]("Template was precompiled with a newer version of Handlebars than the current runtime. Please update your runtime to a newer version ("+a[1]+").")}}function e(a,b){function c(c,d,e){e.hash&&(d=p.extend({},d,e.hash),e.ids&&(e.ids[0]=!0)),c=b.VM.resolvePartial.call(this,c,d,e);var f=b.VM.invokePartial.call(this,c,d,e);if(null==f&&b.compile&&(e.partials[e.name]=b.compile(c,a.compilerOptions,b),f=e.partials[e.name](d,e)),null!=f){if(e.indent){for(var g=f.split("\n"),h=0,i=g.length;h<i&&(g[h]||h+1!==i);h++)g[h]=e.indent+g[h];f=g.join("\n")}return f}throw new r["default"]("The partial "+e.name+" could not be compiled when running in runtime-only mode")}function d(b){function c(b){return""+a.main(e,b,e.helpers,e.partials,g,i,h)}var f=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],g=f.data;d._setup(f),!f.partial&&a.useData&&(g=j(b,g));var h=void 0,i=a.useBlockParams?[]:void 0;return a.useDepths&&(h=f.depths?b!=f.depths[0]?[b].concat(f.depths):f.depths:[b]),(c=k(a.main,c,e,f.depths||[],g,i))(b,f)}if(!b)throw new r["default"]("No environment passed to template");if(!a||!a.main)throw new r["default"]("Unknown template object: "+typeof a);a.main.decorator=a.main_d,b.VM.checkRevision(a.compiler);var e={strict:function(a,b){if(!(b in a))throw new r["default"]('"'+b+'" not defined in '+a);return a[b]},lookup:function(a,b){for(var c=a.length,d=0;d<c;d++)if(a[d]&&null!=a[d][b])return a[d][b]},lambda:function(a,b){return"function"==typeof a?a.call(b):a},escapeExpression:p.escapeExpression,invokePartial:c,fn:function(b){var c=a[b];return c.decorator=a[b+"_d"],c},programs:[],program:function(a,b,c,d,e){var g=this.programs[a],h=this.fn(a);return b||e||d||c?g=f(this,a,h,b,c,d,e):g||(g=this.programs[a]=f(this,a,h)),g},data:function(a,b){for(;a&&b--;)a=a._parent;return a},merge:function(a,b){var c=a||b;return a&&b&&a!==b&&(c=p.extend({},b,a)),c},nullContext:l({}),noop:b.VM.noop,compilerInfo:a.compiler};return d.isTop=!0,d._setup=function(c){c.partial?(e.helpers=c.helpers,e.partials=c.partials,e.decorators=c.decorators):(e.helpers=e.merge(c.helpers,b.helpers),a.usePartial&&(e.partials=e.merge(c.partials,b.partials)),(a.usePartial||a.useDecorators)&&(e.decorators=e.merge(c.decorators,b.decorators)))},d._child=function(b,c,d,g){if(a.useBlockParams&&!d)throw new r["default"]("must pass block params");if(a.useDepths&&!g)throw new r["default"]("must pass parent depths");return f(e,b,a[b],c,0,d,g)},d}function f(a,b,c,d,e,f,g){function h(b){var e=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],h=g;return!g||b==g[0]||b===a.nullContext&&null===g[0]||(h=[b].concat(g)),c(a,b,a.helpers,a.partials,e.data||d,f&&[e.blockParams].concat(f),h)}return h=k(c,h,a,g,d,f),h.program=b,h.depth=g?g.length:0,h.blockParams=e||0,h}function g(a,b,c){return a?a.call||c.name||(c.name=a,a=c.partials[a]):a="@partial-block"===c.name?c.data["partial-block"]:c.partials[c.name],a}function h(a,b,c){var d=c.data&&c.data["partial-block"];c.partial=!0,c.ids&&(c.data.contextPath=c.ids[0]||c.data.contextPath);var e=void 0;if(c.fn&&c.fn!==i&&!function(){c.data=s.createFrame(c.data);var a=c.fn;e=c.data["partial-block"]=function(b){var c=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];return c.data=s.createFrame(c.data),c.data["partial-block"]=d,a(b,c)},a.partials&&(c.partials=p.extend({},c.partials,a.partials))}(),void 0===a&&e&&(a=e),void 0===a)throw new r["default"]("The partial "+c.name+" could not be found");if(a instanceof Function)return a(b,c)}function i(){return""}function j(a,b){return b&&"root"in b||(b=b?s.createFrame(b):{},b.root=a),b}function k(a,b,c,d,e,f){if(a.decorator){var g={};b=a.decorator(b,g,c,d&&d[0],e,f,d),p.extend(b,g)}return b}var l=c(23)["default"],m=c(3)["default"],n=c(1)["default"];b.__esModule=!0,b.checkRevision=d,b.template=e,b.wrapProgram=f,b.resolvePartial=g,b.invokePartial=h,b.noop=i;var o=c(5),p=m(o),q=c(6),r=n(q),s=c(4)},function(a,b,c){a.exports={"default":c(24),__esModule:!0}},function(a,b,c){c(25),a.exports=c(30).Object.seal},function(a,b,c){var d=c(26);c(27)("seal",function(a){return function(b){return a&&d(b)?a(b):b}})},function(a,b){a.exports=function(a){return"object"==typeof a?null!==a:"function"==typeof a}},function(a,b,c){var d=c(28),e=c(30),f=c(33);a.exports=function(a,b){var c=(e.Object||{})[a]||Object[a],g={};g[a]=b(c),d(d.S+d.F*f(function(){c(1)}),"Object",g)}},function(a,b,c){var d=c(29),e=c(30),f=c(31),g="prototype",h=function(a,b,c){var i,j,k,l=a&h.F,m=a&h.G,n=a&h.S,o=a&h.P,p=a&h.B,q=a&h.W,r=m?e:e[b]||(e[b]={}),s=m?d:n?d[b]:(d[b]||{})[g];m&&(c=b);for(i in c)j=!l&&s&&i in s,j&&i in r||(k=j?s[i]:c[i],r[i]=m&&"function"!=typeof s[i]?c[i]:p&&j?f(k,d):q&&s[i]==k?function(a){var b=function(b){return this instanceof a?new a(b):a(b)};return b[g]=a[g],b}(k):o&&"function"==typeof k?f(Function.call,k):k,o&&((r[g]||(r[g]={}))[i]=k))};h.F=1,h.G=2,h.S=4,h.P=8,h.B=16,h.W=32,a.exports=h},function(a,b){var c=a.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=c)},function(a,b){var c=a.exports={version:"1.2.6"};"number"==typeof __e&&(__e=c)},function(a,b,c){var d=c(32);a.exports=function(a,b,c){if(d(a),void 0===b)return a;switch(c){case 1:return function(c){return a.call(b,c)};case 2:return function(c,d){return a.call(b,c,d)};case 3:return function(c,d,e){return a.call(b,c,d,e)}}return function(){return a.apply(b,arguments)}}},function(a,b){a.exports=function(a){if("function"!=typeof a)throw TypeError(a+" is not a function!");return a}},function(a,b){a.exports=function(a){try{return!!a()}catch(b){return!0}}},function(a,b){(function(c){"use strict";b.__esModule=!0,b["default"]=function(a){var b="undefined"!=typeof c?c:window,d=b.Handlebars;a.noConflict=function(){return b.Handlebars===a&&(b.Handlebars=d),a}},a.exports=b["default"]}).call(b,function(){return this}())},function(a,b){"use strict";b.__esModule=!0;var c={helpers:{helperExpression:function(a){return"SubExpression"===a.type||("MustacheStatement"===a.type||"BlockStatement"===a.type)&&!!(a.params&&a.params.length||a.hash)},scopedId:function(a){return/^\.|this\b/.test(a.original)},simpleId:function(a){return 1===a.parts.length&&!c.helpers.scopedId(a)&&!a.depth}}};b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";function d(a,b){if("Program"===a.type)return a;h["default"].yy=n,n.locInfo=function(a){return new n.SourceLocation(b&&b.srcName,a)};var c=new j["default"](b);return c.accept(h["default"].parse(a))}var e=c(1)["default"],f=c(3)["default"];b.__esModule=!0,b.parse=d;var g=c(37),h=e(g),i=c(38),j=e(i),k=c(40),l=f(k),m=c(5);b.parser=h["default"];var n={};m.extend(n,l)},function(a,b){"use strict";b.__esModule=!0;var c=function(){function a(){this.yy={}}var b={trace:function(){},yy:{},symbols_:{error:2,root:3,program:4,EOF:5,program_repetition0:6,statement:7,mustache:8,block:9,rawBlock:10,partial:11,partialBlock:12,content:13,COMMENT:14,CONTENT:15,openRawBlock:16,rawBlock_repetition_plus0:17,END_RAW_BLOCK:18,OPEN_RAW_BLOCK:19,helperName:20,openRawBlock_repetition0:21,openRawBlock_option0:22,CLOSE_RAW_BLOCK:23,openBlock:24,block_option0:25,closeBlock:26,openInverse:27,block_option1:28,OPEN_BLOCK:29,openBlock_repetition0:30,openBlock_option0:31,openBlock_option1:32,CLOSE:33,OPEN_INVERSE:34,openInverse_repetition0:35,openInverse_option0:36,openInverse_option1:37,openInverseChain:38,OPEN_INVERSE_CHAIN:39,openInverseChain_repetition0:40,openInverseChain_option0:41,openInverseChain_option1:42,inverseAndProgram:43,INVERSE:44,inverseChain:45,inverseChain_option0:46,OPEN_ENDBLOCK:47,OPEN:48,mustache_repetition0:49,mustache_option0:50,OPEN_UNESCAPED:51,mustache_repetition1:52,mustache_option1:53,CLOSE_UNESCAPED:54,OPEN_PARTIAL:55,partialName:56,partial_repetition0:57,partial_option0:58,openPartialBlock:59,OPEN_PARTIAL_BLOCK:60,openPartialBlock_repetition0:61,openPartialBlock_option0:62,param:63,sexpr:64,OPEN_SEXPR:65,sexpr_repetition0:66,sexpr_option0:67,CLOSE_SEXPR:68,hash:69,hash_repetition_plus0:70,hashSegment:71,ID:72,EQUALS:73,blockParams:74,OPEN_BLOCK_PARAMS:75,blockParams_repetition_plus0:76,CLOSE_BLOCK_PARAMS:77,path:78,dataName:79,STRING:80,NUMBER:81,BOOLEAN:82,UNDEFINED:83,NULL:84,DATA:85,pathSegments:86,SEP:87,$accept:0,$end:1},terminals_:{2:"error",5:"EOF",14:"COMMENT",15:"CONTENT",18:"END_RAW_BLOCK",19:"OPEN_RAW_BLOCK",23:"CLOSE_RAW_BLOCK",29:"OPEN_BLOCK",33:"CLOSE",34:"OPEN_INVERSE",39:"OPEN_INVERSE_CHAIN",44:"INVERSE",47:"OPEN_ENDBLOCK",48:"OPEN",51:"OPEN_UNESCAPED",54:"CLOSE_UNESCAPED",55:"OPEN_PARTIAL",60:"OPEN_PARTIAL_BLOCK",65:"OPEN_SEXPR",68:"CLOSE_SEXPR",72:"ID",73:"EQUALS",75:"OPEN_BLOCK_PARAMS",77:"CLOSE_BLOCK_PARAMS",80:"STRING",81:"NUMBER",82:"BOOLEAN",83:"UNDEFINED",84:"NULL",85:"DATA",87:"SEP"},productions_:[0,[3,2],[4,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[13,1],[10,3],[16,5],[9,4],[9,4],[24,6],[27,6],[38,6],[43,2],[45,3],[45,1],[26,3],[8,5],[8,5],[11,5],[12,3],[59,5],[63,1],[63,1],[64,5],[69,1],[71,3],[74,3],[20,1],[20,1],[20,1],[20,1],[20,1],[20,1],[20,1],[56,1],[56,1],[79,2],[78,1],[86,3],[86,1],[6,0],[6,2],[17,1],[17,2],[21,0],[21,2],[22,0],[22,1],[25,0],[25,1],[28,0],[28,1],[30,0],[30,2],[31,0],[31,1],[32,0],[32,1],[35,0],[35,2],[36,0],[36,1],[37,0],[37,1],[40,0],[40,2],[41,0],[41,1],[42,0],[42,1],[46,0],[46,1],[49,0],[49,2],[50,0],[50,1],[52,0],[52,2],[53,0],[53,1],[57,0],[57,2],[58,0],[58,1],[61,0],[61,2],[62,0],[62,1],[66,0],[66,2],[67,0],[67,1],[70,1],[70,2],[76,1],[76,2]],performAction:function(a,b,c,d,e,f,g){var h=f.length-1;switch(e){case 1:return f[h-1];case 2:this.$=d.prepareProgram(f[h]);break;case 3:this.$=f[h];break;case 4:this.$=f[h];break;case 5:this.$=f[h];break;case 6:this.$=f[h];break;case 7:this.$=f[h];break;case 8:this.$=f[h];break;case 9:this.$={type:"CommentStatement",value:d.stripComment(f[h]),strip:d.stripFlags(f[h],f[h]),loc:d.locInfo(this._$)};break;case 10:this.$={type:"ContentStatement",original:f[h],value:f[h],loc:d.locInfo(this._$)};break;case 11:this.$=d.prepareRawBlock(f[h-2],f[h-1],f[h],this._$);break;case 12:this.$={path:f[h-3],params:f[h-2],hash:f[h-1]};break;case 13:this.$=d.prepareBlock(f[h-3],f[h-2],f[h-1],f[h],!1,this._$);break;case 14:this.$=d.prepareBlock(f[h-3],f[h-2],f[h-1],f[h],!0,this._$);break;case 15:this.$={open:f[h-5],path:f[h-4],params:f[h-3],hash:f[h-2],blockParams:f[h-1],strip:d.stripFlags(f[h-5],f[h])};break;case 16:this.$={path:f[h-4],params:f[h-3],hash:f[h-2],blockParams:f[h-1],strip:d.stripFlags(f[h-5],f[h])};break;case 17:this.$={path:f[h-4],params:f[h-3],hash:f[h-2],blockParams:f[h-1],strip:d.stripFlags(f[h-5],f[h])};break;case 18:this.$={strip:d.stripFlags(f[h-1],f[h-1]),program:f[h]};break;case 19:var i=d.prepareBlock(f[h-2],f[h-1],f[h],f[h],!1,this._$),j=d.prepareProgram([i],f[h-1].loc);j.chained=!0,this.$={strip:f[h-2].strip,program:j,chain:!0};break;case 20:this.$=f[h];break;case 21:this.$={path:f[h-1],strip:d.stripFlags(f[h-2],f[h])};break;case 22:this.$=d.prepareMustache(f[h-3],f[h-2],f[h-1],f[h-4],d.stripFlags(f[h-4],f[h]),this._$);break;case 23:this.$=d.prepareMustache(f[h-3],f[h-2],f[h-1],f[h-4],d.stripFlags(f[h-4],f[h]),this._$);break;case 24:this.$={type:"PartialStatement",name:f[h-3],params:f[h-2],hash:f[h-1],indent:"",strip:d.stripFlags(f[h-4],f[h]),loc:d.locInfo(this._$)};break;case 25:this.$=d.preparePartialBlock(f[h-2],f[h-1],f[h],this._$);break;case 26:this.$={path:f[h-3],params:f[h-2],hash:f[h-1],strip:d.stripFlags(f[h-4],f[h])};break;case 27:this.$=f[h];break;case 28:this.$=f[h];break;case 29:this.$={type:"SubExpression",path:f[h-3],params:f[h-2],hash:f[h-1],loc:d.locInfo(this._$)};break;case 30:this.$={type:"Hash",pairs:f[h],loc:d.locInfo(this._$)};break;case 31:this.$={type:"HashPair",key:d.id(f[h-2]),value:f[h],loc:d.locInfo(this._$)};break;case 32:this.$=d.id(f[h-1]);break;case 33:this.$=f[h];break;case 34:this.$=f[h];break;case 35:this.$={type:"StringLiteral",value:f[h],original:f[h],loc:d.locInfo(this._$)};break;case 36:this.$={type:"NumberLiteral",value:Number(f[h]),original:Number(f[h]),loc:d.locInfo(this._$)};break;case 37:this.$={type:"BooleanLiteral",value:"true"===f[h],original:"true"===f[h],loc:d.locInfo(this._$)};break;case 38:this.$={type:"UndefinedLiteral",original:void 0,value:void 0,loc:d.locInfo(this._$)};break;case 39:this.$={type:"NullLiteral",original:null,value:null,loc:d.locInfo(this._$)};break;case 40:this.$=f[h];break;case 41:this.$=f[h];break;case 42:this.$=d.preparePath(!0,f[h],this._$);break;case 43:this.$=d.preparePath(!1,f[h],this._$);break;case 44:f[h-2].push({part:d.id(f[h]),original:f[h],separator:f[h-1]}),this.$=f[h-2];break;case 45:this.$=[{part:d.id(f[h]),original:f[h]}];break;case 46:this.$=[];break;case 47:f[h-1].push(f[h]);break;case 48:this.$=[f[h]];break;case 49:f[h-1].push(f[h]);break;case 50:this.$=[];break;case 51:f[h-1].push(f[h]);break;case 58:this.$=[];break;case 59:f[h-1].push(f[h]);break;case 64:this.$=[];break;case 65:f[h-1].push(f[h]);break;case 70:this.$=[];break;case 71:f[h-1].push(f[h]);break;case 78:this.$=[];break;case 79:f[h-1].push(f[h]);break;case 82:this.$=[];break;case 83:f[h-1].push(f[h]);break;case 86:this.$=[];break;case 87:f[h-1].push(f[h]);break;case 90:this.$=[];break;case 91:f[h-1].push(f[h]);break;case 94:this.$=[];break;case 95:f[h-1].push(f[h]);break;case 98:this.$=[f[h]];break;case 99:f[h-1].push(f[h]);break;case 100:this.$=[f[h]];break;case 101:f[h-1].push(f[h])}},table:[{3:1,4:2,5:[2,46],6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{1:[3]},{5:[1,4]},{5:[2,2],7:5,8:6,9:7,10:8,11:9,12:10,13:11,14:[1,12],15:[1,20],16:17,19:[1,23],24:15,27:16,29:[1,21],34:[1,22],39:[2,2],44:[2,2],47:[2,2],48:[1,13],51:[1,14],55:[1,18],59:19,60:[1,24]},{1:[2,1]},{5:[2,47],14:[2,47],15:[2,47],19:[2,47],29:[2,47],34:[2,47],39:[2,47],44:[2,47],47:[2,47],48:[2,47],51:[2,47],55:[2,47],60:[2,47]},{5:[2,3],14:[2,3],15:[2,3],19:[2,3],29:[2,3],34:[2,3],39:[2,3],44:[2,3],47:[2,3],48:[2,3],51:[2,3],55:[2,3],60:[2,3]},{5:[2,4],14:[2,4],15:[2,4],19:[2,4],29:[2,4],34:[2,4],39:[2,4],44:[2,4],47:[2,4],48:[2,4],51:[2,4],55:[2,4],60:[2,4]},{5:[2,5],14:[2,5],15:[2,5],19:[2,5],29:[2,5],34:[2,5],39:[2,5],44:[2,5],47:[2,5],48:[2,5],51:[2,5],55:[2,5],60:[2,5]},{5:[2,6],14:[2,6],15:[2,6],19:[2,6],29:[2,6],34:[2,6],39:[2,6],44:[2,6],47:[2,6],48:[2,6],51:[2,6],55:[2,6],60:[2,6]},{5:[2,7],14:[2,7],15:[2,7],19:[2,7],29:[2,7],34:[2,7],39:[2,7],44:[2,7],47:[2,7],48:[2,7],51:[2,7],55:[2,7],60:[2,7]},{5:[2,8],14:[2,8],15:[2,8],19:[2,8],29:[2,8],34:[2,8],39:[2,8],44:[2,8],47:[2,8],48:[2,8],51:[2,8],55:[2,8],60:[2,8]},{5:[2,9],14:[2,9],15:[2,9],19:[2,9],29:[2,9],34:[2,9],39:[2,9],44:[2,9],47:[2,9],48:[2,9],51:[2,9],55:[2,9],60:[2,9]},{20:25,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:36,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:37,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],39:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{4:38,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{13:40,15:[1,20],17:39},{20:42,56:41,64:43,65:[1,44],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:45,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{5:[2,10],14:[2,10],15:[2,10],18:[2,10],19:[2,10],29:[2,10],34:[2,10],39:[2,10],44:[2,10],47:[2,10],48:[2,10],51:[2,10],55:[2,10],60:[2,10]},{20:46,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:47,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:48,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:42,56:49,64:43,65:[1,44],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[2,78],49:50,65:[2,78],72:[2,78],80:[2,78],81:[2,78],82:[2,78],83:[2,78],84:[2,78],85:[2,78]},{23:[2,33],33:[2,33],54:[2,33],65:[2,33],68:[2,33],72:[2,33],75:[2,33],80:[2,33],81:[2,33],82:[2,33],83:[2,33],84:[2,33],85:[2,33]},{23:[2,34],33:[2,34],54:[2,34],65:[2,34],68:[2,34],72:[2,34],75:[2,34],80:[2,34],81:[2,34],82:[2,34],83:[2,34],84:[2,34],85:[2,34]},{23:[2,35],33:[2,35],54:[2,35],65:[2,35],68:[2,35],72:[2,35],75:[2,35],80:[2,35],81:[2,35],82:[2,35],83:[2,35],84:[2,35],85:[2,35]},{23:[2,36],33:[2,36],54:[2,36],65:[2,36],68:[2,36],72:[2,36],75:[2,36],80:[2,36],81:[2,36],82:[2,36],83:[2,36],84:[2,36],85:[2,36]},{23:[2,37],33:[2,37],54:[2,37],65:[2,37],68:[2,37],72:[2,37],75:[2,37],80:[2,37],81:[2,37],82:[2,37],83:[2,37],84:[2,37],85:[2,37]},{23:[2,38],33:[2,38],54:[2,38],65:[2,38],68:[2,38],72:[2,38],75:[2,38],80:[2,38],81:[2,38],82:[2,38],83:[2,38],84:[2,38],85:[2,38]},{23:[2,39],33:[2,39],54:[2,39],65:[2,39],68:[2,39],72:[2,39],75:[2,39],80:[2,39],81:[2,39],82:[2,39],83:[2,39],84:[2,39],85:[2,39]},{23:[2,43],33:[2,43],54:[2,43],65:[2,43],68:[2,43],72:[2,43],75:[2,43],80:[2,43],81:[2,43],82:[2,43],83:[2,43],84:[2,43],85:[2,43],87:[1,51]},{72:[1,35],86:52},{23:[2,45],33:[2,45],54:[2,45],65:[2,45],68:[2,45],72:[2,45],75:[2,45],80:[2,45],81:[2,45],82:[2,45],83:[2,45],84:[2,45],85:[2,45],87:[2,45]},{52:53,54:[2,82],65:[2,82],72:[2,82],80:[2,82],81:[2,82],82:[2,82],83:[2,82],84:[2,82],85:[2,82]},{25:54,38:56,39:[1,58],43:57,44:[1,59],45:55,47:[2,54]},{28:60,43:61,44:[1,59],47:[2,56]},{13:63,15:[1,20],18:[1,62]},{15:[2,48],18:[2,48]},{33:[2,86],57:64,65:[2,86],72:[2,86],80:[2,86],81:[2,86],82:[2,86],83:[2,86],84:[2,86],85:[2,86]},{33:[2,40],65:[2,40],72:[2,40],80:[2,40],81:[2,40],82:[2,40],83:[2,40],84:[2,40],85:[2,40]},{33:[2,41],65:[2,41],72:[2,41],80:[2,41],81:[2,41],82:[2,41],83:[2,41],84:[2,41],85:[2,41]},{20:65,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{26:66,47:[1,67]},{30:68,33:[2,58],65:[2,58],72:[2,58],75:[2,58],80:[2,58],81:[2,58],82:[2,58],83:[2,58],84:[2,58],85:[2,58]},{33:[2,64],35:69,65:[2,64],72:[2,64],75:[2,64],80:[2,64],81:[2,64],82:[2,64],83:[2,64],84:[2,64],85:[2,64]},{21:70,23:[2,50],65:[2,50],72:[2,50],80:[2,50],81:[2,50],82:[2,50],83:[2,50],84:[2,50],85:[2,50]},{33:[2,90],61:71,65:[2,90],72:[2,90],80:[2,90],81:[2,90],82:[2,90],83:[2,90],84:[2,90],85:[2,90]},{20:75,33:[2,80],50:72,63:73,64:76,65:[1,44],69:74,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{72:[1,80]},{23:[2,42],33:[2,42],54:[2,42],65:[2,42],68:[2,42],72:[2,42],75:[2,42],80:[2,42],81:[2,42],82:[2,42],83:[2,42],84:[2,42],85:[2,42],87:[1,51]},{20:75,53:81,54:[2,84],63:82,64:76,65:[1,44],69:83,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{26:84,47:[1,67]},{47:[2,55]},{4:85,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],39:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{47:[2,20]},{20:86,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:87,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{26:88,47:[1,67]},{47:[2,57]},{5:[2,11],14:[2,11],15:[2,11],19:[2,11],29:[2,11],34:[2,11],39:[2,11],44:[2,11],47:[2,11],48:[2,11],51:[2,11],55:[2,11],60:[2,11]},{15:[2,49],18:[2,49]},{20:75,33:[2,88],58:89,63:90,64:76,65:[1,44],69:91,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{65:[2,94],66:92,68:[2,94],72:[2,94],80:[2,94],81:[2,94],82:[2,94],83:[2,94],84:[2,94],85:[2,94]},{5:[2,25],14:[2,25],15:[2,25],19:[2,25],29:[2,25],34:[2,25],39:[2,25],44:[2,25],47:[2,25],48:[2,25],51:[2,25],55:[2,25],60:[2,25]},{20:93,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:75,31:94,33:[2,60],63:95,64:76,65:[1,44],69:96,70:77,71:78,72:[1,79],75:[2,60],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:75,33:[2,66],36:97,63:98,64:76,65:[1,44],69:99,70:77,71:78,72:[1,79],75:[2,66],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:75,22:100,23:[2,52],63:101,64:76,65:[1,44],69:102,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:75,33:[2,92],62:103,63:104,64:76,65:[1,44],69:105,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[1,106]},{33:[2,79],65:[2,79],72:[2,79],80:[2,79],81:[2,79],82:[2,79],83:[2,79],84:[2,79],85:[2,79]},{33:[2,81]},{23:[2,27],33:[2,27],54:[2,27],65:[2,27],68:[2,27],72:[2,27],75:[2,27],80:[2,27],81:[2,27],82:[2,27],83:[2,27],84:[2,27],85:[2,27]},{23:[2,28],33:[2,28],54:[2,28],65:[2,28],68:[2,28],72:[2,28],75:[2,28],80:[2,28],81:[2,28],82:[2,28],83:[2,28],84:[2,28],85:[2,28]},{23:[2,30],33:[2,30],54:[2,30],68:[2,30],71:107,72:[1,108],75:[2,30]},{23:[2,98],33:[2,98],54:[2,98],68:[2,98],72:[2,98],75:[2,98]},{23:[2,45],33:[2,45],54:[2,45],65:[2,45],68:[2,45],72:[2,45],73:[1,109],75:[2,45],80:[2,45],81:[2,45],82:[2,45],83:[2,45],84:[2,45],85:[2,45],87:[2,45]},{23:[2,44],33:[2,44],54:[2,44],65:[2,44],68:[2,44],72:[2,44],75:[2,44],80:[2,44],81:[2,44],82:[2,44],83:[2,44],84:[2,44],85:[2,44],87:[2,44]},{54:[1,110]},{54:[2,83],65:[2,83],72:[2,83],80:[2,83],81:[2,83],82:[2,83],83:[2,83],84:[2,83],85:[2,83]},{54:[2,85]},{5:[2,13],14:[2,13],15:[2,13],19:[2,13],29:[2,13],34:[2,13],39:[2,13],44:[2,13],47:[2,13],48:[2,13],51:[2,13],55:[2,13],60:[2,13]},{38:56,39:[1,58],43:57,44:[1,59],45:112,46:111,47:[2,76]},{33:[2,70],40:113,65:[2,70],72:[2,70],75:[2,70],80:[2,70],81:[2,70],82:[2,70],83:[2,70],84:[2,70],85:[2,70]},{47:[2,18]},{5:[2,14],14:[2,14],15:[2,14],19:[2,14],29:[2,14],34:[2,14],39:[2,14],44:[2,14],47:[2,14],48:[2,14],51:[2,14],55:[2,14],60:[2,14]},{33:[1,114]},{33:[2,87],65:[2,87],72:[2,87],80:[2,87],81:[2,87],82:[2,87],83:[2,87],84:[2,87],
  94519. 85:[2,87]},{33:[2,89]},{20:75,63:116,64:76,65:[1,44],67:115,68:[2,96],69:117,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[1,118]},{32:119,33:[2,62],74:120,75:[1,121]},{33:[2,59],65:[2,59],72:[2,59],75:[2,59],80:[2,59],81:[2,59],82:[2,59],83:[2,59],84:[2,59],85:[2,59]},{33:[2,61],75:[2,61]},{33:[2,68],37:122,74:123,75:[1,121]},{33:[2,65],65:[2,65],72:[2,65],75:[2,65],80:[2,65],81:[2,65],82:[2,65],83:[2,65],84:[2,65],85:[2,65]},{33:[2,67],75:[2,67]},{23:[1,124]},{23:[2,51],65:[2,51],72:[2,51],80:[2,51],81:[2,51],82:[2,51],83:[2,51],84:[2,51],85:[2,51]},{23:[2,53]},{33:[1,125]},{33:[2,91],65:[2,91],72:[2,91],80:[2,91],81:[2,91],82:[2,91],83:[2,91],84:[2,91],85:[2,91]},{33:[2,93]},{5:[2,22],14:[2,22],15:[2,22],19:[2,22],29:[2,22],34:[2,22],39:[2,22],44:[2,22],47:[2,22],48:[2,22],51:[2,22],55:[2,22],60:[2,22]},{23:[2,99],33:[2,99],54:[2,99],68:[2,99],72:[2,99],75:[2,99]},{73:[1,109]},{20:75,63:126,64:76,65:[1,44],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{5:[2,23],14:[2,23],15:[2,23],19:[2,23],29:[2,23],34:[2,23],39:[2,23],44:[2,23],47:[2,23],48:[2,23],51:[2,23],55:[2,23],60:[2,23]},{47:[2,19]},{47:[2,77]},{20:75,33:[2,72],41:127,63:128,64:76,65:[1,44],69:129,70:77,71:78,72:[1,79],75:[2,72],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{5:[2,24],14:[2,24],15:[2,24],19:[2,24],29:[2,24],34:[2,24],39:[2,24],44:[2,24],47:[2,24],48:[2,24],51:[2,24],55:[2,24],60:[2,24]},{68:[1,130]},{65:[2,95],68:[2,95],72:[2,95],80:[2,95],81:[2,95],82:[2,95],83:[2,95],84:[2,95],85:[2,95]},{68:[2,97]},{5:[2,21],14:[2,21],15:[2,21],19:[2,21],29:[2,21],34:[2,21],39:[2,21],44:[2,21],47:[2,21],48:[2,21],51:[2,21],55:[2,21],60:[2,21]},{33:[1,131]},{33:[2,63]},{72:[1,133],76:132},{33:[1,134]},{33:[2,69]},{15:[2,12]},{14:[2,26],15:[2,26],19:[2,26],29:[2,26],34:[2,26],47:[2,26],48:[2,26],51:[2,26],55:[2,26],60:[2,26]},{23:[2,31],33:[2,31],54:[2,31],68:[2,31],72:[2,31],75:[2,31]},{33:[2,74],42:135,74:136,75:[1,121]},{33:[2,71],65:[2,71],72:[2,71],75:[2,71],80:[2,71],81:[2,71],82:[2,71],83:[2,71],84:[2,71],85:[2,71]},{33:[2,73],75:[2,73]},{23:[2,29],33:[2,29],54:[2,29],65:[2,29],68:[2,29],72:[2,29],75:[2,29],80:[2,29],81:[2,29],82:[2,29],83:[2,29],84:[2,29],85:[2,29]},{14:[2,15],15:[2,15],19:[2,15],29:[2,15],34:[2,15],39:[2,15],44:[2,15],47:[2,15],48:[2,15],51:[2,15],55:[2,15],60:[2,15]},{72:[1,138],77:[1,137]},{72:[2,100],77:[2,100]},{14:[2,16],15:[2,16],19:[2,16],29:[2,16],34:[2,16],44:[2,16],47:[2,16],48:[2,16],51:[2,16],55:[2,16],60:[2,16]},{33:[1,139]},{33:[2,75]},{33:[2,32]},{72:[2,101],77:[2,101]},{14:[2,17],15:[2,17],19:[2,17],29:[2,17],34:[2,17],39:[2,17],44:[2,17],47:[2,17],48:[2,17],51:[2,17],55:[2,17],60:[2,17]}],defaultActions:{4:[2,1],55:[2,55],57:[2,20],61:[2,57],74:[2,81],83:[2,85],87:[2,18],91:[2,89],102:[2,53],105:[2,93],111:[2,19],112:[2,77],117:[2,97],120:[2,63],123:[2,69],124:[2,12],136:[2,75],137:[2,32]},parseError:function(a,b){throw new Error(a)},parse:function(a){function b(){var a;return a=c.lexer.lex()||1,"number"!=typeof a&&(a=c.symbols_[a]||a),a}var c=this,d=[0],e=[null],f=[],g=this.table,h="",i=0,j=0,k=0;this.lexer.setInput(a),this.lexer.yy=this.yy,this.yy.lexer=this.lexer,this.yy.parser=this,"undefined"==typeof this.lexer.yylloc&&(this.lexer.yylloc={});var l=this.lexer.yylloc;f.push(l);var m=this.lexer.options&&this.lexer.options.ranges;"function"==typeof this.yy.parseError&&(this.parseError=this.yy.parseError);for(var n,o,p,q,r,s,t,u,v,w={};;){if(p=d[d.length-1],this.defaultActions[p]?q=this.defaultActions[p]:(null!==n&&"undefined"!=typeof n||(n=b()),q=g[p]&&g[p][n]),"undefined"==typeof q||!q.length||!q[0]){var x="";if(!k){v=[];for(s in g[p])this.terminals_[s]&&s>2&&v.push("'"+this.terminals_[s]+"'");x=this.lexer.showPosition?"Parse error on line "+(i+1)+":\n"+this.lexer.showPosition()+"\nExpecting "+v.join(", ")+", got '"+(this.terminals_[n]||n)+"'":"Parse error on line "+(i+1)+": Unexpected "+(1==n?"end of input":"'"+(this.terminals_[n]||n)+"'"),this.parseError(x,{text:this.lexer.match,token:this.terminals_[n]||n,line:this.lexer.yylineno,loc:l,expected:v})}}if(q[0]instanceof Array&&q.length>1)throw new Error("Parse Error: multiple actions possible at state: "+p+", token: "+n);switch(q[0]){case 1:d.push(n),e.push(this.lexer.yytext),f.push(this.lexer.yylloc),d.push(q[1]),n=null,o?(n=o,o=null):(j=this.lexer.yyleng,h=this.lexer.yytext,i=this.lexer.yylineno,l=this.lexer.yylloc,k>0&&k--);break;case 2:if(t=this.productions_[q[1]][1],w.$=e[e.length-t],w._$={first_line:f[f.length-(t||1)].first_line,last_line:f[f.length-1].last_line,first_column:f[f.length-(t||1)].first_column,last_column:f[f.length-1].last_column},m&&(w._$.range=[f[f.length-(t||1)].range[0],f[f.length-1].range[1]]),r=this.performAction.call(w,h,j,i,this.yy,q[1],e,f),"undefined"!=typeof r)return r;t&&(d=d.slice(0,-1*t*2),e=e.slice(0,-1*t),f=f.slice(0,-1*t)),d.push(this.productions_[q[1]][0]),e.push(w.$),f.push(w._$),u=g[d[d.length-2]][d[d.length-1]],d.push(u);break;case 3:return!0}}return!0}},c=function(){var a={EOF:1,parseError:function(a,b){if(!this.yy.parser)throw new Error(a);this.yy.parser.parseError(a,b)},setInput:function(a){return this._input=a,this._more=this._less=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var a=this._input[0];this.yytext+=a,this.yyleng++,this.offset++,this.match+=a,this.matched+=a;var b=a.match(/(?:\r\n?|\n).*/g);return b?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),a},unput:function(a){var b=a.length,c=a.split(/(?:\r\n?|\n)/g);this._input=a+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-b-1),this.offset-=b;var d=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),c.length-1&&(this.yylineno-=c.length-1);var e=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:c?(c.length===d.length?this.yylloc.first_column:0)+d[d.length-c.length].length-c[0].length:this.yylloc.first_column-b},this.options.ranges&&(this.yylloc.range=[e[0],e[0]+this.yyleng-b]),this},more:function(){return this._more=!0,this},less:function(a){this.unput(this.match.slice(a))},pastInput:function(){var a=this.matched.substr(0,this.matched.length-this.match.length);return(a.length>20?"...":"")+a.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var a=this.match;return a.length<20&&(a+=this._input.substr(0,20-a.length)),(a.substr(0,20)+(a.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var a=this.pastInput(),b=new Array(a.length+1).join("-");return a+this.upcomingInput()+"\n"+b+"^"},next:function(){if(this.done)return this.EOF;this._input||(this.done=!0);var a,b,c,d,e;this._more||(this.yytext="",this.match="");for(var f=this._currentRules(),g=0;g<f.length&&(c=this._input.match(this.rules[f[g]]),!c||b&&!(c[0].length>b[0].length)||(b=c,d=g,this.options.flex));g++);return b?(e=b[0].match(/(?:\r\n?|\n).*/g),e&&(this.yylineno+=e.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:e?e[e.length-1].length-e[e.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+b[0].length},this.yytext+=b[0],this.match+=b[0],this.matches=b,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._input=this._input.slice(b[0].length),this.matched+=b[0],a=this.performAction.call(this,this.yy,this,f[d],this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),a?a:void 0):""===this._input?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){var a=this.next();return"undefined"!=typeof a?a:this.lex()},begin:function(a){this.conditionStack.push(a)},popState:function(){return this.conditionStack.pop()},_currentRules:function(){return this.conditions[this.conditionStack[this.conditionStack.length-1]].rules},topState:function(){return this.conditionStack[this.conditionStack.length-2]},pushState:function(a){this.begin(a)}};return a.options={},a.performAction=function(a,b,c,d){function e(a,c){return b.yytext=b.yytext.substr(a,b.yyleng-c)}switch(c){case 0:if("\\\\"===b.yytext.slice(-2)?(e(0,1),this.begin("mu")):"\\"===b.yytext.slice(-1)?(e(0,1),this.begin("emu")):this.begin("mu"),b.yytext)return 15;break;case 1:return 15;case 2:return this.popState(),15;case 3:return this.begin("raw"),15;case 4:return this.popState(),"raw"===this.conditionStack[this.conditionStack.length-1]?15:(b.yytext=b.yytext.substr(5,b.yyleng-9),"END_RAW_BLOCK");case 5:return 15;case 6:return this.popState(),14;case 7:return 65;case 8:return 68;case 9:return 19;case 10:return this.popState(),this.begin("raw"),23;case 11:return 55;case 12:return 60;case 13:return 29;case 14:return 47;case 15:return this.popState(),44;case 16:return this.popState(),44;case 17:return 34;case 18:return 39;case 19:return 51;case 20:return 48;case 21:this.unput(b.yytext),this.popState(),this.begin("com");break;case 22:return this.popState(),14;case 23:return 48;case 24:return 73;case 25:return 72;case 26:return 72;case 27:return 87;case 28:break;case 29:return this.popState(),54;case 30:return this.popState(),33;case 31:return b.yytext=e(1,2).replace(/\\"/g,'"'),80;case 32:return b.yytext=e(1,2).replace(/\\'/g,"'"),80;case 33:return 85;case 34:return 82;case 35:return 82;case 36:return 83;case 37:return 84;case 38:return 81;case 39:return 75;case 40:return 77;case 41:return 72;case 42:return b.yytext=b.yytext.replace(/\\([\\\]])/g,"$1"),72;case 43:return"INVALID";case 44:return 5}},a.rules=[/^(?:[^\x00]*?(?=(\{\{)))/,/^(?:[^\x00]+)/,/^(?:[^\x00]{2,}?(?=(\{\{|\\\{\{|\\\\\{\{|$)))/,/^(?:\{\{\{\{(?=[^\/]))/,/^(?:\{\{\{\{\/[^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=[=}\s\/.])\}\}\}\})/,/^(?:[^\x00]*?(?=(\{\{\{\{)))/,/^(?:[\s\S]*?--(~)?\}\})/,/^(?:\()/,/^(?:\))/,/^(?:\{\{\{\{)/,/^(?:\}\}\}\})/,/^(?:\{\{(~)?>)/,/^(?:\{\{(~)?#>)/,/^(?:\{\{(~)?#\*?)/,/^(?:\{\{(~)?\/)/,/^(?:\{\{(~)?\^\s*(~)?\}\})/,/^(?:\{\{(~)?\s*else\s*(~)?\}\})/,/^(?:\{\{(~)?\^)/,/^(?:\{\{(~)?\s*else\b)/,/^(?:\{\{(~)?\{)/,/^(?:\{\{(~)?&)/,/^(?:\{\{(~)?!--)/,/^(?:\{\{(~)?![\s\S]*?\}\})/,/^(?:\{\{(~)?\*?)/,/^(?:=)/,/^(?:\.\.)/,/^(?:\.(?=([=~}\s\/.)|])))/,/^(?:[\/.])/,/^(?:\s+)/,/^(?:\}(~)?\}\})/,/^(?:(~)?\}\})/,/^(?:"(\\["]|[^"])*")/,/^(?:'(\\[']|[^'])*')/,/^(?:@)/,/^(?:true(?=([~}\s)])))/,/^(?:false(?=([~}\s)])))/,/^(?:undefined(?=([~}\s)])))/,/^(?:null(?=([~}\s)])))/,/^(?:-?[0-9]+(?:\.[0-9]+)?(?=([~}\s)])))/,/^(?:as\s+\|)/,/^(?:\|)/,/^(?:([^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=([=~}\s\/.)|]))))/,/^(?:\[(\\\]|[^\]])*\])/,/^(?:.)/,/^(?:$)/],a.conditions={mu:{rules:[7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44],inclusive:!1},emu:{rules:[2],inclusive:!1},com:{rules:[6],inclusive:!1},raw:{rules:[3,4,5],inclusive:!1},INITIAL:{rules:[0,1,44],inclusive:!0}},a}();return b.lexer=c,a.prototype=b,b.Parser=a,new a}();b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";function d(){var a=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];this.options=a}function e(a,b,c){void 0===b&&(b=a.length);var d=a[b-1],e=a[b-2];return d?"ContentStatement"===d.type?(e||!c?/\r?\n\s*?$/:/(^|\r?\n)\s*?$/).test(d.original):void 0:c}function f(a,b,c){void 0===b&&(b=-1);var d=a[b+1],e=a[b+2];return d?"ContentStatement"===d.type?(e||!c?/^\s*?\r?\n/:/^\s*?(\r?\n|$)/).test(d.original):void 0:c}function g(a,b,c){var d=a[null==b?0:b+1];if(d&&"ContentStatement"===d.type&&(c||!d.rightStripped)){var e=d.value;d.value=d.value.replace(c?/^\s+/:/^[ \t]*\r?\n?/,""),d.rightStripped=d.value!==e}}function h(a,b,c){var d=a[null==b?a.length-1:b-1];if(d&&"ContentStatement"===d.type&&(c||!d.leftStripped)){var e=d.value;return d.value=d.value.replace(c?/\s+$/:/[ \t]+$/,""),d.leftStripped=d.value!==e,d.leftStripped}}var i=c(1)["default"];b.__esModule=!0;var j=c(39),k=i(j);d.prototype=new k["default"],d.prototype.Program=function(a){var b=!this.options.ignoreStandalone,c=!this.isRootSeen;this.isRootSeen=!0;for(var d=a.body,i=0,j=d.length;i<j;i++){var k=d[i],l=this.accept(k);if(l){var m=e(d,i,c),n=f(d,i,c),o=l.openStandalone&&m,p=l.closeStandalone&&n,q=l.inlineStandalone&&m&&n;l.close&&g(d,i,!0),l.open&&h(d,i,!0),b&&q&&(g(d,i),h(d,i)&&"PartialStatement"===k.type&&(k.indent=/([ \t]+$)/.exec(d[i-1].original)[1])),b&&o&&(g((k.program||k.inverse).body),h(d,i)),b&&p&&(g(d,i),h((k.inverse||k.program).body))}}return a},d.prototype.BlockStatement=d.prototype.DecoratorBlock=d.prototype.PartialBlockStatement=function(a){this.accept(a.program),this.accept(a.inverse);var b=a.program||a.inverse,c=a.program&&a.inverse,d=c,i=c;if(c&&c.chained)for(d=c.body[0].program;i.chained;)i=i.body[i.body.length-1].program;var j={open:a.openStrip.open,close:a.closeStrip.close,openStandalone:f(b.body),closeStandalone:e((d||b).body)};if(a.openStrip.close&&g(b.body,null,!0),c){var k=a.inverseStrip;k.open&&h(b.body,null,!0),k.close&&g(d.body,null,!0),a.closeStrip.open&&h(i.body,null,!0),!this.options.ignoreStandalone&&e(b.body)&&f(d.body)&&(h(b.body),g(d.body))}else a.closeStrip.open&&h(b.body,null,!0);return j},d.prototype.Decorator=d.prototype.MustacheStatement=function(a){return a.strip},d.prototype.PartialStatement=d.prototype.CommentStatement=function(a){var b=a.strip||{};return{inlineStandalone:!0,open:b.open,close:b.close}},b["default"]=d,a.exports=b["default"]},function(a,b,c){"use strict";function d(){this.parents=[]}function e(a){this.acceptRequired(a,"path"),this.acceptArray(a.params),this.acceptKey(a,"hash")}function f(a){e.call(this,a),this.acceptKey(a,"program"),this.acceptKey(a,"inverse")}function g(a){this.acceptRequired(a,"name"),this.acceptArray(a.params),this.acceptKey(a,"hash")}var h=c(1)["default"];b.__esModule=!0;var i=c(6),j=h(i);d.prototype={constructor:d,mutating:!1,acceptKey:function(a,b){var c=this.accept(a[b]);if(this.mutating){if(c&&!d.prototype[c.type])throw new j["default"]('Unexpected node type "'+c.type+'" found when accepting '+b+" on "+a.type);a[b]=c}},acceptRequired:function(a,b){if(this.acceptKey(a,b),!a[b])throw new j["default"](a.type+" requires "+b)},acceptArray:function(a){for(var b=0,c=a.length;b<c;b++)this.acceptKey(a,b),a[b]||(a.splice(b,1),b--,c--)},accept:function(a){if(a){if(!this[a.type])throw new j["default"]("Unknown type: "+a.type,a);this.current&&this.parents.unshift(this.current),this.current=a;var b=this[a.type](a);return this.current=this.parents.shift(),!this.mutating||b?b:b!==!1?a:void 0}},Program:function(a){this.acceptArray(a.body)},MustacheStatement:e,Decorator:e,BlockStatement:f,DecoratorBlock:f,PartialStatement:g,PartialBlockStatement:function(a){g.call(this,a),this.acceptKey(a,"program")},ContentStatement:function(){},CommentStatement:function(){},SubExpression:e,PathExpression:function(){},StringLiteral:function(){},NumberLiteral:function(){},BooleanLiteral:function(){},UndefinedLiteral:function(){},NullLiteral:function(){},Hash:function(a){this.acceptArray(a.pairs)},HashPair:function(a){this.acceptRequired(a,"value")}},b["default"]=d,a.exports=b["default"]},function(a,b,c){"use strict";function d(a,b){if(b=b.path?b.path.original:b,a.path.original!==b){var c={loc:a.path.loc};throw new q["default"](a.path.original+" doesn't match "+b,c)}}function e(a,b){this.source=a,this.start={line:b.first_line,column:b.first_column},this.end={line:b.last_line,column:b.last_column}}function f(a){return/^\[.*\]$/.test(a)?a.substr(1,a.length-2):a}function g(a,b){return{open:"~"===a.charAt(2),close:"~"===b.charAt(b.length-3)}}function h(a){return a.replace(/^\{\{~?\!-?-?/,"").replace(/-?-?~?\}\}$/,"")}function i(a,b,c){c=this.locInfo(c);for(var d=a?"@":"",e=[],f=0,g="",h=0,i=b.length;h<i;h++){var j=b[h].part,k=b[h].original!==j;if(d+=(b[h].separator||"")+j,k||".."!==j&&"."!==j&&"this"!==j)e.push(j);else{if(e.length>0)throw new q["default"]("Invalid path: "+d,{loc:c});".."===j&&(f++,g+="../")}}return{type:"PathExpression",data:a,depth:f,parts:e,original:d,loc:c}}function j(a,b,c,d,e,f){var g=d.charAt(3)||d.charAt(2),h="{"!==g&&"&"!==g,i=/\*/.test(d);return{type:i?"Decorator":"MustacheStatement",path:a,params:b,hash:c,escaped:h,strip:e,loc:this.locInfo(f)}}function k(a,b,c,e){d(a,c),e=this.locInfo(e);var f={type:"Program",body:b,strip:{},loc:e};return{type:"BlockStatement",path:a.path,params:a.params,hash:a.hash,program:f,openStrip:{},inverseStrip:{},closeStrip:{},loc:e}}function l(a,b,c,e,f,g){e&&e.path&&d(a,e);var h=/\*/.test(a.open);b.blockParams=a.blockParams;var i=void 0,j=void 0;if(c){if(h)throw new q["default"]("Unexpected inverse block on decorator",c);c.chain&&(c.program.body[0].closeStrip=e.strip),j=c.strip,i=c.program}return f&&(f=i,i=b,b=f),{type:h?"DecoratorBlock":"BlockStatement",path:a.path,params:a.params,hash:a.hash,program:b,inverse:i,openStrip:a.strip,inverseStrip:j,closeStrip:e&&e.strip,loc:this.locInfo(g)}}function m(a,b){if(!b&&a.length){var c=a[0].loc,d=a[a.length-1].loc;c&&d&&(b={source:c.source,start:{line:c.start.line,column:c.start.column},end:{line:d.end.line,column:d.end.column}})}return{type:"Program",body:a,strip:{},loc:b}}function n(a,b,c,e){return d(a,c),{type:"PartialBlockStatement",name:a.path,params:a.params,hash:a.hash,program:b,openStrip:a.strip,closeStrip:c&&c.strip,loc:this.locInfo(e)}}var o=c(1)["default"];b.__esModule=!0,b.SourceLocation=e,b.id=f,b.stripFlags=g,b.stripComment=h,b.preparePath=i,b.prepareMustache=j,b.prepareRawBlock=k,b.prepareBlock=l,b.prepareProgram=m,b.preparePartialBlock=n;var p=c(6),q=o(p)},function(a,b,c){"use strict";function d(){}function e(a,b,c){if(null==a||"string"!=typeof a&&"Program"!==a.type)throw new k["default"]("You must pass a string or Handlebars AST to Handlebars.precompile. You passed "+a);b=b||{},"data"in b||(b.data=!0),b.compat&&(b.useDepths=!0);var d=c.parse(a,b),e=(new c.Compiler).compile(d,b);return(new c.JavaScriptCompiler).compile(e,b)}function f(a,b,c){function d(){var d=c.parse(a,b),e=(new c.Compiler).compile(d,b),f=(new c.JavaScriptCompiler).compile(e,b,void 0,!0);return c.template(f)}function e(a,b){return f||(f=d()),f.call(this,a,b)}if(void 0===b&&(b={}),null==a||"string"!=typeof a&&"Program"!==a.type)throw new k["default"]("You must pass a string or Handlebars AST to Handlebars.compile. You passed "+a);b=l.extend({},b),"data"in b||(b.data=!0),b.compat&&(b.useDepths=!0);var f=void 0;return e._setup=function(a){return f||(f=d()),f._setup(a)},e._child=function(a,b,c,e){return f||(f=d()),f._child(a,b,c,e)},e}function g(a,b){if(a===b)return!0;if(l.isArray(a)&&l.isArray(b)&&a.length===b.length){for(var c=0;c<a.length;c++)if(!g(a[c],b[c]))return!1;return!0}}function h(a){if(!a.path.parts){var b=a.path;a.path={type:"PathExpression",data:!1,depth:0,parts:[b.original+""],original:b.original+"",loc:b.loc}}}var i=c(1)["default"];b.__esModule=!0,b.Compiler=d,b.precompile=e,b.compile=f;var j=c(6),k=i(j),l=c(5),m=c(35),n=i(m),o=[].slice;d.prototype={compiler:d,equals:function(a){var b=this.opcodes.length;if(a.opcodes.length!==b)return!1;for(var c=0;c<b;c++){var d=this.opcodes[c],e=a.opcodes[c];if(d.opcode!==e.opcode||!g(d.args,e.args))return!1}b=this.children.length;for(var c=0;c<b;c++)if(!this.children[c].equals(a.children[c]))return!1;return!0},guid:0,compile:function(a,b){this.sourceNode=[],this.opcodes=[],this.children=[],this.options=b,this.stringParams=b.stringParams,this.trackIds=b.trackIds,b.blockParams=b.blockParams||[];var c=b.knownHelpers;if(b.knownHelpers={helperMissing:!0,blockHelperMissing:!0,each:!0,"if":!0,unless:!0,"with":!0,log:!0,lookup:!0},c)for(var d in c)d in c&&(this.options.knownHelpers[d]=c[d]);return this.accept(a)},compileProgram:function(a){var b=new this.compiler,c=b.compile(a,this.options),d=this.guid++;return this.usePartial=this.usePartial||c.usePartial,this.children[d]=c,this.useDepths=this.useDepths||c.useDepths,d},accept:function(a){if(!this[a.type])throw new k["default"]("Unknown type: "+a.type,a);this.sourceNode.unshift(a);var b=this[a.type](a);return this.sourceNode.shift(),b},Program:function(a){this.options.blockParams.unshift(a.blockParams);for(var b=a.body,c=b.length,d=0;d<c;d++)this.accept(b[d]);return this.options.blockParams.shift(),this.isSimple=1===c,this.blockParams=a.blockParams?a.blockParams.length:0,this},BlockStatement:function(a){h(a);var b=a.program,c=a.inverse;b=b&&this.compileProgram(b),c=c&&this.compileProgram(c);var d=this.classifySexpr(a);"helper"===d?this.helperSexpr(a,b,c):"simple"===d?(this.simpleSexpr(a),this.opcode("pushProgram",b),this.opcode("pushProgram",c),this.opcode("emptyHash"),this.opcode("blockValue",a.path.original)):(this.ambiguousSexpr(a,b,c),this.opcode("pushProgram",b),this.opcode("pushProgram",c),this.opcode("emptyHash"),this.opcode("ambiguousBlockValue")),this.opcode("append")},DecoratorBlock:function(a){var b=a.program&&this.compileProgram(a.program),c=this.setupFullMustacheParams(a,b,void 0),d=a.path;this.useDecorators=!0,this.opcode("registerDecorator",c.length,d.original)},PartialStatement:function(a){this.usePartial=!0;var b=a.program;b&&(b=this.compileProgram(a.program));var c=a.params;if(c.length>1)throw new k["default"]("Unsupported number of partial arguments: "+c.length,a);c.length||(this.options.explicitPartialContext?this.opcode("pushLiteral","undefined"):c.push({type:"PathExpression",parts:[],depth:0}));var d=a.name.original,e="SubExpression"===a.name.type;e&&this.accept(a.name),this.setupFullMustacheParams(a,b,void 0,!0);var f=a.indent||"";this.options.preventIndent&&f&&(this.opcode("appendContent",f),f=""),this.opcode("invokePartial",e,d,f),this.opcode("append")},PartialBlockStatement:function(a){this.PartialStatement(a)},MustacheStatement:function(a){this.SubExpression(a),a.escaped&&!this.options.noEscape?this.opcode("appendEscaped"):this.opcode("append")},Decorator:function(a){this.DecoratorBlock(a)},ContentStatement:function(a){a.value&&this.opcode("appendContent",a.value)},CommentStatement:function(){},SubExpression:function(a){h(a);var b=this.classifySexpr(a);"simple"===b?this.simpleSexpr(a):"helper"===b?this.helperSexpr(a):this.ambiguousSexpr(a)},ambiguousSexpr:function(a,b,c){var d=a.path,e=d.parts[0],f=null!=b||null!=c;this.opcode("getContext",d.depth),this.opcode("pushProgram",b),this.opcode("pushProgram",c),d.strict=!0,this.accept(d),this.opcode("invokeAmbiguous",e,f)},simpleSexpr:function(a){var b=a.path;b.strict=!0,this.accept(b),this.opcode("resolvePossibleLambda")},helperSexpr:function(a,b,c){var d=this.setupFullMustacheParams(a,b,c),e=a.path,f=e.parts[0];if(this.options.knownHelpers[f])this.opcode("invokeKnownHelper",d.length,f);else{if(this.options.knownHelpersOnly)throw new k["default"]("You specified knownHelpersOnly, but used the unknown helper "+f,a);e.strict=!0,e.falsy=!0,this.accept(e),this.opcode("invokeHelper",d.length,e.original,n["default"].helpers.simpleId(e))}},PathExpression:function(a){this.addDepth(a.depth),this.opcode("getContext",a.depth);var b=a.parts[0],c=n["default"].helpers.scopedId(a),d=!a.depth&&!c&&this.blockParamIndex(b);d?this.opcode("lookupBlockParam",d,a.parts):b?a.data?(this.options.data=!0,this.opcode("lookupData",a.depth,a.parts,a.strict)):this.opcode("lookupOnContext",a.parts,a.falsy,a.strict,c):this.opcode("pushContext")},StringLiteral:function(a){this.opcode("pushString",a.value)},NumberLiteral:function(a){this.opcode("pushLiteral",a.value)},BooleanLiteral:function(a){this.opcode("pushLiteral",a.value)},UndefinedLiteral:function(){this.opcode("pushLiteral","undefined")},NullLiteral:function(){this.opcode("pushLiteral","null")},Hash:function(a){var b=a.pairs,c=0,d=b.length;for(this.opcode("pushHash");c<d;c++)this.pushParam(b[c].value);for(;c--;)this.opcode("assignToHash",b[c].key);this.opcode("popHash")},opcode:function(a){this.opcodes.push({opcode:a,args:o.call(arguments,1),loc:this.sourceNode[0].loc})},addDepth:function(a){a&&(this.useDepths=!0)},classifySexpr:function(a){var b=n["default"].helpers.simpleId(a.path),c=b&&!!this.blockParamIndex(a.path.parts[0]),d=!c&&n["default"].helpers.helperExpression(a),e=!c&&(d||b);if(e&&!d){var f=a.path.parts[0],g=this.options;g.knownHelpers[f]?d=!0:g.knownHelpersOnly&&(e=!1)}return d?"helper":e?"ambiguous":"simple"},pushParams:function(a){for(var b=0,c=a.length;b<c;b++)this.pushParam(a[b])},pushParam:function(a){var b=null!=a.value?a.value:a.original||"";if(this.stringParams)b.replace&&(b=b.replace(/^(\.?\.\/)*/g,"").replace(/\//g,".")),a.depth&&this.addDepth(a.depth),this.opcode("getContext",a.depth||0),this.opcode("pushStringParam",b,a.type),"SubExpression"===a.type&&this.accept(a);else{if(this.trackIds){var c=void 0;if(!a.parts||n["default"].helpers.scopedId(a)||a.depth||(c=this.blockParamIndex(a.parts[0])),c){var d=a.parts.slice(1).join(".");this.opcode("pushId","BlockParam",c,d)}else b=a.original||b,b.replace&&(b=b.replace(/^this(?:\.|$)/,"").replace(/^\.\//,"").replace(/^\.$/,"")),this.opcode("pushId",a.type,b)}this.accept(a)}},setupFullMustacheParams:function(a,b,c,d){var e=a.params;return this.pushParams(e),this.opcode("pushProgram",b),this.opcode("pushProgram",c),a.hash?this.accept(a.hash):this.opcode("emptyHash",d),e},blockParamIndex:function(a){for(var b=0,c=this.options.blockParams.length;b<c;b++){var d=this.options.blockParams[b],e=d&&l.indexOf(d,a);if(d&&e>=0)return[b,e]}}}},function(a,b,c){"use strict";function d(a){this.value=a}function e(){}function f(a,b,c,d){var e=b.popStack(),f=0,g=c.length;for(a&&g--;f<g;f++)e=b.nameLookup(e,c[f],d);return a?[b.aliasable("container.strict"),"(",e,", ",b.quotedString(c[f]),")"]:e}var g=c(1)["default"];b.__esModule=!0;var h=c(4),i=c(6),j=g(i),k=c(5),l=c(43),m=g(l);e.prototype={nameLookup:function(a,b){return e.isValidJavaScriptVariableName(b)?[a,".",b]:[a,"[",JSON.stringify(b),"]"]},depthedLookup:function(a){return[this.aliasable("container.lookup"),'(depths, "',a,'")']},compilerInfo:function(){var a=h.COMPILER_REVISION,b=h.REVISION_CHANGES[a];return[a,b]},appendToBuffer:function(a,b,c){return k.isArray(a)||(a=[a]),a=this.source.wrap(a,b),this.environment.isSimple?["return ",a,";"]:c?["buffer += ",a,";"]:(a.appendToBuffer=!0,a)},initializeBuffer:function(){return this.quotedString("")},compile:function(a,b,c,d){this.environment=a,this.options=b,this.stringParams=this.options.stringParams,this.trackIds=this.options.trackIds,this.precompile=!d,this.name=this.environment.name,this.isChild=!!c,this.context=c||{decorators:[],programs:[],environments:[]},this.preamble(),this.stackSlot=0,this.stackVars=[],this.aliases={},this.registers={list:[]},this.hashes=[],this.compileStack=[],this.inlineStack=[],this.blockParams=[],this.compileChildren(a,b),this.useDepths=this.useDepths||a.useDepths||a.useDecorators||this.options.compat,this.useBlockParams=this.useBlockParams||a.useBlockParams;var e=a.opcodes,f=void 0,g=void 0,h=void 0,i=void 0;for(h=0,i=e.length;h<i;h++)f=e[h],this.source.currentLocation=f.loc,g=g||f.loc,this[f.opcode].apply(this,f.args);if(this.source.currentLocation=g,this.pushSource(""),this.stackSlot||this.inlineStack.length||this.compileStack.length)throw new j["default"]("Compile completed with content left on stack");this.decorators.isEmpty()?this.decorators=void 0:(this.useDecorators=!0,this.decorators.prepend("var decorators = container.decorators;\n"),this.decorators.push("return fn;"),d?this.decorators=Function.apply(this,["fn","props","container","depth0","data","blockParams","depths",this.decorators.merge()]):(this.decorators.prepend("function(fn, props, container, depth0, data, blockParams, depths) {\n"),this.decorators.push("}\n"),this.decorators=this.decorators.merge()));var k=this.createFunctionContext(d);if(this.isChild)return k;var l={compiler:this.compilerInfo(),main:k};this.decorators&&(l.main_d=this.decorators,l.useDecorators=!0);var m=this.context,n=m.programs,o=m.decorators;for(h=0,i=n.length;h<i;h++)n[h]&&(l[h]=n[h],o[h]&&(l[h+"_d"]=o[h],l.useDecorators=!0));return this.environment.usePartial&&(l.usePartial=!0),this.options.data&&(l.useData=!0),this.useDepths&&(l.useDepths=!0),this.useBlockParams&&(l.useBlockParams=!0),this.options.compat&&(l.compat=!0),d?l.compilerOptions=this.options:(l.compiler=JSON.stringify(l.compiler),this.source.currentLocation={start:{line:1,column:0}},l=this.objectLiteral(l),b.srcName?(l=l.toStringWithSourceMap({file:b.destName}),l.map=l.map&&l.map.toString()):l=l.toString()),l},preamble:function(){this.lastContext=0,this.source=new m["default"](this.options.srcName),this.decorators=new m["default"](this.options.srcName)},createFunctionContext:function(a){var b="",c=this.stackVars.concat(this.registers.list);c.length>0&&(b+=", "+c.join(", "));var d=0;for(var e in this.aliases){var f=this.aliases[e];this.aliases.hasOwnProperty(e)&&f.children&&f.referenceCount>1&&(b+=", alias"+ ++d+"="+e,f.children[0]="alias"+d)}var g=["container","depth0","helpers","partials","data"];(this.useBlockParams||this.useDepths)&&g.push("blockParams"),this.useDepths&&g.push("depths");var h=this.mergeSource(b);return a?(g.push(h),Function.apply(this,g)):this.source.wrap(["function(",g.join(","),") {\n ",h,"}"])},mergeSource:function(a){var b=this.environment.isSimple,c=!this.forceBuffer,d=void 0,e=void 0,f=void 0,g=void 0;return this.source.each(function(a){a.appendToBuffer?(f?a.prepend(" + "):f=a,g=a):(f&&(e?f.prepend("buffer += "):d=!0,g.add(";"),f=g=void 0),e=!0,b||(c=!1))}),c?f?(f.prepend("return "),g.add(";")):e||this.source.push('return "";'):(a+=", buffer = "+(d?"":this.initializeBuffer()),f?(f.prepend("return buffer + "),g.add(";")):this.source.push("return buffer;")),a&&this.source.prepend("var "+a.substring(2)+(d?"":";\n")),this.source.merge()},blockValue:function(a){var b=this.aliasable("helpers.blockHelperMissing"),c=[this.contextName(0)];this.setupHelperArgs(a,0,c);var d=this.popStack();c.splice(1,0,d),this.push(this.source.functionCall(b,"call",c))},ambiguousBlockValue:function(){var a=this.aliasable("helpers.blockHelperMissing"),b=[this.contextName(0)];this.setupHelperArgs("",0,b,!0),this.flushInline();var c=this.topStack();b.splice(1,0,c),this.pushSource(["if (!",this.lastHelper,") { ",c," = ",this.source.functionCall(a,"call",b),"}"])},appendContent:function(a){this.pendingContent?a=this.pendingContent+a:this.pendingLocation=this.source.currentLocation,this.pendingContent=a},append:function(){if(this.isInline())this.replaceStack(function(a){return[" != null ? ",a,' : ""']}),this.pushSource(this.appendToBuffer(this.popStack()));else{var a=this.popStack();this.pushSource(["if (",a," != null) { ",this.appendToBuffer(a,void 0,!0)," }"]),this.environment.isSimple&&this.pushSource(["else { ",this.appendToBuffer("''",void 0,!0)," }"])}},appendEscaped:function(){this.pushSource(this.appendToBuffer([this.aliasable("container.escapeExpression"),"(",this.popStack(),")"]))},getContext:function(a){this.lastContext=a},pushContext:function(){this.pushStackLiteral(this.contextName(this.lastContext))},lookupOnContext:function(a,b,c,d){var e=0;d||!this.options.compat||this.lastContext?this.pushContext():this.push(this.depthedLookup(a[e++])),this.resolvePath("context",a,e,b,c)},lookupBlockParam:function(a,b){this.useBlockParams=!0,this.push(["blockParams[",a[0],"][",a[1],"]"]),this.resolvePath("context",b,1)},lookupData:function(a,b,c){a?this.pushStackLiteral("container.data(data, "+a+")"):this.pushStackLiteral("data"),this.resolvePath("data",b,0,!0,c)},resolvePath:function(a,b,c,d,e){var g=this;if(this.options.strict||this.options.assumeObjects)return void this.push(f(this.options.strict&&e,this,b,a));for(var h=b.length;c<h;c++)this.replaceStack(function(e){
  94520. var f=g.nameLookup(e,b[c],a);return d?[" && ",f]:[" != null ? ",f," : ",e]})},resolvePossibleLambda:function(){this.push([this.aliasable("container.lambda"),"(",this.popStack(),", ",this.contextName(0),")"])},pushStringParam:function(a,b){this.pushContext(),this.pushString(b),"SubExpression"!==b&&("string"==typeof a?this.pushString(a):this.pushStackLiteral(a))},emptyHash:function(a){this.trackIds&&this.push("{}"),this.stringParams&&(this.push("{}"),this.push("{}")),this.pushStackLiteral(a?"undefined":"{}")},pushHash:function(){this.hash&&this.hashes.push(this.hash),this.hash={values:[],types:[],contexts:[],ids:[]}},popHash:function(){var a=this.hash;this.hash=this.hashes.pop(),this.trackIds&&this.push(this.objectLiteral(a.ids)),this.stringParams&&(this.push(this.objectLiteral(a.contexts)),this.push(this.objectLiteral(a.types))),this.push(this.objectLiteral(a.values))},pushString:function(a){this.pushStackLiteral(this.quotedString(a))},pushLiteral:function(a){this.pushStackLiteral(a)},pushProgram:function(a){null!=a?this.pushStackLiteral(this.programExpression(a)):this.pushStackLiteral(null)},registerDecorator:function(a,b){var c=this.nameLookup("decorators",b,"decorator"),d=this.setupHelperArgs(b,a);this.decorators.push(["fn = ",this.decorators.functionCall(c,"",["fn","props","container",d])," || fn;"])},invokeHelper:function(a,b,c){var d=this.popStack(),e=this.setupHelper(a,b),f=c?[e.name," || "]:"",g=["("].concat(f,d);this.options.strict||g.push(" || ",this.aliasable("helpers.helperMissing")),g.push(")"),this.push(this.source.functionCall(g,"call",e.callParams))},invokeKnownHelper:function(a,b){var c=this.setupHelper(a,b);this.push(this.source.functionCall(c.name,"call",c.callParams))},invokeAmbiguous:function(a,b){this.useRegister("helper");var c=this.popStack();this.emptyHash();var d=this.setupHelper(0,a,b),e=this.lastHelper=this.nameLookup("helpers",a,"helper"),f=["(","(helper = ",e," || ",c,")"];this.options.strict||(f[0]="(helper = ",f.push(" != null ? helper : ",this.aliasable("helpers.helperMissing"))),this.push(["(",f,d.paramsInit?["),(",d.paramsInit]:[],"),","(typeof helper === ",this.aliasable('"function"')," ? ",this.source.functionCall("helper","call",d.callParams)," : helper))"])},invokePartial:function(a,b,c){var d=[],e=this.setupParams(b,1,d);a&&(b=this.popStack(),delete e.name),c&&(e.indent=JSON.stringify(c)),e.helpers="helpers",e.partials="partials",e.decorators="container.decorators",a?d.unshift(b):d.unshift(this.nameLookup("partials",b,"partial")),this.options.compat&&(e.depths="depths"),e=this.objectLiteral(e),d.push(e),this.push(this.source.functionCall("container.invokePartial","",d))},assignToHash:function(a){var b=this.popStack(),c=void 0,d=void 0,e=void 0;this.trackIds&&(e=this.popStack()),this.stringParams&&(d=this.popStack(),c=this.popStack());var f=this.hash;c&&(f.contexts[a]=c),d&&(f.types[a]=d),e&&(f.ids[a]=e),f.values[a]=b},pushId:function(a,b,c){"BlockParam"===a?this.pushStackLiteral("blockParams["+b[0]+"].path["+b[1]+"]"+(c?" + "+JSON.stringify("."+c):"")):"PathExpression"===a?this.pushString(b):"SubExpression"===a?this.pushStackLiteral("true"):this.pushStackLiteral("null")},compiler:e,compileChildren:function(a,b){for(var c=a.children,d=void 0,e=void 0,f=0,g=c.length;f<g;f++){d=c[f],e=new this.compiler;var h=this.matchExistingProgram(d);if(null==h){this.context.programs.push("");var i=this.context.programs.length;d.index=i,d.name="program"+i,this.context.programs[i]=e.compile(d,b,this.context,!this.precompile),this.context.decorators[i]=e.decorators,this.context.environments[i]=d,this.useDepths=this.useDepths||e.useDepths,this.useBlockParams=this.useBlockParams||e.useBlockParams,d.useDepths=this.useDepths,d.useBlockParams=this.useBlockParams}else d.index=h.index,d.name="program"+h.index,this.useDepths=this.useDepths||h.useDepths,this.useBlockParams=this.useBlockParams||h.useBlockParams}},matchExistingProgram:function(a){for(var b=0,c=this.context.environments.length;b<c;b++){var d=this.context.environments[b];if(d&&d.equals(a))return d}},programExpression:function(a){var b=this.environment.children[a],c=[b.index,"data",b.blockParams];return(this.useBlockParams||this.useDepths)&&c.push("blockParams"),this.useDepths&&c.push("depths"),"container.program("+c.join(", ")+")"},useRegister:function(a){this.registers[a]||(this.registers[a]=!0,this.registers.list.push(a))},push:function(a){return a instanceof d||(a=this.source.wrap(a)),this.inlineStack.push(a),a},pushStackLiteral:function(a){this.push(new d(a))},pushSource:function(a){this.pendingContent&&(this.source.push(this.appendToBuffer(this.source.quotedString(this.pendingContent),this.pendingLocation)),this.pendingContent=void 0),a&&this.source.push(a)},replaceStack:function(a){var b=["("],c=void 0,e=void 0,f=void 0;if(!this.isInline())throw new j["default"]("replaceStack on non-inline");var g=this.popStack(!0);if(g instanceof d)c=[g.value],b=["(",c],f=!0;else{e=!0;var h=this.incrStack();b=["((",this.push(h)," = ",g,")"],c=this.topStack()}var i=a.call(this,c);f||this.popStack(),e&&this.stackSlot--,this.push(b.concat(i,")"))},incrStack:function(){return this.stackSlot++,this.stackSlot>this.stackVars.length&&this.stackVars.push("stack"+this.stackSlot),this.topStackName()},topStackName:function(){return"stack"+this.stackSlot},flushInline:function(){var a=this.inlineStack;this.inlineStack=[];for(var b=0,c=a.length;b<c;b++){var e=a[b];if(e instanceof d)this.compileStack.push(e);else{var f=this.incrStack();this.pushSource([f," = ",e,";"]),this.compileStack.push(f)}}},isInline:function(){return this.inlineStack.length},popStack:function(a){var b=this.isInline(),c=(b?this.inlineStack:this.compileStack).pop();if(!a&&c instanceof d)return c.value;if(!b){if(!this.stackSlot)throw new j["default"]("Invalid stack pop");this.stackSlot--}return c},topStack:function(){var a=this.isInline()?this.inlineStack:this.compileStack,b=a[a.length-1];return b instanceof d?b.value:b},contextName:function(a){return this.useDepths&&a?"depths["+a+"]":"depth"+a},quotedString:function(a){return this.source.quotedString(a)},objectLiteral:function(a){return this.source.objectLiteral(a)},aliasable:function(a){var b=this.aliases[a];return b?(b.referenceCount++,b):(b=this.aliases[a]=this.source.wrap(a),b.aliasable=!0,b.referenceCount=1,b)},setupHelper:function(a,b,c){var d=[],e=this.setupHelperArgs(b,a,d,c),f=this.nameLookup("helpers",b,"helper"),g=this.aliasable(this.contextName(0)+" != null ? "+this.contextName(0)+" : (container.nullContext || {})");return{params:d,paramsInit:e,name:f,callParams:[g].concat(d)}},setupParams:function(a,b,c){var d={},e=[],f=[],g=[],h=!c,i=void 0;h&&(c=[]),d.name=this.quotedString(a),d.hash=this.popStack(),this.trackIds&&(d.hashIds=this.popStack()),this.stringParams&&(d.hashTypes=this.popStack(),d.hashContexts=this.popStack());var j=this.popStack(),k=this.popStack();(k||j)&&(d.fn=k||"container.noop",d.inverse=j||"container.noop");for(var l=b;l--;)i=this.popStack(),c[l]=i,this.trackIds&&(g[l]=this.popStack()),this.stringParams&&(f[l]=this.popStack(),e[l]=this.popStack());return h&&(d.args=this.source.generateArray(c)),this.trackIds&&(d.ids=this.source.generateArray(g)),this.stringParams&&(d.types=this.source.generateArray(f),d.contexts=this.source.generateArray(e)),this.options.data&&(d.data="data"),this.useBlockParams&&(d.blockParams="blockParams"),d},setupHelperArgs:function(a,b,c,d){var e=this.setupParams(a,b,c);return e=this.objectLiteral(e),d?(this.useRegister("options"),c.push("options"),["options=",e]):c?(c.push(e),""):e}},function(){for(var a="break else new var case finally return void catch for switch while continue function this with default if throw delete in try do instanceof typeof abstract enum int short boolean export interface static byte extends long super char final native synchronized class float package throws const goto private transient debugger implements protected volatile double import public let yield await null true false".split(" "),b=e.RESERVED_WORDS={},c=0,d=a.length;c<d;c++)b[a[c]]=!0}(),e.isValidJavaScriptVariableName=function(a){return!e.RESERVED_WORDS[a]&&/^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(a)},b["default"]=e,a.exports=b["default"]},function(a,b,c){"use strict";function d(a,b,c){if(f.isArray(a)){for(var d=[],e=0,g=a.length;e<g;e++)d.push(b.wrap(a[e],c));return d}return"boolean"==typeof a||"number"==typeof a?a+"":a}function e(a){this.srcFile=a,this.source=[]}b.__esModule=!0;var f=c(5),g=void 0;try{}catch(h){}g||(g=function(a,b,c,d){this.src="",d&&this.add(d)},g.prototype={add:function(a){f.isArray(a)&&(a=a.join("")),this.src+=a},prepend:function(a){f.isArray(a)&&(a=a.join("")),this.src=a+this.src},toStringWithSourceMap:function(){return{code:this.toString()}},toString:function(){return this.src}}),e.prototype={isEmpty:function(){return!this.source.length},prepend:function(a,b){this.source.unshift(this.wrap(a,b))},push:function(a,b){this.source.push(this.wrap(a,b))},merge:function(){var a=this.empty();return this.each(function(b){a.add([" ",b,"\n"])}),a},each:function(a){for(var b=0,c=this.source.length;b<c;b++)a(this.source[b])},empty:function(){var a=this.currentLocation||{start:{}};return new g(a.start.line,a.start.column,this.srcFile)},wrap:function(a){var b=arguments.length<=1||void 0===arguments[1]?this.currentLocation||{start:{}}:arguments[1];return a instanceof g?a:(a=d(a,this,b),new g(b.start.line,b.start.column,this.srcFile,a))},functionCall:function(a,b,c){return c=this.generateList(c),this.wrap([a,b?"."+b+"(":"(",c,")"])},quotedString:function(a){return'"'+(a+"").replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")+'"'},objectLiteral:function(a){var b=[];for(var c in a)if(a.hasOwnProperty(c)){var e=d(a[c],this);"undefined"!==e&&b.push([this.quotedString(c),":",e])}var f=this.generateList(b);return f.prepend("{"),f.add("}"),f},generateList:function(a){for(var b=this.empty(),c=0,e=a.length;c<e;c++)c&&b.add(","),b.add(d(a[c],this));return b},generateArray:function(a){var b=this.generateList(a);return b.prepend("["),b.add("]"),b}},b["default"]=e,a.exports=b["default"]}])});
  94521. /***/ }),
  94522. /* 25 */
  94523. /***/ (function(module, exports, __webpack_require__) {
  94524. "use strict";
  94525. Object.defineProperty(exports, "__esModule", { value: true });
  94526. var EventManager = (function () {
  94527. function EventManager(_templateManager) {
  94528. var _this = this;
  94529. this._templateManager = _templateManager;
  94530. this._callbacksContainer = {};
  94531. this._templateManager.onEventTriggered.add(function (eventData) {
  94532. _this._eventTriggered(eventData);
  94533. });
  94534. }
  94535. EventManager.prototype.registerCallback = function (templateName, callback, eventType, selector) {
  94536. if (!this._callbacksContainer[templateName]) {
  94537. this._callbacksContainer[templateName] = [];
  94538. }
  94539. this._callbacksContainer[templateName].push({
  94540. eventType: eventType,
  94541. callback: callback
  94542. });
  94543. };
  94544. EventManager.prototype.unregisterCallback = function (templateName, callback, eventType, selector) {
  94545. var callbackDefs = this._callbacksContainer[templateName] || [];
  94546. this._callbacksContainer[templateName] = callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); });
  94547. };
  94548. EventManager.prototype._eventTriggered = function (data) {
  94549. var templateName = data.template.name;
  94550. var eventType = data.event.type;
  94551. var selector = data.selector;
  94552. var callbackDefs = this._callbacksContainer[templateName] || [];
  94553. callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); }).forEach(function (callbackDef) {
  94554. callbackDef.callback(data);
  94555. });
  94556. };
  94557. EventManager.prototype.dispose = function () {
  94558. this._callbacksContainer = {};
  94559. };
  94560. return EventManager;
  94561. }());
  94562. exports.EventManager = EventManager;
  94563. /***/ }),
  94564. /* 26 */
  94565. /***/ (function(module, exports, __webpack_require__) {
  94566. "use strict";
  94567. Object.defineProperty(exports, "__esModule", { value: true });
  94568. var mappers_1 = __webpack_require__(1);
  94569. var types_1 = __webpack_require__(27);
  94570. var deepmerge = __webpack_require__(2);
  94571. var babylonjs_1 = __webpack_require__(0);
  94572. var ConfigurationLoader = (function () {
  94573. function ConfigurationLoader(_enableCache) {
  94574. if (_enableCache === void 0) { _enableCache = false; }
  94575. this._enableCache = _enableCache;
  94576. this._configurationCache = {};
  94577. this._loadRequests = [];
  94578. }
  94579. ConfigurationLoader.prototype.loadConfiguration = function (initConfig, callback) {
  94580. var _this = this;
  94581. if (initConfig === void 0) { initConfig = {}; }
  94582. var loadedConfig = deepmerge({}, initConfig);
  94583. var extendedConfiguration = types_1.getConfigurationType(loadedConfig.extends || "");
  94584. loadedConfig = deepmerge(extendedConfiguration, loadedConfig);
  94585. if (loadedConfig.configuration) {
  94586. var mapperType_1 = "json";
  94587. return Promise.resolve().then(function () {
  94588. if (typeof loadedConfig.configuration === "string" || (loadedConfig.configuration && loadedConfig.configuration.url)) {
  94589. var url = '';
  94590. if (typeof loadedConfig.configuration === "string") {
  94591. url = loadedConfig.configuration;
  94592. }
  94593. if (typeof loadedConfig.configuration === "object" && loadedConfig.configuration.url) {
  94594. url = loadedConfig.configuration.url;
  94595. var type = loadedConfig.configuration.mapper;
  94596. if (!type) {
  94597. type = loadedConfig.configuration.url.split('.').pop();
  94598. }
  94599. mapperType_1 = type || mapperType_1;
  94600. }
  94601. return _this._loadFile(url);
  94602. }
  94603. else {
  94604. if (typeof loadedConfig.configuration === "object") {
  94605. mapperType_1 = loadedConfig.configuration.mapper || mapperType_1;
  94606. return loadedConfig.configuration.payload || {};
  94607. }
  94608. return {};
  94609. }
  94610. }).then(function (data) {
  94611. var mapper = mappers_1.mapperManager.getMapper(mapperType_1);
  94612. var parsed = mapper.map(data);
  94613. var merged = deepmerge(loadedConfig, parsed);
  94614. if (callback)
  94615. callback(merged);
  94616. return merged;
  94617. });
  94618. }
  94619. else {
  94620. if (callback)
  94621. callback(loadedConfig);
  94622. return Promise.resolve(loadedConfig);
  94623. }
  94624. };
  94625. ConfigurationLoader.prototype.dispose = function () {
  94626. this._loadRequests.forEach(function (request) {
  94627. request.abort();
  94628. });
  94629. this._loadRequests.length = 0;
  94630. };
  94631. ConfigurationLoader.prototype._loadFile = function (url) {
  94632. var _this = this;
  94633. var cacheReference = this._configurationCache;
  94634. if (this._enableCache && cacheReference[url]) {
  94635. return Promise.resolve(cacheReference[url]);
  94636. }
  94637. return new Promise(function (resolve, reject) {
  94638. var fileRequest = babylonjs_1.Tools.LoadFile(url, function (result) {
  94639. var idx = _this._loadRequests.indexOf(fileRequest);
  94640. if (idx !== -1)
  94641. _this._loadRequests.splice(idx, 1);
  94642. if (_this._enableCache)
  94643. cacheReference[url] = result;
  94644. resolve(result);
  94645. }, undefined, undefined, false, function (request, error) {
  94646. var idx = _this._loadRequests.indexOf(fileRequest);
  94647. if (idx !== -1)
  94648. _this._loadRequests.splice(idx, 1);
  94649. reject(error);
  94650. });
  94651. _this._loadRequests.push(fileRequest);
  94652. });
  94653. };
  94654. return ConfigurationLoader;
  94655. }());
  94656. exports.ConfigurationLoader = ConfigurationLoader;
  94657. /***/ }),
  94658. /* 27 */
  94659. /***/ (function(module, exports, __webpack_require__) {
  94660. "use strict";
  94661. Object.defineProperty(exports, "__esModule", { value: true });
  94662. var minimal_1 = __webpack_require__(28);
  94663. exports.minimalConfiguration = minimal_1.minimalConfiguration;
  94664. var default_1 = __webpack_require__(29);
  94665. exports.defaultConfiguration = default_1.defaultConfiguration;
  94666. var getConfigurationType = function (type) {
  94667. switch (type) {
  94668. case 'default':
  94669. return default_1.defaultConfiguration;
  94670. case 'minimal':
  94671. return minimal_1.minimalConfiguration;
  94672. case 'none':
  94673. return {};
  94674. default:
  94675. return default_1.defaultConfiguration;
  94676. }
  94677. };
  94678. exports.getConfigurationType = getConfigurationType;
  94679. /***/ }),
  94680. /* 28 */
  94681. /***/ (function(module, exports, __webpack_require__) {
  94682. "use strict";
  94683. Object.defineProperty(exports, "__esModule", { value: true });
  94684. exports.minimalConfiguration = {
  94685. version: "0.1",
  94686. templates: {
  94687. main: {
  94688. html: __webpack_require__(7)
  94689. },
  94690. loadingScreen: {
  94691. html: __webpack_require__(8),
  94692. params: {
  94693. backgroundColor: "#000000",
  94694. loadingImage: __webpack_require__(9)
  94695. }
  94696. },
  94697. viewer: {
  94698. html: __webpack_require__(10),
  94699. },
  94700. overlay: {
  94701. html: __webpack_require__(11),
  94702. params: {
  94703. closeImage: __webpack_require__(12),
  94704. closeText: 'Close'
  94705. }
  94706. },
  94707. error: {
  94708. html: __webpack_require__(13)
  94709. }
  94710. },
  94711. engine: {
  94712. antialiasing: true
  94713. }
  94714. };
  94715. /***/ }),
  94716. /* 29 */
  94717. /***/ (function(module, exports, __webpack_require__) {
  94718. "use strict";
  94719. Object.defineProperty(exports, "__esModule", { value: true });
  94720. exports.defaultConfiguration = {
  94721. version: "3.2.0-alpha4",
  94722. templates: {
  94723. main: {
  94724. html: __webpack_require__(7)
  94725. },
  94726. loadingScreen: {
  94727. html: __webpack_require__(8),
  94728. params: {
  94729. backgroundColor: "#000000",
  94730. loadingImage: __webpack_require__(9)
  94731. }
  94732. },
  94733. viewer: {
  94734. html: __webpack_require__(10),
  94735. events: {
  94736. pointerout: true,
  94737. pointerdown: true,
  94738. pointerup: true
  94739. }
  94740. },
  94741. navBar: {
  94742. html: __webpack_require__(30),
  94743. params: {
  94744. buttons: {
  94745. "fullscreen-button": {
  94746. altText: "Fullscreen",
  94747. image: __webpack_require__(31)
  94748. }
  94749. },
  94750. visibilityTimeout: 2000
  94751. },
  94752. events: {
  94753. pointerdown: { 'fullscreen-button': true },
  94754. pointerover: true
  94755. }
  94756. },
  94757. overlay: {
  94758. html: __webpack_require__(11),
  94759. params: {
  94760. closeImage: __webpack_require__(12),
  94761. closeText: 'Close'
  94762. }
  94763. },
  94764. help: {
  94765. html: __webpack_require__(32)
  94766. },
  94767. share: {
  94768. html: __webpack_require__(33)
  94769. },
  94770. error: {
  94771. html: __webpack_require__(13)
  94772. }
  94773. },
  94774. camera: {
  94775. behaviors: {
  94776. autoRotate: 0,
  94777. framing: {
  94778. type: 2,
  94779. zoomOnBoundingInfo: true,
  94780. zoomStopsAnimation: false
  94781. }
  94782. }
  94783. },
  94784. skybox: {
  94785. pbr: true,
  94786. blur: 0.7,
  94787. infiniteDIstance: false,
  94788. },
  94789. ground: true,
  94790. engine: {
  94791. antialiasing: true
  94792. },
  94793. scene: {
  94794. imageProcessingConfiguration: {
  94795. exposure: 1.4,
  94796. contrast: 1.66,
  94797. toneMappingEnabled: true
  94798. }
  94799. }
  94800. };
  94801. /***/ }),
  94802. /* 30 */
  94803. /***/ (function(module, exports) {
  94804. module.exports = "<style>nav-bar{position:absolute;height:160px;width:100%;bottom:0;background-color:rgba(0,0,0,.3);color:#fff;transition:1s;align-items:flex-start;justify-content:space-around;display:flex;flex-direction:column}@media screen and (min-width:768px){nav-bar{align-items:center;flex-direction:row;justify-content:space-between;height:80px}}div.flex-container{display:flex;width:100%}div.thumbnail{position:relative;overflow:hidden;display:block;width:40px;height:40px;background-size:cover;background-position:center;border-radius:20px;margin:0 10px}div.title-container{flex-direction:column;display:flex;justify-content:space-between}span.model-title{font-size:125%}span.model-subtitle{font-size:90%}div.button-container{align-items:center;justify-content:flex-end}div.button{cursor:pointer;height:30px;margin:0 10px}div.button img{height:100%}</style> {{#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=flex-container id=model-metadata> <div class=thumbnail> </div> <div class=title-container> <span class=model-title>{{#if title}}{{title}}{{/if}}</span> <span class=model-subtitle> {{#if subtitle}}{{subtitle}} {{/if}}</span> </div> </div> <div class=\"button-container flex-container\"> {{#eachInMap buttons}} <div id={{id}} class=button> {{#if text}} <span>{{text}}</span>> {{/if}} {{#if image}} <img src={{image}} alt={{altText}}> {{/if}} </div> {{/eachInMap}} </div>";
  94805. /***/ }),
  94806. /* 31 */
  94807. /***/ (function(module, exports) {
  94808. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwAQAAAAB/ecQqAAAAAnRSTlMAAHaTzTgAAAAeSURBVHgBY6ASsP/A/wcXZQNGhCkyAfE24HUndQAAXlkXcQ24P7gAAAAASUVORK5CYII="
  94809. /***/ }),
  94810. /* 32 */
  94811. /***/ (function(module, exports) {
  94812. module.exports = "HELP";
  94813. /***/ }),
  94814. /* 33 */
  94815. /***/ (function(module, exports) {
  94816. module.exports = "SHARE";
  94817. /***/ }),
  94818. /* 34 */
  94819. /***/ (function(module, exports, __webpack_require__) {
  94820. 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};
  94821. 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)}}();
  94822. (function universalModuleDefinition(root, factory) {
  94823. var amdDependencies = [];
  94824. var BABYLON = root.BABYLON;
  94825. if(true) {
  94826. BABYLON = BABYLON || __webpack_require__(0);
  94827. module.exports = factory(BABYLON);
  94828. } else if(typeof define === 'function' && define.amd) {
  94829. amdDependencies.push("babylonjs");
  94830. define("babylonjs-loaders", amdDependencies, factory);
  94831. } else if(typeof exports === 'object') {
  94832. BABYLON = BABYLON || require("babylonjs");
  94833. exports["babylonjs-loaders"] = factory(BABYLON);
  94834. } else {
  94835. root["BABYLON"] = factory(BABYLON);
  94836. }
  94837. })(this, function(BABYLON) {
  94838. BABYLON = BABYLON || this.BABYLON;
  94839. "use strict";
  94840. var BABYLON;
  94841. (function (BABYLON) {
  94842. var STLFileLoader = /** @class */ (function () {
  94843. function STLFileLoader() {
  94844. this.solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g;
  94845. this.facetsPattern = /facet([\s\S]*?)endfacet/g;
  94846. 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;
  94847. 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;
  94848. this.name = "stl";
  94849. // force data to come in as an ArrayBuffer
  94850. // we'll convert to string if it looks like it's an ASCII .stl
  94851. this.extensions = {
  94852. ".stl": { isBinary: true },
  94853. };
  94854. }
  94855. STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  94856. var matches;
  94857. if (this.isBinary(data)) {
  94858. // binary .stl
  94859. var babylonMesh = new BABYLON.Mesh("stlmesh", scene);
  94860. this.parseBinary(babylonMesh, data);
  94861. if (meshes) {
  94862. meshes.push(babylonMesh);
  94863. }
  94864. return true;
  94865. }
  94866. // ASCII .stl
  94867. // convert to string
  94868. var array_buffer = new Uint8Array(data);
  94869. var str = '';
  94870. for (var i = 0; i < data.byteLength; i++) {
  94871. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  94872. }
  94873. data = str;
  94874. while (matches = this.solidPattern.exec(data)) {
  94875. var meshName = matches[1];
  94876. var meshNameFromEnd = matches[3];
  94877. if (meshName != meshNameFromEnd) {
  94878. BABYLON.Tools.Error("Error in STL, solid name != endsolid name");
  94879. return false;
  94880. }
  94881. // check meshesNames
  94882. if (meshesNames && meshName) {
  94883. if (meshesNames instanceof Array) {
  94884. if (!meshesNames.indexOf(meshName)) {
  94885. continue;
  94886. }
  94887. }
  94888. else {
  94889. if (meshName !== meshesNames) {
  94890. continue;
  94891. }
  94892. }
  94893. }
  94894. // stl mesh name can be empty as well
  94895. meshName = meshName || "stlmesh";
  94896. var babylonMesh = new BABYLON.Mesh(meshName, scene);
  94897. this.parseASCII(babylonMesh, matches[2]);
  94898. if (meshes) {
  94899. meshes.push(babylonMesh);
  94900. }
  94901. }
  94902. return true;
  94903. };
  94904. STLFileLoader.prototype.load = function (scene, data, rootUrl) {
  94905. var result = this.importMesh(null, scene, data, rootUrl, null, null, null);
  94906. if (result) {
  94907. scene.createDefaultCameraOrLight();
  94908. }
  94909. return result;
  94910. };
  94911. STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  94912. var container = new BABYLON.AssetContainer(scene);
  94913. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  94914. container.removeAllFromScene();
  94915. return container;
  94916. };
  94917. STLFileLoader.prototype.isBinary = function (data) {
  94918. // check if file size is correct for binary stl
  94919. var faceSize, nFaces, reader;
  94920. reader = new DataView(data);
  94921. faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  94922. nFaces = reader.getUint32(80, true);
  94923. if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {
  94924. return true;
  94925. }
  94926. // check characters higher than ASCII to confirm binary
  94927. var fileLength = reader.byteLength;
  94928. for (var index = 0; index < fileLength; index++) {
  94929. if (reader.getUint8(index) > 127) {
  94930. return true;
  94931. }
  94932. }
  94933. return false;
  94934. };
  94935. STLFileLoader.prototype.parseBinary = function (mesh, data) {
  94936. var reader = new DataView(data);
  94937. var faces = reader.getUint32(80, true);
  94938. var dataOffset = 84;
  94939. var faceLength = 12 * 4 + 2;
  94940. var offset = 0;
  94941. var positions = new Float32Array(faces * 3 * 3);
  94942. var normals = new Float32Array(faces * 3 * 3);
  94943. var indices = new Uint32Array(faces * 3);
  94944. var indicesCount = 0;
  94945. for (var face = 0; face < faces; face++) {
  94946. var start = dataOffset + face * faceLength;
  94947. var normalX = reader.getFloat32(start, true);
  94948. var normalY = reader.getFloat32(start + 4, true);
  94949. var normalZ = reader.getFloat32(start + 8, true);
  94950. for (var i = 1; i <= 3; i++) {
  94951. var vertexstart = start + i * 12;
  94952. // ordering is intentional to match ascii import
  94953. positions[offset] = reader.getFloat32(vertexstart, true);
  94954. positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);
  94955. positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);
  94956. normals[offset] = normalX;
  94957. normals[offset + 2] = normalY;
  94958. normals[offset + 1] = normalZ;
  94959. offset += 3;
  94960. }
  94961. indices[indicesCount] = indicesCount++;
  94962. indices[indicesCount] = indicesCount++;
  94963. indices[indicesCount] = indicesCount++;
  94964. }
  94965. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  94966. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  94967. mesh.setIndices(indices);
  94968. mesh.computeWorldMatrix(true);
  94969. };
  94970. STLFileLoader.prototype.parseASCII = function (mesh, solidData) {
  94971. var positions = [];
  94972. var normals = [];
  94973. var indices = [];
  94974. var indicesCount = 0;
  94975. //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
  94976. var matches;
  94977. while (matches = this.facetsPattern.exec(solidData)) {
  94978. var facet = matches[1];
  94979. //one normal per face
  94980. var normalMatches = this.normalPattern.exec(facet);
  94981. this.normalPattern.lastIndex = 0;
  94982. if (!normalMatches) {
  94983. continue;
  94984. }
  94985. var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
  94986. var vertexMatch;
  94987. while (vertexMatch = this.vertexPattern.exec(facet)) {
  94988. positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
  94989. normals.push(normal[0], normal[1], normal[2]);
  94990. }
  94991. indices.push(indicesCount++, indicesCount++, indicesCount++);
  94992. this.vertexPattern.lastIndex = 0;
  94993. }
  94994. this.facetsPattern.lastIndex = 0;
  94995. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  94996. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  94997. mesh.setIndices(indices);
  94998. mesh.computeWorldMatrix(true);
  94999. };
  95000. return STLFileLoader;
  95001. }());
  95002. BABYLON.STLFileLoader = STLFileLoader;
  95003. if (BABYLON.SceneLoader) {
  95004. BABYLON.SceneLoader.RegisterPlugin(new STLFileLoader());
  95005. }
  95006. })(BABYLON || (BABYLON = {}));
  95007. //# sourceMappingURL=babylon.stlFileLoader.js.map
  95008. "use strict";
  95009. var BABYLON;
  95010. (function (BABYLON) {
  95011. /**
  95012. * Class reading and parsing the MTL file bundled with the obj file.
  95013. */
  95014. var MTLFileLoader = /** @class */ (function () {
  95015. function MTLFileLoader() {
  95016. // All material loaded from the mtl will be set here
  95017. this.materials = [];
  95018. }
  95019. /**
  95020. * This function will read the mtl file and create each material described inside
  95021. * This function could be improve by adding :
  95022. * -some component missing (Ni, Tf...)
  95023. * -including the specific options available
  95024. *
  95025. * @param scene
  95026. * @param data
  95027. * @param rootUrl
  95028. */
  95029. MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) {
  95030. if (data instanceof ArrayBuffer) {
  95031. return;
  95032. }
  95033. //Split the lines from the file
  95034. var lines = data.split('\n');
  95035. //Space char
  95036. var delimiter_pattern = /\s+/;
  95037. //Array with RGB colors
  95038. var color;
  95039. //New material
  95040. var material = null;
  95041. //Look at each line
  95042. for (var i = 0; i < lines.length; i++) {
  95043. var line = lines[i].trim();
  95044. // Blank line or comment
  95045. if (line.length === 0 || line.charAt(0) === '#') {
  95046. continue;
  95047. }
  95048. //Get the first parameter (keyword)
  95049. var pos = line.indexOf(' ');
  95050. var key = (pos >= 0) ? line.substring(0, pos) : line;
  95051. key = key.toLowerCase();
  95052. //Get the data following the key
  95053. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  95054. //This mtl keyword will create the new material
  95055. if (key === "newmtl") {
  95056. //Check if it is the first material.
  95057. // Materials specifications are described after this keyword.
  95058. if (material) {
  95059. //Add the previous material in the material array.
  95060. this.materials.push(material);
  95061. }
  95062. //Create a new material.
  95063. // value is the name of the material read in the mtl file
  95064. material = new BABYLON.StandardMaterial(value, scene);
  95065. }
  95066. else if (key === "kd" && material) {
  95067. // Diffuse color (color under white light) using RGB values
  95068. //value = "r g b"
  95069. color = value.split(delimiter_pattern, 3).map(parseFloat);
  95070. //color = [r,g,b]
  95071. //Set tghe color into the material
  95072. material.diffuseColor = BABYLON.Color3.FromArray(color);
  95073. }
  95074. else if (key === "ka" && material) {
  95075. // Ambient color (color under shadow) using RGB values
  95076. //value = "r g b"
  95077. color = value.split(delimiter_pattern, 3).map(parseFloat);
  95078. //color = [r,g,b]
  95079. //Set tghe color into the material
  95080. material.ambientColor = BABYLON.Color3.FromArray(color);
  95081. }
  95082. else if (key === "ks" && material) {
  95083. // Specular color (color when light is reflected from shiny surface) using RGB values
  95084. //value = "r g b"
  95085. color = value.split(delimiter_pattern, 3).map(parseFloat);
  95086. //color = [r,g,b]
  95087. //Set the color into the material
  95088. material.specularColor = BABYLON.Color3.FromArray(color);
  95089. }
  95090. else if (key === "ke" && material) {
  95091. // Emissive color using RGB values
  95092. color = value.split(delimiter_pattern, 3).map(parseFloat);
  95093. material.emissiveColor = BABYLON.Color3.FromArray(color);
  95094. }
  95095. else if (key === "ns" && material) {
  95096. //value = "Integer"
  95097. material.specularPower = parseFloat(value);
  95098. }
  95099. else if (key === "d" && material) {
  95100. //d is dissolve for current material. It mean alpha for BABYLON
  95101. material.alpha = parseFloat(value);
  95102. //Texture
  95103. //This part can be improved by adding the possible options of texture
  95104. }
  95105. else if (key === "map_ka" && material) {
  95106. // ambient texture map with a loaded image
  95107. //We must first get the folder of the image
  95108. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  95109. }
  95110. else if (key === "map_kd" && material) {
  95111. // Diffuse texture map with a loaded image
  95112. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  95113. }
  95114. else if (key === "map_ks" && material) {
  95115. // Specular texture map with a loaded image
  95116. //We must first get the folder of the image
  95117. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  95118. }
  95119. else if (key === "map_ns") {
  95120. //Specular
  95121. //Specular highlight component
  95122. //We must first get the folder of the image
  95123. //
  95124. //Not supported by BABYLON
  95125. //
  95126. // continue;
  95127. }
  95128. else if (key === "map_bump" && material) {
  95129. //The bump texture
  95130. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  95131. }
  95132. else if (key === "map_d" && material) {
  95133. // The dissolve of the material
  95134. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  95135. //Options for illumination
  95136. }
  95137. else if (key === "illum") {
  95138. //Illumination
  95139. if (value === "0") {
  95140. //That mean Kd == Kd
  95141. }
  95142. else if (value === "1") {
  95143. //Color on and Ambient on
  95144. }
  95145. else if (value === "2") {
  95146. //Highlight on
  95147. }
  95148. else if (value === "3") {
  95149. //Reflection on and Ray trace on
  95150. }
  95151. else if (value === "4") {
  95152. //Transparency: Glass on, Reflection: Ray trace on
  95153. }
  95154. else if (value === "5") {
  95155. //Reflection: Fresnel on and Ray trace on
  95156. }
  95157. else if (value === "6") {
  95158. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  95159. }
  95160. else if (value === "7") {
  95161. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  95162. }
  95163. else if (value === "8") {
  95164. //Reflection on and Ray trace off
  95165. }
  95166. else if (value === "9") {
  95167. //Transparency: Glass on, Reflection: Ray trace off
  95168. }
  95169. else if (value === "10") {
  95170. //Casts shadows onto invisible surfaces
  95171. }
  95172. }
  95173. else {
  95174. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  95175. }
  95176. }
  95177. //At the end of the file, add the last material
  95178. if (material) {
  95179. this.materials.push(material);
  95180. }
  95181. };
  95182. /**
  95183. * Gets the texture for the material.
  95184. *
  95185. * If the material is imported from input file,
  95186. * We sanitize the url to ensure it takes the textre from aside the material.
  95187. *
  95188. * @param rootUrl The root url to load from
  95189. * @param value The value stored in the mtl
  95190. * @return The Texture
  95191. */
  95192. MTLFileLoader._getTexture = function (rootUrl, value, scene) {
  95193. if (!value) {
  95194. return null;
  95195. }
  95196. var url = rootUrl;
  95197. // Load from input file.
  95198. if (rootUrl === "file:") {
  95199. var lastDelimiter = value.lastIndexOf("\\");
  95200. if (lastDelimiter === -1) {
  95201. lastDelimiter = value.lastIndexOf("/");
  95202. }
  95203. if (lastDelimiter > -1) {
  95204. url += value.substr(lastDelimiter + 1);
  95205. }
  95206. else {
  95207. url += value;
  95208. }
  95209. }
  95210. else {
  95211. url += value;
  95212. }
  95213. return new BABYLON.Texture(url, scene);
  95214. };
  95215. return MTLFileLoader;
  95216. }());
  95217. BABYLON.MTLFileLoader = MTLFileLoader;
  95218. var OBJFileLoader = /** @class */ (function () {
  95219. function OBJFileLoader() {
  95220. this.name = "obj";
  95221. this.extensions = ".obj";
  95222. this.obj = /^o/;
  95223. this.group = /^g/;
  95224. this.mtllib = /^mtllib /;
  95225. this.usemtl = /^usemtl /;
  95226. this.smooth = /^s /;
  95227. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  95228. // vn float float float
  95229. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  95230. // vt float float
  95231. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  95232. // f vertex vertex vertex ...
  95233. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  95234. // f vertex/uvs vertex/uvs vertex/uvs ...
  95235. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  95236. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  95237. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  95238. // f vertex//normal vertex//normal vertex//normal ...
  95239. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  95240. }
  95241. /**
  95242. * Calls synchronously the MTL file attached to this obj.
  95243. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  95244. * Without this function materials are not displayed in the first frame (but displayed after).
  95245. * In consequence it is impossible to get material information in your HTML file
  95246. *
  95247. * @param url The URL of the MTL file
  95248. * @param rootUrl
  95249. * @param onSuccess Callback function to be called when the MTL file is loaded
  95250. * @private
  95251. */
  95252. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  95253. //The complete path to the mtl file
  95254. var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;
  95255. // Loads through the babylon tools to allow fileInput search.
  95256. BABYLON.Tools.LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function () { console.warn("Error - Unable to load " + pathOfFile); });
  95257. };
  95258. OBJFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  95259. //get the meshes from OBJ file
  95260. var loadedMeshes = this._parseSolid(meshesNames, scene, data, rootUrl);
  95261. //Push meshes from OBJ file into the variable mesh of this function
  95262. if (meshes) {
  95263. loadedMeshes.forEach(function (mesh) {
  95264. meshes.push(mesh);
  95265. });
  95266. }
  95267. return true;
  95268. };
  95269. OBJFileLoader.prototype.load = function (scene, data, rootUrl) {
  95270. //Get the 3D model
  95271. return this.importMesh(null, scene, data, rootUrl, null, null, null);
  95272. };
  95273. OBJFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  95274. var container = new BABYLON.AssetContainer(scene);
  95275. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  95276. container.removeAllFromScene();
  95277. return container;
  95278. };
  95279. /**
  95280. * Read the OBJ file and create an Array of meshes.
  95281. * Each mesh contains all information given by the OBJ and the MTL file.
  95282. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  95283. *
  95284. * @param meshesNames
  95285. * @param scene BABYLON.Scene The scene where are displayed the data
  95286. * @param data String The content of the obj file
  95287. * @param rootUrl String The path to the folder
  95288. * @returns Array<AbstractMesh>
  95289. * @private
  95290. */
  95291. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  95292. var positions = []; //values for the positions of vertices
  95293. var normals = []; //Values for the normals
  95294. var uvs = []; //Values for the textures
  95295. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  95296. var handledMesh; //The current mesh of meshes array
  95297. var indicesForBabylon = []; //The list of indices for VertexData
  95298. var wrappedPositionForBabylon = []; //The list of position in vectors
  95299. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  95300. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  95301. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  95302. var curPositionInIndices = 0;
  95303. var hasMeshes = false; //Meshes are defined in the file
  95304. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  95305. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  95306. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  95307. var triangles = []; //Indices from new triangles coming from polygons
  95308. var materialNameFromObj = ""; //The name of the current material
  95309. var fileToLoad = ""; //The name of the mtlFile to load
  95310. var materialsFromMTLFile = new MTLFileLoader();
  95311. var objMeshName = ""; //The name of the current obj mesh
  95312. var increment = 1; //Id for meshes created by the multimaterial
  95313. var isFirstMaterial = true;
  95314. /**
  95315. * Search for obj in the given array.
  95316. * This function is called to check if a couple of data already exists in an array.
  95317. *
  95318. * If found, returns the index of the founded tuple index. Returns -1 if not found
  95319. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  95320. * @param obj Array<number>
  95321. * @returns {boolean}
  95322. */
  95323. var isInArray = function (arr, obj) {
  95324. if (!arr[obj[0]])
  95325. arr[obj[0]] = { normals: [], idx: [] };
  95326. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  95327. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  95328. };
  95329. var isInArrayUV = function (arr, obj) {
  95330. if (!arr[obj[0]])
  95331. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  95332. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  95333. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  95334. return arr[obj[0]].idx[idx];
  95335. }
  95336. return -1;
  95337. };
  95338. /**
  95339. * This function set the data for each triangle.
  95340. * Data are position, normals and uvs
  95341. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  95342. * If the tuple already exist, add only their indice
  95343. *
  95344. * @param indicePositionFromObj Integer The index in positions array
  95345. * @param indiceUvsFromObj Integer The index in uvs array
  95346. * @param indiceNormalFromObj Integer The index in normals array
  95347. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  95348. * @param textureVectorFromOBJ Vector3 The value of uvs
  95349. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  95350. */
  95351. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  95352. //Check if this tuple already exists in the list of tuples
  95353. var _index;
  95354. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  95355. _index = isInArrayUV(tuplePosNorm, [
  95356. indicePositionFromObj,
  95357. indiceNormalFromObj,
  95358. indiceUvsFromObj
  95359. ]);
  95360. }
  95361. else {
  95362. _index = isInArray(tuplePosNorm, [
  95363. indicePositionFromObj,
  95364. indiceNormalFromObj
  95365. ]);
  95366. }
  95367. //If it not exists
  95368. if (_index == -1) {
  95369. //Add an new indice.
  95370. //The array of indices is only an array with his length equal to the number of triangles - 1.
  95371. //We add vertices data in this order
  95372. indicesForBabylon.push(wrappedPositionForBabylon.length);
  95373. //Push the position of vertice for Babylon
  95374. //Each element is a BABYLON.Vector3(x,y,z)
  95375. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  95376. //Push the uvs for Babylon
  95377. //Each element is a BABYLON.Vector3(u,v)
  95378. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  95379. //Push the normals for Babylon
  95380. //Each element is a BABYLON.Vector3(x,y,z)
  95381. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  95382. //Add the tuple in the comparison list
  95383. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  95384. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  95385. if (OBJFileLoader.OPTIMIZE_WITH_UV)
  95386. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  95387. }
  95388. else {
  95389. //The tuple already exists
  95390. //Add the index of the already existing tuple
  95391. //At this index we can get the value of position, normal and uvs of vertex
  95392. indicesForBabylon.push(_index);
  95393. }
  95394. };
  95395. /**
  95396. * Transform BABYLON.Vector() object onto 3 digits in an array
  95397. */
  95398. var unwrapData = function () {
  95399. //Every array has the same length
  95400. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  95401. //Push the x, y, z values of each element in the unwrapped array
  95402. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  95403. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  95404. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  95405. }
  95406. // Reset arrays for the next new meshes
  95407. wrappedPositionForBabylon = [];
  95408. wrappedNormalsForBabylon = [];
  95409. wrappedUvsForBabylon = [];
  95410. tuplePosNorm = [];
  95411. curPositionInIndices = 0;
  95412. };
  95413. /**
  95414. * Create triangles from polygons by recursion
  95415. * The best to understand how it works is to draw it in the same time you get the recursion.
  95416. * It is important to notice that a triangle is a polygon
  95417. * We get 4 patterns of face defined in OBJ File :
  95418. * facePattern1 = ["1","2","3","4","5","6"]
  95419. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  95420. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  95421. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  95422. * Each pattern is divided by the same method
  95423. * @param face Array[String] The indices of elements
  95424. * @param v Integer The variable to increment
  95425. */
  95426. var getTriangles = function (face, v) {
  95427. //Work for each element of the array
  95428. if (v + 1 < face.length) {
  95429. //Add on the triangle variable the indexes to obtain triangles
  95430. triangles.push(face[0], face[v], face[v + 1]);
  95431. //Incrementation for recursion
  95432. v += 1;
  95433. //Recursion
  95434. getTriangles(face, v);
  95435. }
  95436. //Result obtained after 2 iterations:
  95437. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  95438. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  95439. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  95440. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  95441. };
  95442. /**
  95443. * Create triangles and push the data for each polygon for the pattern 1
  95444. * In this pattern we get vertice positions
  95445. * @param face
  95446. * @param v
  95447. */
  95448. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  95449. //Get the indices of triangles for each polygon
  95450. getTriangles(face, v);
  95451. //For each element in the triangles array.
  95452. //This var could contains 1 to an infinity of triangles
  95453. for (var k = 0; k < triangles.length; k++) {
  95454. // Set position indice
  95455. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  95456. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  95457. positions[indicePositionFromObj], //Get the vectors data
  95458. BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
  95459. );
  95460. }
  95461. //Reset variable for the next line
  95462. triangles = [];
  95463. };
  95464. /**
  95465. * Create triangles and push the data for each polygon for the pattern 2
  95466. * In this pattern we get vertice positions and uvsu
  95467. * @param face
  95468. * @param v
  95469. */
  95470. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  95471. //Get the indices of triangles for each polygon
  95472. getTriangles(face, v);
  95473. for (var k = 0; k < triangles.length; k++) {
  95474. //triangle[k] = "1/1"
  95475. //Split the data for getting position and uv
  95476. var point = triangles[k].split("/"); // ["1", "1"]
  95477. //Set position indice
  95478. var indicePositionFromObj = parseInt(point[0]) - 1;
  95479. //Set uv indice
  95480. var indiceUvsFromObj = parseInt(point[1]) - 1;
  95481. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  95482. positions[indicePositionFromObj], //Get the values for each element
  95483. uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
  95484. );
  95485. }
  95486. //Reset variable for the next line
  95487. triangles = [];
  95488. };
  95489. /**
  95490. * Create triangles and push the data for each polygon for the pattern 3
  95491. * In this pattern we get vertice positions, uvs and normals
  95492. * @param face
  95493. * @param v
  95494. */
  95495. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  95496. //Get the indices of triangles for each polygon
  95497. getTriangles(face, v);
  95498. for (var k = 0; k < triangles.length; k++) {
  95499. //triangle[k] = "1/1/1"
  95500. //Split the data for getting position, uv, and normals
  95501. var point = triangles[k].split("/"); // ["1", "1", "1"]
  95502. // Set position indice
  95503. var indicePositionFromObj = parseInt(point[0]) - 1;
  95504. // Set uv indice
  95505. var indiceUvsFromObj = parseInt(point[1]) - 1;
  95506. // Set normal indice
  95507. var indiceNormalFromObj = parseInt(point[2]) - 1;
  95508. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  95509. );
  95510. }
  95511. //Reset variable for the next line
  95512. triangles = [];
  95513. };
  95514. /**
  95515. * Create triangles and push the data for each polygon for the pattern 4
  95516. * In this pattern we get vertice positions and normals
  95517. * @param face
  95518. * @param v
  95519. */
  95520. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  95521. getTriangles(face, v);
  95522. for (var k = 0; k < triangles.length; k++) {
  95523. //triangle[k] = "1//1"
  95524. //Split the data for getting position and normals
  95525. var point = triangles[k].split("//"); // ["1", "1"]
  95526. // We check indices, and normals
  95527. var indicePositionFromObj = parseInt(point[0]) - 1;
  95528. var indiceNormalFromObj = parseInt(point[1]) - 1;
  95529. setData(indicePositionFromObj, 1, //Default value for uv
  95530. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  95531. BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
  95532. }
  95533. //Reset variable for the next line
  95534. triangles = [];
  95535. };
  95536. var addPreviousObjMesh = function () {
  95537. //Check if it is not the first mesh. Otherwise we don't have data.
  95538. if (meshesFromObj.length > 0) {
  95539. //Get the previous mesh for applying the data about the faces
  95540. //=> in obj file, faces definition append after the name of the mesh
  95541. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  95542. //Set the data into Array for the mesh
  95543. unwrapData();
  95544. // Reverse tab. Otherwise face are displayed in the wrong sens
  95545. indicesForBabylon.reverse();
  95546. //Set the information for the mesh
  95547. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  95548. handledMesh.indices = indicesForBabylon.slice();
  95549. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  95550. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  95551. handledMesh.uvs = unwrappedUVForBabylon.slice();
  95552. //Reset the array for the next mesh
  95553. indicesForBabylon = [];
  95554. unwrappedPositionsForBabylon = [];
  95555. unwrappedNormalsForBabylon = [];
  95556. unwrappedUVForBabylon = [];
  95557. }
  95558. };
  95559. //Main function
  95560. //Split the file into lines
  95561. var lines = data.split('\n');
  95562. //Look at each line
  95563. for (var i = 0; i < lines.length; i++) {
  95564. var line = lines[i].trim();
  95565. var result;
  95566. //Comment or newLine
  95567. if (line.length === 0 || line.charAt(0) === '#') {
  95568. continue;
  95569. //Get information about one position possible for the vertices
  95570. }
  95571. else if ((result = this.vertexPattern.exec(line)) !== null) {
  95572. //Create a Vector3 with the position x, y, z
  95573. //Value of result:
  95574. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  95575. //Add the Vector in the list of positions
  95576. positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  95577. }
  95578. else if ((result = this.normalPattern.exec(line)) !== null) {
  95579. //Create a Vector3 with the normals x, y, z
  95580. //Value of result
  95581. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  95582. //Add the Vector in the list of normals
  95583. normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  95584. }
  95585. else if ((result = this.uvPattern.exec(line)) !== null) {
  95586. //Create a Vector2 with the normals u, v
  95587. //Value of result
  95588. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  95589. //Add the Vector in the list of uvs
  95590. uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  95591. //Identify patterns of faces
  95592. //Face could be defined in different type of pattern
  95593. }
  95594. else if ((result = this.facePattern3.exec(line)) !== null) {
  95595. //Value of result:
  95596. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  95597. //Set the data for this face
  95598. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  95599. 1);
  95600. }
  95601. else if ((result = this.facePattern4.exec(line)) !== null) {
  95602. //Value of result:
  95603. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  95604. //Set the data for this face
  95605. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  95606. 1);
  95607. }
  95608. else if ((result = this.facePattern2.exec(line)) !== null) {
  95609. //Value of result:
  95610. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  95611. //Set the data for this face
  95612. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  95613. 1);
  95614. }
  95615. else if ((result = this.facePattern1.exec(line)) !== null) {
  95616. //Value of result
  95617. //["f 1 2 3", "1 2 3"...]
  95618. //Set the data for this face
  95619. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  95620. 1);
  95621. //Define a mesh or an object
  95622. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  95623. }
  95624. else if (this.group.test(line) || this.obj.test(line)) {
  95625. //Create a new mesh corresponding to the name of the group.
  95626. //Definition of the mesh
  95627. var objMesh =
  95628. //Set the name of the current obj mesh
  95629. {
  95630. name: line.substring(2).trim(),
  95631. indices: undefined,
  95632. positions: undefined,
  95633. normals: undefined,
  95634. uvs: undefined,
  95635. materialName: ""
  95636. };
  95637. addPreviousObjMesh();
  95638. //Push the last mesh created with only the name
  95639. meshesFromObj.push(objMesh);
  95640. //Set this variable to indicate that now meshesFromObj has objects defined inside
  95641. hasMeshes = true;
  95642. isFirstMaterial = true;
  95643. increment = 1;
  95644. //Keyword for applying a material
  95645. }
  95646. else if (this.usemtl.test(line)) {
  95647. //Get the name of the material
  95648. materialNameFromObj = line.substring(7).trim();
  95649. //If this new material is in the same mesh
  95650. if (!isFirstMaterial) {
  95651. //Set the data for the previous mesh
  95652. addPreviousObjMesh();
  95653. //Create a new mesh
  95654. var objMesh =
  95655. //Set the name of the current obj mesh
  95656. {
  95657. name: objMeshName + "_mm" + increment.toString(),
  95658. indices: undefined,
  95659. positions: undefined,
  95660. normals: undefined,
  95661. uvs: undefined,
  95662. materialName: materialNameFromObj
  95663. };
  95664. increment++;
  95665. //If meshes are already defined
  95666. meshesFromObj.push(objMesh);
  95667. }
  95668. //Set the material name if the previous line define a mesh
  95669. if (hasMeshes && isFirstMaterial) {
  95670. //Set the material name to the previous mesh (1 material per mesh)
  95671. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  95672. isFirstMaterial = false;
  95673. }
  95674. //Keyword for loading the mtl file
  95675. }
  95676. else if (this.mtllib.test(line)) {
  95677. //Get the name of mtl file
  95678. fileToLoad = line.substring(7).trim();
  95679. //Apply smoothing
  95680. }
  95681. else if (this.smooth.test(line)) {
  95682. // smooth shading => apply smoothing
  95683. //Toda y I don't know it work with babylon and with obj.
  95684. //With the obj file an integer is set
  95685. }
  95686. else {
  95687. //If there is another possibility
  95688. console.log("Unhandled expression at line : " + line);
  95689. }
  95690. }
  95691. //At the end of the file, add the last mesh into the meshesFromObj array
  95692. if (hasMeshes) {
  95693. //Set the data for the last mesh
  95694. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  95695. //Reverse indices for displaying faces in the good sens
  95696. indicesForBabylon.reverse();
  95697. //Get the good array
  95698. unwrapData();
  95699. //Set array
  95700. handledMesh.indices = indicesForBabylon;
  95701. handledMesh.positions = unwrappedPositionsForBabylon;
  95702. handledMesh.normals = unwrappedNormalsForBabylon;
  95703. handledMesh.uvs = unwrappedUVForBabylon;
  95704. }
  95705. //If any o or g keyword found, create a mesj with a random id
  95706. if (!hasMeshes) {
  95707. // reverse tab of indices
  95708. indicesForBabylon.reverse();
  95709. //Get positions normals uvs
  95710. unwrapData();
  95711. //Set data for one mesh
  95712. meshesFromObj.push({
  95713. name: BABYLON.Geometry.RandomId(),
  95714. indices: indicesForBabylon,
  95715. positions: unwrappedPositionsForBabylon,
  95716. normals: unwrappedNormalsForBabylon,
  95717. uvs: unwrappedUVForBabylon,
  95718. materialName: materialNameFromObj
  95719. });
  95720. }
  95721. //Create a BABYLON.Mesh list
  95722. var babylonMeshesArray = []; //The mesh for babylon
  95723. var materialToUse = new Array();
  95724. //Set data for each mesh
  95725. for (var j = 0; j < meshesFromObj.length; j++) {
  95726. //check meshesNames (stlFileLoader)
  95727. if (meshesNames && meshesFromObj[j].name) {
  95728. if (meshesNames instanceof Array) {
  95729. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  95730. continue;
  95731. }
  95732. }
  95733. else {
  95734. if (meshesFromObj[j].name !== meshesNames) {
  95735. continue;
  95736. }
  95737. }
  95738. }
  95739. //Get the current mesh
  95740. //Set the data with VertexBuffer for each mesh
  95741. handledMesh = meshesFromObj[j];
  95742. //Create a BABYLON.Mesh with the name of the obj mesh
  95743. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  95744. //Push the name of the material to an array
  95745. //This is indispensable for the importMesh function
  95746. materialToUse.push(meshesFromObj[j].materialName);
  95747. var vertexData = new BABYLON.VertexData(); //The container for the values
  95748. //Set the data for the babylonMesh
  95749. vertexData.positions = handledMesh.positions;
  95750. vertexData.normals = handledMesh.normals;
  95751. vertexData.uvs = handledMesh.uvs;
  95752. vertexData.indices = handledMesh.indices;
  95753. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  95754. vertexData.applyToMesh(babylonMesh);
  95755. //Push the mesh into an array
  95756. babylonMeshesArray.push(babylonMesh);
  95757. }
  95758. //load the materials
  95759. //Check if we have a file to load
  95760. if (fileToLoad !== "") {
  95761. //Load the file synchronously
  95762. this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  95763. //Create materials thanks MTLLoader function
  95764. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  95765. //Look at each material loaded in the mtl file
  95766. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  95767. //Three variables to get all meshes with the same material
  95768. var startIndex = 0;
  95769. var _indices = [];
  95770. var _index;
  95771. //The material from MTL file is used in the meshes loaded
  95772. //Push the indice in an array
  95773. //Check if the material is not used for another mesh
  95774. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  95775. _indices.push(_index);
  95776. startIndex = _index + 1;
  95777. }
  95778. //If the material is not used dispose it
  95779. if (_index == -1 && _indices.length == 0) {
  95780. //If the material is not needed, remove it
  95781. materialsFromMTLFile.materials[n].dispose();
  95782. }
  95783. else {
  95784. for (var o = 0; o < _indices.length; o++) {
  95785. //Apply the material to the BABYLON.Mesh for each mesh with the material
  95786. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  95787. }
  95788. }
  95789. }
  95790. });
  95791. }
  95792. //Return an array with all BABYLON.Mesh
  95793. return babylonMeshesArray;
  95794. };
  95795. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  95796. return OBJFileLoader;
  95797. }());
  95798. BABYLON.OBJFileLoader = OBJFileLoader;
  95799. if (BABYLON.SceneLoader) {
  95800. //Add this loader into the register plugin
  95801. BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
  95802. }
  95803. })(BABYLON || (BABYLON = {}));
  95804. //# sourceMappingURL=babylon.objFileLoader.js.map
  95805. "use strict";
  95806. var BABYLON;
  95807. (function (BABYLON) {
  95808. var GLTFLoaderCoordinateSystemMode;
  95809. (function (GLTFLoaderCoordinateSystemMode) {
  95810. /**
  95811. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  95812. */
  95813. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  95814. /**
  95815. * Sets the useRightHandedSystem flag on the scene.
  95816. */
  95817. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  95818. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  95819. var GLTFLoaderAnimationStartMode;
  95820. (function (GLTFLoaderAnimationStartMode) {
  95821. /**
  95822. * No animation will start.
  95823. */
  95824. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  95825. /**
  95826. * The first animation will start.
  95827. */
  95828. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  95829. /**
  95830. * All animations will start.
  95831. */
  95832. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  95833. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  95834. var GLTFLoaderState;
  95835. (function (GLTFLoaderState) {
  95836. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  95837. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  95838. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  95839. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  95840. var GLTFFileLoader = /** @class */ (function () {
  95841. function GLTFFileLoader() {
  95842. // #region Common options
  95843. /**
  95844. * Raised when the asset has been parsed.
  95845. * The data.json property stores the glTF JSON.
  95846. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  95847. */
  95848. this.onParsedObservable = new BABYLON.Observable();
  95849. // #endregion
  95850. // #region V2 options
  95851. /**
  95852. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  95853. */
  95854. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  95855. /**
  95856. * The animation start mode (NONE, FIRST, ALL).
  95857. */
  95858. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  95859. /**
  95860. * Set to true to compile materials before raising the success callback.
  95861. */
  95862. this.compileMaterials = false;
  95863. /**
  95864. * Set to true to also compile materials with clip planes.
  95865. */
  95866. this.useClipPlane = false;
  95867. /**
  95868. * Set to true to compile shadow generators before raising the success callback.
  95869. */
  95870. this.compileShadowGenerators = false;
  95871. /**
  95872. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  95873. */
  95874. this.onMeshLoadedObservable = new BABYLON.Observable();
  95875. /**
  95876. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  95877. */
  95878. this.onTextureLoadedObservable = new BABYLON.Observable();
  95879. /**
  95880. * Raised when the loader creates a material after parsing the glTF properties of the material.
  95881. */
  95882. this.onMaterialLoadedObservable = new BABYLON.Observable();
  95883. /**
  95884. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  95885. * For assets with LODs, raised when all of the LODs are complete.
  95886. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  95887. */
  95888. this.onCompleteObservable = new BABYLON.Observable();
  95889. /**
  95890. * Raised when the loader is disposed.
  95891. */
  95892. this.onDisposeObservable = new BABYLON.Observable();
  95893. /**
  95894. * Raised after a loader extension is created.
  95895. * Set additional options for a loader extension in this event.
  95896. */
  95897. this.onExtensionLoadedObservable = new BABYLON.Observable();
  95898. // #endregion
  95899. this._loader = null;
  95900. this.name = "gltf";
  95901. this.extensions = {
  95902. ".gltf": { isBinary: false },
  95903. ".glb": { isBinary: true }
  95904. };
  95905. }
  95906. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  95907. set: function (callback) {
  95908. if (this._onParsedObserver) {
  95909. this.onParsedObservable.remove(this._onParsedObserver);
  95910. }
  95911. this._onParsedObserver = this.onParsedObservable.add(callback);
  95912. },
  95913. enumerable: true,
  95914. configurable: true
  95915. });
  95916. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  95917. set: function (callback) {
  95918. if (this._onMeshLoadedObserver) {
  95919. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  95920. }
  95921. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  95922. },
  95923. enumerable: true,
  95924. configurable: true
  95925. });
  95926. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  95927. set: function (callback) {
  95928. if (this._onTextureLoadedObserver) {
  95929. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  95930. }
  95931. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  95932. },
  95933. enumerable: true,
  95934. configurable: true
  95935. });
  95936. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  95937. set: function (callback) {
  95938. if (this._onMaterialLoadedObserver) {
  95939. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  95940. }
  95941. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  95942. },
  95943. enumerable: true,
  95944. configurable: true
  95945. });
  95946. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  95947. set: function (callback) {
  95948. if (this._onCompleteObserver) {
  95949. this.onCompleteObservable.remove(this._onCompleteObserver);
  95950. }
  95951. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  95952. },
  95953. enumerable: true,
  95954. configurable: true
  95955. });
  95956. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  95957. set: function (callback) {
  95958. if (this._onDisposeObserver) {
  95959. this.onDisposeObservable.remove(this._onDisposeObserver);
  95960. }
  95961. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  95962. },
  95963. enumerable: true,
  95964. configurable: true
  95965. });
  95966. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  95967. set: function (callback) {
  95968. if (this._onExtensionLoadedObserver) {
  95969. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  95970. }
  95971. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  95972. },
  95973. enumerable: true,
  95974. configurable: true
  95975. });
  95976. /**
  95977. * Gets a promise that resolves when the asset is completely loaded.
  95978. * @returns A promise that resolves when the asset is completely loaded.
  95979. */
  95980. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  95981. var _this = this;
  95982. return new Promise(function (resolve) {
  95983. _this.onCompleteObservable.add(function () {
  95984. resolve();
  95985. }, undefined, undefined, undefined, true);
  95986. });
  95987. };
  95988. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  95989. /**
  95990. * The loader state or null if not active.
  95991. */
  95992. get: function () {
  95993. return this._loader ? this._loader.state : null;
  95994. },
  95995. enumerable: true,
  95996. configurable: true
  95997. });
  95998. /**
  95999. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  96000. */
  96001. GLTFFileLoader.prototype.dispose = function () {
  96002. if (this._loader) {
  96003. this._loader.dispose();
  96004. this._loader = null;
  96005. }
  96006. this.onMeshLoadedObservable.clear();
  96007. this.onTextureLoadedObservable.clear();
  96008. this.onMaterialLoadedObservable.clear();
  96009. this.onDisposeObservable.notifyObservers(this);
  96010. this.onDisposeObservable.clear();
  96011. };
  96012. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  96013. var _this = this;
  96014. return Promise.resolve().then(function () {
  96015. var loaderData = _this._parse(data);
  96016. _this._loader = _this._getLoader(loaderData);
  96017. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  96018. });
  96019. };
  96020. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  96021. var _this = this;
  96022. return Promise.resolve().then(function () {
  96023. var loaderData = _this._parse(data);
  96024. _this._loader = _this._getLoader(loaderData);
  96025. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  96026. });
  96027. };
  96028. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  96029. var _this = this;
  96030. return Promise.resolve().then(function () {
  96031. var loaderData = _this._parse(data);
  96032. _this._loader = _this._getLoader(loaderData);
  96033. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  96034. var container = new BABYLON.AssetContainer(scene);
  96035. Array.prototype.push.apply(container.meshes, result.meshes);
  96036. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  96037. Array.prototype.push.apply(container.skeletons, result.skeletons);
  96038. Array.prototype.push.apply(container.animationGroups, result.animationGroups);
  96039. container.removeAllFromScene();
  96040. return container;
  96041. });
  96042. });
  96043. };
  96044. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  96045. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  96046. };
  96047. GLTFFileLoader.prototype.createPlugin = function () {
  96048. return new GLTFFileLoader();
  96049. };
  96050. GLTFFileLoader.prototype._parse = function (data) {
  96051. var parsedData;
  96052. if (data instanceof ArrayBuffer) {
  96053. parsedData = GLTFFileLoader._parseBinary(data);
  96054. }
  96055. else {
  96056. parsedData = {
  96057. json: JSON.parse(data),
  96058. bin: null
  96059. };
  96060. }
  96061. this.onParsedObservable.notifyObservers(parsedData);
  96062. this.onParsedObservable.clear();
  96063. return parsedData;
  96064. };
  96065. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  96066. var _this = this;
  96067. var loaderVersion = { major: 2, minor: 0 };
  96068. var asset = loaderData.json.asset || {};
  96069. var version = GLTFFileLoader._parseVersion(asset.version);
  96070. if (!version) {
  96071. throw new Error("Invalid version: " + asset.version);
  96072. }
  96073. if (asset.minVersion !== undefined) {
  96074. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  96075. if (!minVersion) {
  96076. throw new Error("Invalid minimum version: " + asset.minVersion);
  96077. }
  96078. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  96079. throw new Error("Incompatible minimum version: " + asset.minVersion);
  96080. }
  96081. }
  96082. var createLoaders = {
  96083. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  96084. 2: GLTFFileLoader.CreateGLTFLoaderV2
  96085. };
  96086. var createLoader = createLoaders[version.major];
  96087. if (!createLoader) {
  96088. throw new Error("Unsupported version: " + asset.version);
  96089. }
  96090. var loader = createLoader();
  96091. loader.coordinateSystemMode = this.coordinateSystemMode;
  96092. loader.animationStartMode = this.animationStartMode;
  96093. loader.compileMaterials = this.compileMaterials;
  96094. loader.useClipPlane = this.useClipPlane;
  96095. loader.compileShadowGenerators = this.compileShadowGenerators;
  96096. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  96097. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  96098. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  96099. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  96100. loader.onCompleteObservable.add(function () {
  96101. _this.onMeshLoadedObservable.clear();
  96102. _this.onTextureLoadedObservable.clear();
  96103. _this.onMaterialLoadedObservable.clear();
  96104. _this.onCompleteObservable.notifyObservers(_this);
  96105. _this.onCompleteObservable.clear();
  96106. });
  96107. return loader;
  96108. };
  96109. GLTFFileLoader._parseBinary = function (data) {
  96110. var Binary = {
  96111. Magic: 0x46546C67
  96112. };
  96113. var binaryReader = new BinaryReader(data);
  96114. var magic = binaryReader.readUint32();
  96115. if (magic !== Binary.Magic) {
  96116. throw new Error("Unexpected magic: " + magic);
  96117. }
  96118. var version = binaryReader.readUint32();
  96119. switch (version) {
  96120. case 1: return GLTFFileLoader._parseV1(binaryReader);
  96121. case 2: return GLTFFileLoader._parseV2(binaryReader);
  96122. }
  96123. throw new Error("Unsupported version: " + version);
  96124. };
  96125. GLTFFileLoader._parseV1 = function (binaryReader) {
  96126. var ContentFormat = {
  96127. JSON: 0
  96128. };
  96129. var length = binaryReader.readUint32();
  96130. if (length != binaryReader.getLength()) {
  96131. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  96132. }
  96133. var contentLength = binaryReader.readUint32();
  96134. var contentFormat = binaryReader.readUint32();
  96135. var content;
  96136. switch (contentFormat) {
  96137. case ContentFormat.JSON: {
  96138. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  96139. break;
  96140. }
  96141. default: {
  96142. throw new Error("Unexpected content format: " + contentFormat);
  96143. }
  96144. }
  96145. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  96146. var body = binaryReader.readUint8Array(bytesRemaining);
  96147. return {
  96148. json: content,
  96149. bin: body
  96150. };
  96151. };
  96152. GLTFFileLoader._parseV2 = function (binaryReader) {
  96153. var ChunkFormat = {
  96154. JSON: 0x4E4F534A,
  96155. BIN: 0x004E4942
  96156. };
  96157. var length = binaryReader.readUint32();
  96158. if (length !== binaryReader.getLength()) {
  96159. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  96160. }
  96161. // JSON chunk
  96162. var chunkLength = binaryReader.readUint32();
  96163. var chunkFormat = binaryReader.readUint32();
  96164. if (chunkFormat !== ChunkFormat.JSON) {
  96165. throw new Error("First chunk format is not JSON");
  96166. }
  96167. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  96168. // Look for BIN chunk
  96169. var bin = null;
  96170. while (binaryReader.getPosition() < binaryReader.getLength()) {
  96171. var chunkLength_1 = binaryReader.readUint32();
  96172. var chunkFormat_1 = binaryReader.readUint32();
  96173. switch (chunkFormat_1) {
  96174. case ChunkFormat.JSON: {
  96175. throw new Error("Unexpected JSON chunk");
  96176. }
  96177. case ChunkFormat.BIN: {
  96178. bin = binaryReader.readUint8Array(chunkLength_1);
  96179. break;
  96180. }
  96181. default: {
  96182. // ignore unrecognized chunkFormat
  96183. binaryReader.skipBytes(chunkLength_1);
  96184. break;
  96185. }
  96186. }
  96187. }
  96188. return {
  96189. json: json,
  96190. bin: bin
  96191. };
  96192. };
  96193. GLTFFileLoader._parseVersion = function (version) {
  96194. if (version === "1.0" || version === "1.0.1") {
  96195. return {
  96196. major: 1,
  96197. minor: 0
  96198. };
  96199. }
  96200. var match = (version + "").match(/^(\d+)\.(\d+)/);
  96201. if (!match) {
  96202. return null;
  96203. }
  96204. return {
  96205. major: parseInt(match[1]),
  96206. minor: parseInt(match[2])
  96207. };
  96208. };
  96209. GLTFFileLoader._compareVersion = function (a, b) {
  96210. if (a.major > b.major)
  96211. return 1;
  96212. if (a.major < b.major)
  96213. return -1;
  96214. if (a.minor > b.minor)
  96215. return 1;
  96216. if (a.minor < b.minor)
  96217. return -1;
  96218. return 0;
  96219. };
  96220. GLTFFileLoader._decodeBufferToText = function (buffer) {
  96221. var result = "";
  96222. var length = buffer.byteLength;
  96223. for (var i = 0; i < length; i++) {
  96224. result += String.fromCharCode(buffer[i]);
  96225. }
  96226. return result;
  96227. };
  96228. // #endregion
  96229. // #region V1 options
  96230. GLTFFileLoader.IncrementalLoading = true;
  96231. GLTFFileLoader.HomogeneousCoordinates = false;
  96232. return GLTFFileLoader;
  96233. }());
  96234. BABYLON.GLTFFileLoader = GLTFFileLoader;
  96235. var BinaryReader = /** @class */ (function () {
  96236. function BinaryReader(arrayBuffer) {
  96237. this._arrayBuffer = arrayBuffer;
  96238. this._dataView = new DataView(arrayBuffer);
  96239. this._byteOffset = 0;
  96240. }
  96241. BinaryReader.prototype.getPosition = function () {
  96242. return this._byteOffset;
  96243. };
  96244. BinaryReader.prototype.getLength = function () {
  96245. return this._arrayBuffer.byteLength;
  96246. };
  96247. BinaryReader.prototype.readUint32 = function () {
  96248. var value = this._dataView.getUint32(this._byteOffset, true);
  96249. this._byteOffset += 4;
  96250. return value;
  96251. };
  96252. BinaryReader.prototype.readUint8Array = function (length) {
  96253. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  96254. this._byteOffset += length;
  96255. return value;
  96256. };
  96257. BinaryReader.prototype.skipBytes = function (length) {
  96258. this._byteOffset += length;
  96259. };
  96260. return BinaryReader;
  96261. }());
  96262. if (BABYLON.SceneLoader) {
  96263. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  96264. }
  96265. })(BABYLON || (BABYLON = {}));
  96266. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  96267. "use strict";
  96268. var BABYLON;
  96269. (function (BABYLON) {
  96270. var GLTF1;
  96271. (function (GLTF1) {
  96272. /**
  96273. * Enums
  96274. */
  96275. var EComponentType;
  96276. (function (EComponentType) {
  96277. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  96278. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  96279. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  96280. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  96281. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  96282. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  96283. var EShaderType;
  96284. (function (EShaderType) {
  96285. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  96286. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  96287. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  96288. var EParameterType;
  96289. (function (EParameterType) {
  96290. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  96291. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  96292. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  96293. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  96294. EParameterType[EParameterType["INT"] = 5124] = "INT";
  96295. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  96296. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  96297. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  96298. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  96299. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  96300. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  96301. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  96302. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  96303. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  96304. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  96305. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  96306. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  96307. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  96308. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  96309. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  96310. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  96311. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  96312. var ETextureWrapMode;
  96313. (function (ETextureWrapMode) {
  96314. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  96315. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  96316. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  96317. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  96318. var ETextureFilterType;
  96319. (function (ETextureFilterType) {
  96320. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  96321. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  96322. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  96323. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  96324. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  96325. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  96326. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  96327. var ETextureFormat;
  96328. (function (ETextureFormat) {
  96329. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  96330. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  96331. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  96332. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  96333. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  96334. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  96335. var ECullingType;
  96336. (function (ECullingType) {
  96337. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  96338. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  96339. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  96340. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  96341. var EBlendingFunction;
  96342. (function (EBlendingFunction) {
  96343. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  96344. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  96345. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  96346. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  96347. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  96348. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  96349. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  96350. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  96351. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  96352. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  96353. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  96354. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  96355. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  96356. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  96357. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  96358. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  96359. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  96360. })(BABYLON || (BABYLON = {}));
  96361. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  96362. "use strict";
  96363. var BABYLON;
  96364. (function (BABYLON) {
  96365. var GLTF1;
  96366. (function (GLTF1) {
  96367. /**
  96368. * Tokenizer. Used for shaders compatibility
  96369. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  96370. */
  96371. var ETokenType;
  96372. (function (ETokenType) {
  96373. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  96374. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  96375. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  96376. })(ETokenType || (ETokenType = {}));
  96377. var Tokenizer = /** @class */ (function () {
  96378. function Tokenizer(toParse) {
  96379. this._pos = 0;
  96380. this.currentToken = ETokenType.UNKNOWN;
  96381. this.currentIdentifier = "";
  96382. this.currentString = "";
  96383. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  96384. this._toParse = toParse;
  96385. this._maxPos = toParse.length;
  96386. }
  96387. Tokenizer.prototype.getNextToken = function () {
  96388. if (this.isEnd())
  96389. return ETokenType.END_OF_INPUT;
  96390. this.currentString = this.read();
  96391. this.currentToken = ETokenType.UNKNOWN;
  96392. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  96393. this.currentToken = ETokenType.IDENTIFIER;
  96394. this.currentIdentifier = this.currentString;
  96395. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  96396. this.currentIdentifier += this.currentString;
  96397. this.forward();
  96398. }
  96399. }
  96400. return this.currentToken;
  96401. };
  96402. Tokenizer.prototype.peek = function () {
  96403. return this._toParse[this._pos];
  96404. };
  96405. Tokenizer.prototype.read = function () {
  96406. return this._toParse[this._pos++];
  96407. };
  96408. Tokenizer.prototype.forward = function () {
  96409. this._pos++;
  96410. };
  96411. Tokenizer.prototype.isEnd = function () {
  96412. return this._pos >= this._maxPos;
  96413. };
  96414. return Tokenizer;
  96415. }());
  96416. /**
  96417. * Values
  96418. */
  96419. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  96420. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  96421. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  96422. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  96423. /**
  96424. * Parse
  96425. */
  96426. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  96427. for (var buf in parsedBuffers) {
  96428. var parsedBuffer = parsedBuffers[buf];
  96429. gltfRuntime.buffers[buf] = parsedBuffer;
  96430. gltfRuntime.buffersCount++;
  96431. }
  96432. };
  96433. var parseShaders = function (parsedShaders, gltfRuntime) {
  96434. for (var sha in parsedShaders) {
  96435. var parsedShader = parsedShaders[sha];
  96436. gltfRuntime.shaders[sha] = parsedShader;
  96437. gltfRuntime.shaderscount++;
  96438. }
  96439. };
  96440. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  96441. for (var object in parsedObjects) {
  96442. var parsedObject = parsedObjects[object];
  96443. gltfRuntime[runtimeProperty][object] = parsedObject;
  96444. }
  96445. };
  96446. /**
  96447. * Utils
  96448. */
  96449. var normalizeUVs = function (buffer) {
  96450. if (!buffer) {
  96451. return;
  96452. }
  96453. for (var i = 0; i < buffer.length / 2; i++) {
  96454. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  96455. }
  96456. };
  96457. var getAttribute = function (attributeParameter) {
  96458. if (attributeParameter.semantic === "NORMAL") {
  96459. return "normal";
  96460. }
  96461. else if (attributeParameter.semantic === "POSITION") {
  96462. return "position";
  96463. }
  96464. else if (attributeParameter.semantic === "JOINT") {
  96465. return "matricesIndices";
  96466. }
  96467. else if (attributeParameter.semantic === "WEIGHT") {
  96468. return "matricesWeights";
  96469. }
  96470. else if (attributeParameter.semantic === "COLOR") {
  96471. return "color";
  96472. }
  96473. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  96474. var channel = Number(attributeParameter.semantic.split("_")[1]);
  96475. return "uv" + (channel === 0 ? "" : channel + 1);
  96476. }
  96477. return null;
  96478. };
  96479. /**
  96480. * Loads and creates animations
  96481. */
  96482. var loadAnimations = function (gltfRuntime) {
  96483. for (var anim in gltfRuntime.animations) {
  96484. var animation = gltfRuntime.animations[anim];
  96485. if (!animation.channels || !animation.samplers) {
  96486. continue;
  96487. }
  96488. var lastAnimation = null;
  96489. for (var i = 0; i < animation.channels.length; i++) {
  96490. // Get parameters and load buffers
  96491. var channel = animation.channels[i];
  96492. var sampler = animation.samplers[channel.sampler];
  96493. if (!sampler) {
  96494. continue;
  96495. }
  96496. var inputData = null;
  96497. var outputData = null;
  96498. if (animation.parameters) {
  96499. inputData = animation.parameters[sampler.input];
  96500. outputData = animation.parameters[sampler.output];
  96501. }
  96502. else {
  96503. inputData = sampler.input;
  96504. outputData = sampler.output;
  96505. }
  96506. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  96507. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  96508. var targetID = channel.target.id;
  96509. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  96510. if (targetNode === null) {
  96511. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  96512. }
  96513. if (targetNode === null) {
  96514. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  96515. continue;
  96516. }
  96517. var isBone = targetNode instanceof BABYLON.Bone;
  96518. // Get target path (position, rotation or scaling)
  96519. var targetPath = channel.target.path;
  96520. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  96521. if (targetPathIndex !== -1) {
  96522. targetPath = babylonAnimationPaths[targetPathIndex];
  96523. }
  96524. // Determine animation type
  96525. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  96526. if (!isBone) {
  96527. if (targetPath === "rotationQuaternion") {
  96528. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  96529. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  96530. }
  96531. else {
  96532. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  96533. }
  96534. }
  96535. // Create animation and key frames
  96536. var babylonAnimation = null;
  96537. var keys = [];
  96538. var arrayOffset = 0;
  96539. var modifyKey = false;
  96540. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  96541. babylonAnimation = lastAnimation;
  96542. modifyKey = true;
  96543. }
  96544. if (!modifyKey) {
  96545. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  96546. }
  96547. // For each frame
  96548. for (var j = 0; j < bufferInput.length; j++) {
  96549. var value = null;
  96550. if (targetPath === "rotationQuaternion") {
  96551. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  96552. arrayOffset += 4;
  96553. }
  96554. else {
  96555. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  96556. arrayOffset += 3;
  96557. }
  96558. if (isBone) {
  96559. var bone = targetNode;
  96560. var translation = BABYLON.Vector3.Zero();
  96561. var rotationQuaternion = new BABYLON.Quaternion();
  96562. var scaling = BABYLON.Vector3.Zero();
  96563. // Warning on decompose
  96564. var mat = bone.getBaseMatrix();
  96565. if (modifyKey && lastAnimation) {
  96566. mat = lastAnimation.getKeys()[j].value;
  96567. }
  96568. mat.decompose(scaling, rotationQuaternion, translation);
  96569. if (targetPath === "position") {
  96570. translation = value;
  96571. }
  96572. else if (targetPath === "rotationQuaternion") {
  96573. rotationQuaternion = value;
  96574. }
  96575. else {
  96576. scaling = value;
  96577. }
  96578. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  96579. }
  96580. if (!modifyKey) {
  96581. keys.push({
  96582. frame: bufferInput[j],
  96583. value: value
  96584. });
  96585. }
  96586. else if (lastAnimation) {
  96587. lastAnimation.getKeys()[j].value = value;
  96588. }
  96589. }
  96590. // Finish
  96591. if (!modifyKey && babylonAnimation) {
  96592. babylonAnimation.setKeys(keys);
  96593. targetNode.animations.push(babylonAnimation);
  96594. }
  96595. lastAnimation = babylonAnimation;
  96596. gltfRuntime.scene.stopAnimation(targetNode);
  96597. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  96598. }
  96599. }
  96600. };
  96601. /**
  96602. * Returns the bones transformation matrix
  96603. */
  96604. var configureBoneTransformation = function (node) {
  96605. var mat = null;
  96606. if (node.translation || node.rotation || node.scale) {
  96607. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  96608. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  96609. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  96610. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  96611. }
  96612. else {
  96613. mat = BABYLON.Matrix.FromArray(node.matrix);
  96614. }
  96615. return mat;
  96616. };
  96617. /**
  96618. * Returns the parent bone
  96619. */
  96620. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  96621. // Try to find
  96622. for (var i = 0; i < newSkeleton.bones.length; i++) {
  96623. if (newSkeleton.bones[i].name === jointName) {
  96624. return newSkeleton.bones[i];
  96625. }
  96626. }
  96627. // Not found, search in gltf nodes
  96628. var nodes = gltfRuntime.nodes;
  96629. for (var nde in nodes) {
  96630. var node = nodes[nde];
  96631. if (!node.jointName) {
  96632. continue;
  96633. }
  96634. var children = node.children;
  96635. for (var i = 0; i < children.length; i++) {
  96636. var child = gltfRuntime.nodes[children[i]];
  96637. if (!child.jointName) {
  96638. continue;
  96639. }
  96640. if (child.jointName === jointName) {
  96641. var mat = configureBoneTransformation(node);
  96642. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  96643. bone.id = nde;
  96644. return bone;
  96645. }
  96646. }
  96647. }
  96648. return null;
  96649. };
  96650. /**
  96651. * Returns the appropriate root node
  96652. */
  96653. var getNodeToRoot = function (nodesToRoot, id) {
  96654. for (var i = 0; i < nodesToRoot.length; i++) {
  96655. var nodeToRoot = nodesToRoot[i];
  96656. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  96657. var child = nodeToRoot.node.children[j];
  96658. if (child === id) {
  96659. return nodeToRoot.bone;
  96660. }
  96661. }
  96662. }
  96663. return null;
  96664. };
  96665. /**
  96666. * Returns the node with the joint name
  96667. */
  96668. var getJointNode = function (gltfRuntime, jointName) {
  96669. var nodes = gltfRuntime.nodes;
  96670. var node = nodes[jointName];
  96671. if (node) {
  96672. return {
  96673. node: node,
  96674. id: jointName
  96675. };
  96676. }
  96677. for (var nde in nodes) {
  96678. node = nodes[nde];
  96679. if (node.jointName === jointName) {
  96680. return {
  96681. node: node,
  96682. id: nde
  96683. };
  96684. }
  96685. }
  96686. return null;
  96687. };
  96688. /**
  96689. * Checks if a nodes is in joints
  96690. */
  96691. var nodeIsInJoints = function (skins, id) {
  96692. for (var i = 0; i < skins.jointNames.length; i++) {
  96693. if (skins.jointNames[i] === id) {
  96694. return true;
  96695. }
  96696. }
  96697. return false;
  96698. };
  96699. /**
  96700. * Fills the nodes to root for bones and builds hierarchy
  96701. */
  96702. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  96703. // Creates nodes for root
  96704. for (var nde in gltfRuntime.nodes) {
  96705. var node = gltfRuntime.nodes[nde];
  96706. var id = nde;
  96707. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  96708. continue;
  96709. }
  96710. // Create node to root bone
  96711. var mat = configureBoneTransformation(node);
  96712. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  96713. bone.id = id;
  96714. nodesToRoot.push({ bone: bone, node: node, id: id });
  96715. }
  96716. // Parenting
  96717. for (var i = 0; i < nodesToRoot.length; i++) {
  96718. var nodeToRoot = nodesToRoot[i];
  96719. var children = nodeToRoot.node.children;
  96720. for (var j = 0; j < children.length; j++) {
  96721. var child = null;
  96722. for (var k = 0; k < nodesToRoot.length; k++) {
  96723. if (nodesToRoot[k].id === children[j]) {
  96724. child = nodesToRoot[k];
  96725. break;
  96726. }
  96727. }
  96728. if (child) {
  96729. child.bone._parent = nodeToRoot.bone;
  96730. nodeToRoot.bone.children.push(child.bone);
  96731. }
  96732. }
  96733. }
  96734. };
  96735. /**
  96736. * Imports a skeleton
  96737. */
  96738. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  96739. if (!newSkeleton) {
  96740. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  96741. }
  96742. if (!skins.babylonSkeleton) {
  96743. return newSkeleton;
  96744. }
  96745. // Find the root bones
  96746. var nodesToRoot = [];
  96747. var nodesToRootToAdd = [];
  96748. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  96749. newSkeleton.bones = [];
  96750. // Joints
  96751. for (var i = 0; i < skins.jointNames.length; i++) {
  96752. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  96753. if (!jointNode) {
  96754. continue;
  96755. }
  96756. var node = jointNode.node;
  96757. if (!node) {
  96758. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  96759. continue;
  96760. }
  96761. var id = jointNode.id;
  96762. // Optimize, if the bone already exists...
  96763. var existingBone = gltfRuntime.scene.getBoneByID(id);
  96764. if (existingBone) {
  96765. newSkeleton.bones.push(existingBone);
  96766. continue;
  96767. }
  96768. // Search for parent bone
  96769. var foundBone = false;
  96770. var parentBone = null;
  96771. for (var j = 0; j < i; j++) {
  96772. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  96773. if (!jointNode_1) {
  96774. continue;
  96775. }
  96776. var joint = jointNode_1.node;
  96777. if (!joint) {
  96778. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  96779. continue;
  96780. }
  96781. var children = joint.children;
  96782. if (!children) {
  96783. continue;
  96784. }
  96785. foundBone = false;
  96786. for (var k = 0; k < children.length; k++) {
  96787. if (children[k] === id) {
  96788. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  96789. foundBone = true;
  96790. break;
  96791. }
  96792. }
  96793. if (foundBone) {
  96794. break;
  96795. }
  96796. }
  96797. // Create bone
  96798. var mat = configureBoneTransformation(node);
  96799. if (!parentBone && nodesToRoot.length > 0) {
  96800. parentBone = getNodeToRoot(nodesToRoot, id);
  96801. if (parentBone) {
  96802. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  96803. nodesToRootToAdd.push(parentBone);
  96804. }
  96805. }
  96806. }
  96807. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  96808. bone.id = id;
  96809. }
  96810. // Polish
  96811. var bones = newSkeleton.bones;
  96812. newSkeleton.bones = [];
  96813. for (var i = 0; i < skins.jointNames.length; i++) {
  96814. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  96815. if (!jointNode) {
  96816. continue;
  96817. }
  96818. for (var j = 0; j < bones.length; j++) {
  96819. if (bones[j].id === jointNode.id) {
  96820. newSkeleton.bones.push(bones[j]);
  96821. break;
  96822. }
  96823. }
  96824. }
  96825. newSkeleton.prepare();
  96826. // Finish
  96827. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  96828. newSkeleton.bones.push(nodesToRootToAdd[i]);
  96829. }
  96830. return newSkeleton;
  96831. };
  96832. /**
  96833. * Imports a mesh and its geometries
  96834. */
  96835. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  96836. if (!newMesh) {
  96837. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  96838. newMesh.id = id;
  96839. }
  96840. if (!node.babylonNode) {
  96841. return newMesh;
  96842. }
  96843. var subMaterials = [];
  96844. var vertexData = null;
  96845. var verticesStarts = new Array();
  96846. var verticesCounts = new Array();
  96847. var indexStarts = new Array();
  96848. var indexCounts = new Array();
  96849. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  96850. var meshID = meshes[meshIndex];
  96851. var mesh = gltfRuntime.meshes[meshID];
  96852. if (!mesh) {
  96853. continue;
  96854. }
  96855. // Positions, normals and UVs
  96856. for (var i = 0; i < mesh.primitives.length; i++) {
  96857. // Temporary vertex data
  96858. var tempVertexData = new BABYLON.VertexData();
  96859. var primitive = mesh.primitives[i];
  96860. if (primitive.mode !== 4) {
  96861. // continue;
  96862. }
  96863. var attributes = primitive.attributes;
  96864. var accessor = null;
  96865. var buffer = null;
  96866. // Set positions, normal and uvs
  96867. for (var semantic in attributes) {
  96868. // Link accessor and buffer view
  96869. accessor = gltfRuntime.accessors[attributes[semantic]];
  96870. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  96871. if (semantic === "NORMAL") {
  96872. tempVertexData.normals = new Float32Array(buffer.length);
  96873. tempVertexData.normals.set(buffer);
  96874. }
  96875. else if (semantic === "POSITION") {
  96876. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  96877. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  96878. for (var j = 0; j < buffer.length; j += 4) {
  96879. tempVertexData.positions[j] = buffer[j];
  96880. tempVertexData.positions[j + 1] = buffer[j + 1];
  96881. tempVertexData.positions[j + 2] = buffer[j + 2];
  96882. }
  96883. }
  96884. else {
  96885. tempVertexData.positions = new Float32Array(buffer.length);
  96886. tempVertexData.positions.set(buffer);
  96887. }
  96888. verticesCounts.push(tempVertexData.positions.length);
  96889. }
  96890. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  96891. var channel = Number(semantic.split("_")[1]);
  96892. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  96893. var uvs = new Float32Array(buffer.length);
  96894. uvs.set(buffer);
  96895. normalizeUVs(uvs);
  96896. tempVertexData.set(uvs, uvKind);
  96897. }
  96898. else if (semantic === "JOINT") {
  96899. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  96900. tempVertexData.matricesIndices.set(buffer);
  96901. }
  96902. else if (semantic === "WEIGHT") {
  96903. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  96904. tempVertexData.matricesWeights.set(buffer);
  96905. }
  96906. else if (semantic === "COLOR") {
  96907. tempVertexData.colors = new Float32Array(buffer.length);
  96908. tempVertexData.colors.set(buffer);
  96909. }
  96910. }
  96911. // Indices
  96912. accessor = gltfRuntime.accessors[primitive.indices];
  96913. if (accessor) {
  96914. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  96915. tempVertexData.indices = new Int32Array(buffer.length);
  96916. tempVertexData.indices.set(buffer);
  96917. indexCounts.push(tempVertexData.indices.length);
  96918. }
  96919. else {
  96920. // Set indices on the fly
  96921. var indices = [];
  96922. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  96923. indices.push(j);
  96924. }
  96925. tempVertexData.indices = new Int32Array(indices);
  96926. indexCounts.push(tempVertexData.indices.length);
  96927. }
  96928. if (!vertexData) {
  96929. vertexData = tempVertexData;
  96930. }
  96931. else {
  96932. vertexData.merge(tempVertexData);
  96933. }
  96934. // Sub material
  96935. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  96936. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  96937. // Update vertices start and index start
  96938. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  96939. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  96940. }
  96941. }
  96942. var material;
  96943. if (subMaterials.length > 1) {
  96944. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  96945. material.subMaterials = subMaterials;
  96946. }
  96947. else {
  96948. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  96949. }
  96950. if (subMaterials.length === 1) {
  96951. material = subMaterials[0];
  96952. }
  96953. if (!newMesh.material) {
  96954. newMesh.material = material;
  96955. }
  96956. // Apply geometry
  96957. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  96958. newMesh.computeWorldMatrix(true);
  96959. // Apply submeshes
  96960. newMesh.subMeshes = [];
  96961. var index = 0;
  96962. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  96963. var meshID = meshes[meshIndex];
  96964. var mesh = gltfRuntime.meshes[meshID];
  96965. if (!mesh) {
  96966. continue;
  96967. }
  96968. for (var i = 0; i < mesh.primitives.length; i++) {
  96969. if (mesh.primitives[i].mode !== 4) {
  96970. //continue;
  96971. }
  96972. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  96973. index++;
  96974. }
  96975. }
  96976. // Finish
  96977. return newMesh;
  96978. };
  96979. /**
  96980. * Configure node transformation from position, rotation and scaling
  96981. */
  96982. var configureNode = function (newNode, position, rotation, scaling) {
  96983. if (newNode.position) {
  96984. newNode.position = position;
  96985. }
  96986. if (newNode.rotationQuaternion || newNode.rotation) {
  96987. newNode.rotationQuaternion = rotation;
  96988. }
  96989. if (newNode.scaling) {
  96990. newNode.scaling = scaling;
  96991. }
  96992. };
  96993. /**
  96994. * Configures node from transformation matrix
  96995. */
  96996. var configureNodeFromMatrix = function (newNode, node, parent) {
  96997. if (node.matrix) {
  96998. var position = new BABYLON.Vector3(0, 0, 0);
  96999. var rotation = new BABYLON.Quaternion();
  97000. var scaling = new BABYLON.Vector3(0, 0, 0);
  97001. var mat = BABYLON.Matrix.FromArray(node.matrix);
  97002. mat.decompose(scaling, rotation, position);
  97003. configureNode(newNode, position, rotation, scaling);
  97004. }
  97005. else if (node.translation && node.rotation && node.scale) {
  97006. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  97007. }
  97008. newNode.computeWorldMatrix(true);
  97009. };
  97010. /**
  97011. * Imports a node
  97012. */
  97013. var importNode = function (gltfRuntime, node, id, parent) {
  97014. var lastNode = null;
  97015. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  97016. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  97017. return null;
  97018. }
  97019. }
  97020. // Meshes
  97021. if (node.skin) {
  97022. if (node.meshes) {
  97023. var skin = gltfRuntime.skins[node.skin];
  97024. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  97025. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  97026. if (newMesh.skeleton === null) {
  97027. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  97028. if (!skin.babylonSkeleton) {
  97029. skin.babylonSkeleton = newMesh.skeleton;
  97030. }
  97031. }
  97032. lastNode = newMesh;
  97033. }
  97034. }
  97035. else if (node.meshes) {
  97036. /**
  97037. * Improve meshes property
  97038. */
  97039. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  97040. lastNode = newMesh;
  97041. }
  97042. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  97043. var light = gltfRuntime.lights[node.light];
  97044. if (light) {
  97045. if (light.type === "ambient") {
  97046. var ambienLight = light[light.type];
  97047. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  97048. hemiLight.name = node.name || "";
  97049. if (ambienLight.color) {
  97050. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  97051. }
  97052. lastNode = hemiLight;
  97053. }
  97054. else if (light.type === "directional") {
  97055. var directionalLight = light[light.type];
  97056. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  97057. dirLight.name = node.name || "";
  97058. if (directionalLight.color) {
  97059. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  97060. }
  97061. lastNode = dirLight;
  97062. }
  97063. else if (light.type === "point") {
  97064. var pointLight = light[light.type];
  97065. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  97066. ptLight.name = node.name || "";
  97067. if (pointLight.color) {
  97068. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  97069. }
  97070. lastNode = ptLight;
  97071. }
  97072. else if (light.type === "spot") {
  97073. var spotLight = light[light.type];
  97074. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  97075. spLight.name = node.name || "";
  97076. if (spotLight.color) {
  97077. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  97078. }
  97079. if (spotLight.fallOfAngle) {
  97080. spLight.angle = spotLight.fallOfAngle;
  97081. }
  97082. if (spotLight.fallOffExponent) {
  97083. spLight.exponent = spotLight.fallOffExponent;
  97084. }
  97085. lastNode = spLight;
  97086. }
  97087. }
  97088. }
  97089. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  97090. var camera = gltfRuntime.cameras[node.camera];
  97091. if (camera) {
  97092. if (camera.type === "orthographic") {
  97093. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  97094. orthoCamera.name = node.name || "";
  97095. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  97096. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  97097. lastNode = orthoCamera;
  97098. }
  97099. else if (camera.type === "perspective") {
  97100. var perspectiveCamera = camera[camera.type];
  97101. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  97102. persCamera.name = node.name || "";
  97103. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  97104. if (!perspectiveCamera.aspectRatio) {
  97105. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  97106. }
  97107. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  97108. persCamera.maxZ = perspectiveCamera.zfar;
  97109. persCamera.minZ = perspectiveCamera.znear;
  97110. }
  97111. lastNode = persCamera;
  97112. }
  97113. }
  97114. }
  97115. // Empty node
  97116. if (!node.jointName) {
  97117. if (node.babylonNode) {
  97118. return node.babylonNode;
  97119. }
  97120. else if (lastNode === null) {
  97121. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  97122. node.babylonNode = dummy;
  97123. lastNode = dummy;
  97124. }
  97125. }
  97126. if (lastNode !== null) {
  97127. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  97128. configureNodeFromMatrix(lastNode, node, parent);
  97129. }
  97130. else {
  97131. var translation = node.translation || [0, 0, 0];
  97132. var rotation = node.rotation || [0, 0, 0, 1];
  97133. var scale = node.scale || [1, 1, 1];
  97134. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  97135. }
  97136. lastNode.updateCache(true);
  97137. node.babylonNode = lastNode;
  97138. }
  97139. return lastNode;
  97140. };
  97141. /**
  97142. * Traverses nodes and creates them
  97143. */
  97144. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  97145. if (meshIncluded === void 0) { meshIncluded = false; }
  97146. var node = gltfRuntime.nodes[id];
  97147. var newNode = null;
  97148. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  97149. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  97150. meshIncluded = true;
  97151. }
  97152. else {
  97153. meshIncluded = false;
  97154. }
  97155. }
  97156. else {
  97157. meshIncluded = true;
  97158. }
  97159. if (!node.jointName && meshIncluded) {
  97160. newNode = importNode(gltfRuntime, node, id, parent);
  97161. if (newNode !== null) {
  97162. newNode.id = id;
  97163. newNode.parent = parent;
  97164. }
  97165. }
  97166. if (node.children) {
  97167. for (var i = 0; i < node.children.length; i++) {
  97168. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  97169. }
  97170. }
  97171. };
  97172. /**
  97173. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  97174. */
  97175. var postLoad = function (gltfRuntime) {
  97176. // Nodes
  97177. var currentScene = gltfRuntime.currentScene;
  97178. if (currentScene) {
  97179. for (var i = 0; i < currentScene.nodes.length; i++) {
  97180. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  97181. }
  97182. }
  97183. else {
  97184. for (var thing in gltfRuntime.scenes) {
  97185. currentScene = gltfRuntime.scenes[thing];
  97186. for (var i = 0; i < currentScene.nodes.length; i++) {
  97187. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  97188. }
  97189. }
  97190. }
  97191. // Set animations
  97192. loadAnimations(gltfRuntime);
  97193. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  97194. var skeleton = gltfRuntime.scene.skeletons[i];
  97195. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  97196. }
  97197. };
  97198. /**
  97199. * onBind shaderrs callback to set uniforms and matrices
  97200. */
  97201. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  97202. var materialValues = material.values || technique.parameters;
  97203. for (var unif in unTreatedUniforms) {
  97204. var uniform = unTreatedUniforms[unif];
  97205. var type = uniform.type;
  97206. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  97207. if (uniform.semantic && !uniform.source && !uniform.node) {
  97208. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  97209. }
  97210. else if (uniform.semantic && (uniform.source || uniform.node)) {
  97211. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  97212. if (source === null) {
  97213. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  97214. }
  97215. if (source === null) {
  97216. continue;
  97217. }
  97218. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  97219. }
  97220. }
  97221. else {
  97222. var value = materialValues[technique.uniforms[unif]];
  97223. if (!value) {
  97224. continue;
  97225. }
  97226. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  97227. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  97228. if (texture === null || texture === undefined) {
  97229. continue;
  97230. }
  97231. shaderMaterial.getEffect().setTexture(unif, texture);
  97232. }
  97233. else {
  97234. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  97235. }
  97236. }
  97237. }
  97238. onSuccess(shaderMaterial);
  97239. };
  97240. /**
  97241. * Prepare uniforms to send the only one time
  97242. * Loads the appropriate textures
  97243. */
  97244. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  97245. var materialValues = material.values || technique.parameters;
  97246. var techniqueUniforms = technique.uniforms;
  97247. /**
  97248. * Prepare values here (not matrices)
  97249. */
  97250. for (var unif in unTreatedUniforms) {
  97251. var uniform = unTreatedUniforms[unif];
  97252. var type = uniform.type;
  97253. var value = materialValues[techniqueUniforms[unif]];
  97254. if (value === undefined) {
  97255. // In case the value is the same for all materials
  97256. value = uniform.value;
  97257. }
  97258. if (!value) {
  97259. continue;
  97260. }
  97261. var onLoadTexture = function (uniformName) {
  97262. return function (texture) {
  97263. if (uniform.value && uniformName) {
  97264. // Static uniform
  97265. shaderMaterial.setTexture(uniformName, texture);
  97266. delete unTreatedUniforms[uniformName];
  97267. }
  97268. };
  97269. };
  97270. // Texture (sampler2D)
  97271. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  97272. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  97273. }
  97274. else {
  97275. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  97276. // Static uniform
  97277. delete unTreatedUniforms[unif];
  97278. }
  97279. }
  97280. }
  97281. };
  97282. /**
  97283. * Shader compilation failed
  97284. */
  97285. var onShaderCompileError = function (program, shaderMaterial, onError) {
  97286. return function (effect, error) {
  97287. shaderMaterial.dispose(true);
  97288. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  97289. };
  97290. };
  97291. /**
  97292. * Shader compilation success
  97293. */
  97294. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  97295. return function (_) {
  97296. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  97297. shaderMaterial.onBind = function (mesh) {
  97298. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  97299. };
  97300. };
  97301. };
  97302. /**
  97303. * Returns the appropriate uniform if already handled by babylon
  97304. */
  97305. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  97306. for (var unif in technique.uniforms) {
  97307. var uniform = technique.uniforms[unif];
  97308. var uniformParameter = technique.parameters[uniform];
  97309. if (tokenizer.currentIdentifier === unif) {
  97310. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  97311. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  97312. if (transformIndex !== -1) {
  97313. delete unTreatedUniforms[unif];
  97314. return babylonTransforms[transformIndex];
  97315. }
  97316. }
  97317. }
  97318. }
  97319. return tokenizer.currentIdentifier;
  97320. };
  97321. /**
  97322. * All shaders loaded. Create materials one by one
  97323. */
  97324. var importMaterials = function (gltfRuntime) {
  97325. // Create materials
  97326. for (var mat in gltfRuntime.materials) {
  97327. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  97328. }
  97329. };
  97330. /**
  97331. * Implementation of the base glTF spec
  97332. */
  97333. var GLTFLoaderBase = /** @class */ (function () {
  97334. function GLTFLoaderBase() {
  97335. }
  97336. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  97337. var gltfRuntime = {
  97338. extensions: {},
  97339. accessors: {},
  97340. buffers: {},
  97341. bufferViews: {},
  97342. meshes: {},
  97343. lights: {},
  97344. cameras: {},
  97345. nodes: {},
  97346. images: {},
  97347. textures: {},
  97348. shaders: {},
  97349. programs: {},
  97350. samplers: {},
  97351. techniques: {},
  97352. materials: {},
  97353. animations: {},
  97354. skins: {},
  97355. extensionsUsed: [],
  97356. scenes: {},
  97357. buffersCount: 0,
  97358. shaderscount: 0,
  97359. scene: scene,
  97360. rootUrl: rootUrl,
  97361. loadedBufferCount: 0,
  97362. loadedBufferViews: {},
  97363. loadedShaderCount: 0,
  97364. importOnlyMeshes: false,
  97365. dummyNodes: []
  97366. };
  97367. // Parse
  97368. if (parsedData.extensions) {
  97369. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  97370. }
  97371. if (parsedData.extensionsUsed) {
  97372. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  97373. }
  97374. if (parsedData.buffers) {
  97375. parseBuffers(parsedData.buffers, gltfRuntime);
  97376. }
  97377. if (parsedData.bufferViews) {
  97378. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  97379. }
  97380. if (parsedData.accessors) {
  97381. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  97382. }
  97383. if (parsedData.meshes) {
  97384. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  97385. }
  97386. if (parsedData.lights) {
  97387. parseObject(parsedData.lights, "lights", gltfRuntime);
  97388. }
  97389. if (parsedData.cameras) {
  97390. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  97391. }
  97392. if (parsedData.nodes) {
  97393. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  97394. }
  97395. if (parsedData.images) {
  97396. parseObject(parsedData.images, "images", gltfRuntime);
  97397. }
  97398. if (parsedData.textures) {
  97399. parseObject(parsedData.textures, "textures", gltfRuntime);
  97400. }
  97401. if (parsedData.shaders) {
  97402. parseShaders(parsedData.shaders, gltfRuntime);
  97403. }
  97404. if (parsedData.programs) {
  97405. parseObject(parsedData.programs, "programs", gltfRuntime);
  97406. }
  97407. if (parsedData.samplers) {
  97408. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  97409. }
  97410. if (parsedData.techniques) {
  97411. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  97412. }
  97413. if (parsedData.materials) {
  97414. parseObject(parsedData.materials, "materials", gltfRuntime);
  97415. }
  97416. if (parsedData.animations) {
  97417. parseObject(parsedData.animations, "animations", gltfRuntime);
  97418. }
  97419. if (parsedData.skins) {
  97420. parseObject(parsedData.skins, "skins", gltfRuntime);
  97421. }
  97422. if (parsedData.scenes) {
  97423. gltfRuntime.scenes = parsedData.scenes;
  97424. }
  97425. if (parsedData.scene && parsedData.scenes) {
  97426. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  97427. }
  97428. return gltfRuntime;
  97429. };
  97430. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  97431. var buffer = gltfRuntime.buffers[id];
  97432. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  97433. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  97434. }
  97435. else {
  97436. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  97437. if (request) {
  97438. onError(request.status + " " + request.statusText);
  97439. }
  97440. });
  97441. }
  97442. };
  97443. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  97444. var texture = gltfRuntime.textures[id];
  97445. if (!texture || !texture.source) {
  97446. onError("");
  97447. return;
  97448. }
  97449. if (texture.babylonTexture) {
  97450. onSuccess(null);
  97451. return;
  97452. }
  97453. var source = gltfRuntime.images[texture.source];
  97454. if (BABYLON.Tools.IsBase64(source.uri)) {
  97455. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  97456. }
  97457. else {
  97458. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  97459. if (request) {
  97460. onError(request.status + " " + request.statusText);
  97461. }
  97462. });
  97463. }
  97464. };
  97465. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  97466. var texture = gltfRuntime.textures[id];
  97467. if (texture.babylonTexture) {
  97468. onSuccess(texture.babylonTexture);
  97469. return;
  97470. }
  97471. var sampler = gltfRuntime.samplers[texture.sampler];
  97472. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  97473. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  97474. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  97475. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  97476. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  97477. var blob = new Blob([buffer]);
  97478. var blobURL = URL.createObjectURL(blob);
  97479. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  97480. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  97481. if (sampler.wrapS !== undefined) {
  97482. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  97483. }
  97484. if (sampler.wrapT !== undefined) {
  97485. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  97486. }
  97487. newTexture.name = id;
  97488. texture.babylonTexture = newTexture;
  97489. onSuccess(newTexture);
  97490. };
  97491. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  97492. var shader = gltfRuntime.shaders[id];
  97493. if (BABYLON.Tools.IsBase64(shader.uri)) {
  97494. var shaderString = atob(shader.uri.split(",")[1]);
  97495. if (onSuccess) {
  97496. onSuccess(shaderString);
  97497. }
  97498. }
  97499. else {
  97500. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  97501. if (request && onError) {
  97502. onError(request.status + " " + request.statusText);
  97503. }
  97504. });
  97505. }
  97506. };
  97507. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  97508. var material = gltfRuntime.materials[id];
  97509. if (!material.technique) {
  97510. if (onError) {
  97511. onError("No technique found.");
  97512. }
  97513. return;
  97514. }
  97515. var technique = gltfRuntime.techniques[material.technique];
  97516. if (!technique) {
  97517. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  97518. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  97519. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  97520. onSuccess(defaultMaterial);
  97521. return;
  97522. }
  97523. var program = gltfRuntime.programs[technique.program];
  97524. var states = technique.states;
  97525. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  97526. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  97527. var newVertexShader = "";
  97528. var newPixelShader = "";
  97529. var vertexTokenizer = new Tokenizer(vertexShader);
  97530. var pixelTokenizer = new Tokenizer(pixelShader);
  97531. var unTreatedUniforms = {};
  97532. var uniforms = [];
  97533. var attributes = [];
  97534. var samplers = [];
  97535. // Fill uniform, sampler2D and attributes
  97536. for (var unif in technique.uniforms) {
  97537. var uniform = technique.uniforms[unif];
  97538. var uniformParameter = technique.parameters[uniform];
  97539. unTreatedUniforms[unif] = uniformParameter;
  97540. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  97541. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  97542. if (transformIndex !== -1) {
  97543. uniforms.push(babylonTransforms[transformIndex]);
  97544. delete unTreatedUniforms[unif];
  97545. }
  97546. else {
  97547. uniforms.push(unif);
  97548. }
  97549. }
  97550. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  97551. samplers.push(unif);
  97552. }
  97553. else {
  97554. uniforms.push(unif);
  97555. }
  97556. }
  97557. for (var attr in technique.attributes) {
  97558. var attribute = technique.attributes[attr];
  97559. var attributeParameter = technique.parameters[attribute];
  97560. if (attributeParameter.semantic) {
  97561. attributes.push(getAttribute(attributeParameter));
  97562. }
  97563. }
  97564. // Configure vertex shader
  97565. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  97566. var tokenType = vertexTokenizer.currentToken;
  97567. if (tokenType !== ETokenType.IDENTIFIER) {
  97568. newVertexShader += vertexTokenizer.currentString;
  97569. continue;
  97570. }
  97571. var foundAttribute = false;
  97572. for (var attr in technique.attributes) {
  97573. var attribute = technique.attributes[attr];
  97574. var attributeParameter = technique.parameters[attribute];
  97575. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  97576. newVertexShader += getAttribute(attributeParameter);
  97577. foundAttribute = true;
  97578. break;
  97579. }
  97580. }
  97581. if (foundAttribute) {
  97582. continue;
  97583. }
  97584. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  97585. }
  97586. // Configure pixel shader
  97587. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  97588. var tokenType = pixelTokenizer.currentToken;
  97589. if (tokenType !== ETokenType.IDENTIFIER) {
  97590. newPixelShader += pixelTokenizer.currentString;
  97591. continue;
  97592. }
  97593. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  97594. }
  97595. // Create shader material
  97596. var shaderPath = {
  97597. vertex: program.vertexShader + id,
  97598. fragment: program.fragmentShader + id
  97599. };
  97600. var options = {
  97601. attributes: attributes,
  97602. uniforms: uniforms,
  97603. samplers: samplers,
  97604. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  97605. };
  97606. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  97607. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  97608. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  97609. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  97610. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  97611. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  97612. if (states && states.functions) {
  97613. var functions = states.functions;
  97614. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  97615. shaderMaterial.backFaceCulling = false;
  97616. }
  97617. var blendFunc = functions.blendFuncSeparate;
  97618. if (blendFunc) {
  97619. 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) {
  97620. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  97621. }
  97622. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  97623. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  97624. }
  97625. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  97626. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  97627. }
  97628. 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) {
  97629. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  97630. }
  97631. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  97632. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  97633. }
  97634. 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) {
  97635. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  97636. }
  97637. }
  97638. }
  97639. };
  97640. return GLTFLoaderBase;
  97641. }());
  97642. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  97643. /**
  97644. * glTF V1 Loader
  97645. */
  97646. var GLTFLoader = /** @class */ (function () {
  97647. function GLTFLoader() {
  97648. // #region Stubs for IGLTFLoader interface
  97649. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  97650. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  97651. this.compileMaterials = false;
  97652. this.useClipPlane = false;
  97653. this.compileShadowGenerators = false;
  97654. this.onDisposeObservable = new BABYLON.Observable();
  97655. this.onMeshLoadedObservable = new BABYLON.Observable();
  97656. this.onTextureLoadedObservable = new BABYLON.Observable();
  97657. this.onMaterialLoadedObservable = new BABYLON.Observable();
  97658. this.onCompleteObservable = new BABYLON.Observable();
  97659. this.onExtensionLoadedObservable = new BABYLON.Observable();
  97660. this.state = null;
  97661. }
  97662. GLTFLoader.RegisterExtension = function (extension) {
  97663. if (GLTFLoader.Extensions[extension.name]) {
  97664. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  97665. return;
  97666. }
  97667. GLTFLoader.Extensions[extension.name] = extension;
  97668. };
  97669. GLTFLoader.prototype.dispose = function () { };
  97670. // #endregion
  97671. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  97672. var _this = this;
  97673. scene.useRightHandedSystem = true;
  97674. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  97675. gltfRuntime.importOnlyMeshes = true;
  97676. if (meshesNames === "") {
  97677. gltfRuntime.importMeshesNames = [];
  97678. }
  97679. else if (typeof meshesNames === "string") {
  97680. gltfRuntime.importMeshesNames = [meshesNames];
  97681. }
  97682. else if (meshesNames && !(meshesNames instanceof Array)) {
  97683. gltfRuntime.importMeshesNames = [meshesNames];
  97684. }
  97685. else {
  97686. gltfRuntime.importMeshesNames = [];
  97687. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  97688. }
  97689. // Create nodes
  97690. _this._createNodes(gltfRuntime);
  97691. var meshes = new Array();
  97692. var skeletons = new Array();
  97693. // Fill arrays of meshes and skeletons
  97694. for (var nde in gltfRuntime.nodes) {
  97695. var node = gltfRuntime.nodes[nde];
  97696. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  97697. meshes.push(node.babylonNode);
  97698. }
  97699. }
  97700. for (var skl in gltfRuntime.skins) {
  97701. var skin = gltfRuntime.skins[skl];
  97702. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  97703. skeletons.push(skin.babylonSkeleton);
  97704. }
  97705. }
  97706. // Load buffers, shaders, materials, etc.
  97707. _this._loadBuffersAsync(gltfRuntime, function () {
  97708. _this._loadShadersAsync(gltfRuntime, function () {
  97709. importMaterials(gltfRuntime);
  97710. postLoad(gltfRuntime);
  97711. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  97712. onSuccess(meshes, skeletons);
  97713. }
  97714. });
  97715. }, onProgress);
  97716. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  97717. onSuccess(meshes, skeletons);
  97718. }
  97719. }, onError);
  97720. return true;
  97721. };
  97722. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  97723. var _this = this;
  97724. return new Promise(function (resolve, reject) {
  97725. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, skeletons) {
  97726. resolve({
  97727. meshes: meshes,
  97728. particleSystems: [],
  97729. skeletons: skeletons,
  97730. animationGroups: []
  97731. });
  97732. }, onProgress, function (message) {
  97733. reject(new Error(message));
  97734. });
  97735. });
  97736. };
  97737. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  97738. var _this = this;
  97739. scene.useRightHandedSystem = true;
  97740. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  97741. // Load runtime extensios
  97742. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  97743. // Create nodes
  97744. _this._createNodes(gltfRuntime);
  97745. // Load buffers, shaders, materials, etc.
  97746. _this._loadBuffersAsync(gltfRuntime, function () {
  97747. _this._loadShadersAsync(gltfRuntime, function () {
  97748. importMaterials(gltfRuntime);
  97749. postLoad(gltfRuntime);
  97750. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  97751. onSuccess();
  97752. }
  97753. });
  97754. });
  97755. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  97756. onSuccess();
  97757. }
  97758. }, onError);
  97759. }, onError);
  97760. };
  97761. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  97762. var _this = this;
  97763. return new Promise(function (resolve, reject) {
  97764. _this._loadAsync(scene, data, rootUrl, function () {
  97765. resolve();
  97766. }, onProgress, function (message) {
  97767. reject(new Error(message));
  97768. });
  97769. });
  97770. };
  97771. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  97772. var hasShaders = false;
  97773. var processShader = function (sha, shader) {
  97774. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  97775. if (shaderString instanceof ArrayBuffer) {
  97776. return;
  97777. }
  97778. gltfRuntime.loadedShaderCount++;
  97779. if (shaderString) {
  97780. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  97781. }
  97782. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  97783. onload();
  97784. }
  97785. }, function () {
  97786. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  97787. });
  97788. };
  97789. for (var sha in gltfRuntime.shaders) {
  97790. hasShaders = true;
  97791. var shader = gltfRuntime.shaders[sha];
  97792. if (shader) {
  97793. processShader.bind(this, sha, shader)();
  97794. }
  97795. else {
  97796. BABYLON.Tools.Error("No shader named: " + sha);
  97797. }
  97798. }
  97799. if (!hasShaders) {
  97800. onload();
  97801. }
  97802. };
  97803. ;
  97804. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  97805. var hasBuffers = false;
  97806. var processBuffer = function (buf, buffer) {
  97807. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  97808. gltfRuntime.loadedBufferCount++;
  97809. if (bufferView) {
  97810. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  97811. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  97812. }
  97813. gltfRuntime.loadedBufferViews[buf] = bufferView;
  97814. }
  97815. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  97816. onLoad();
  97817. }
  97818. }, function () {
  97819. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  97820. });
  97821. };
  97822. for (var buf in gltfRuntime.buffers) {
  97823. hasBuffers = true;
  97824. var buffer = gltfRuntime.buffers[buf];
  97825. if (buffer) {
  97826. processBuffer.bind(this, buf, buffer)();
  97827. }
  97828. else {
  97829. BABYLON.Tools.Error("No buffer named: " + buf);
  97830. }
  97831. }
  97832. if (!hasBuffers) {
  97833. onLoad();
  97834. }
  97835. };
  97836. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  97837. var currentScene = gltfRuntime.currentScene;
  97838. if (currentScene) {
  97839. // Only one scene even if multiple scenes are defined
  97840. for (var i = 0; i < currentScene.nodes.length; i++) {
  97841. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  97842. }
  97843. }
  97844. else {
  97845. // Load all scenes
  97846. for (var thing in gltfRuntime.scenes) {
  97847. currentScene = gltfRuntime.scenes[thing];
  97848. for (var i = 0; i < currentScene.nodes.length; i++) {
  97849. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  97850. }
  97851. }
  97852. }
  97853. };
  97854. GLTFLoader.Extensions = {};
  97855. return GLTFLoader;
  97856. }());
  97857. GLTF1.GLTFLoader = GLTFLoader;
  97858. ;
  97859. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  97860. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  97861. })(BABYLON || (BABYLON = {}));
  97862. //# sourceMappingURL=babylon.glTFLoader.js.map
  97863. "use strict";
  97864. var BABYLON;
  97865. (function (BABYLON) {
  97866. var GLTF1;
  97867. (function (GLTF1) {
  97868. /**
  97869. * Utils functions for GLTF
  97870. */
  97871. var GLTFUtils = /** @class */ (function () {
  97872. function GLTFUtils() {
  97873. }
  97874. /**
  97875. * Sets the given "parameter" matrix
  97876. * @param scene: the {BABYLON.Scene} object
  97877. * @param source: the source node where to pick the matrix
  97878. * @param parameter: the GLTF technique parameter
  97879. * @param uniformName: the name of the shader's uniform
  97880. * @param shaderMaterial: the shader material
  97881. */
  97882. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  97883. var mat = null;
  97884. if (parameter.semantic === "MODEL") {
  97885. mat = source.getWorldMatrix();
  97886. }
  97887. else if (parameter.semantic === "PROJECTION") {
  97888. mat = scene.getProjectionMatrix();
  97889. }
  97890. else if (parameter.semantic === "VIEW") {
  97891. mat = scene.getViewMatrix();
  97892. }
  97893. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  97894. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  97895. }
  97896. else if (parameter.semantic === "MODELVIEW") {
  97897. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  97898. }
  97899. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  97900. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  97901. }
  97902. else if (parameter.semantic === "MODELINVERSE") {
  97903. mat = source.getWorldMatrix().invert();
  97904. }
  97905. else if (parameter.semantic === "VIEWINVERSE") {
  97906. mat = scene.getViewMatrix().invert();
  97907. }
  97908. else if (parameter.semantic === "PROJECTIONINVERSE") {
  97909. mat = scene.getProjectionMatrix().invert();
  97910. }
  97911. else if (parameter.semantic === "MODELVIEWINVERSE") {
  97912. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  97913. }
  97914. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  97915. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  97916. }
  97917. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  97918. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  97919. }
  97920. else {
  97921. debugger;
  97922. }
  97923. if (mat) {
  97924. switch (parameter.type) {
  97925. case GLTF1.EParameterType.FLOAT_MAT2:
  97926. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  97927. break;
  97928. case GLTF1.EParameterType.FLOAT_MAT3:
  97929. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  97930. break;
  97931. case GLTF1.EParameterType.FLOAT_MAT4:
  97932. shaderMaterial.setMatrix(uniformName, mat);
  97933. break;
  97934. default: break;
  97935. }
  97936. }
  97937. };
  97938. /**
  97939. * Sets the given "parameter" matrix
  97940. * @param shaderMaterial: the shader material
  97941. * @param uniform: the name of the shader's uniform
  97942. * @param value: the value of the uniform
  97943. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  97944. */
  97945. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  97946. switch (type) {
  97947. case GLTF1.EParameterType.FLOAT:
  97948. shaderMaterial.setFloat(uniform, value);
  97949. return true;
  97950. case GLTF1.EParameterType.FLOAT_VEC2:
  97951. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  97952. return true;
  97953. case GLTF1.EParameterType.FLOAT_VEC3:
  97954. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  97955. return true;
  97956. case GLTF1.EParameterType.FLOAT_VEC4:
  97957. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  97958. return true;
  97959. default: return false;
  97960. }
  97961. };
  97962. /**
  97963. * Returns the wrap mode of the texture
  97964. * @param mode: the mode value
  97965. */
  97966. GLTFUtils.GetWrapMode = function (mode) {
  97967. switch (mode) {
  97968. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  97969. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  97970. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  97971. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  97972. }
  97973. };
  97974. /**
  97975. * Returns the byte stride giving an accessor
  97976. * @param accessor: the GLTF accessor objet
  97977. */
  97978. GLTFUtils.GetByteStrideFromType = function (accessor) {
  97979. // Needs this function since "byteStride" isn't requiered in glTF format
  97980. var type = accessor.type;
  97981. switch (type) {
  97982. case "VEC2": return 2;
  97983. case "VEC3": return 3;
  97984. case "VEC4": return 4;
  97985. case "MAT2": return 4;
  97986. case "MAT3": return 9;
  97987. case "MAT4": return 16;
  97988. default: return 1;
  97989. }
  97990. };
  97991. /**
  97992. * Returns the texture filter mode giving a mode value
  97993. * @param mode: the filter mode value
  97994. */
  97995. GLTFUtils.GetTextureFilterMode = function (mode) {
  97996. switch (mode) {
  97997. case GLTF1.ETextureFilterType.LINEAR:
  97998. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  97999. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  98000. case GLTF1.ETextureFilterType.NEAREST:
  98001. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  98002. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  98003. }
  98004. };
  98005. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  98006. var byteOffset = bufferView.byteOffset + byteOffset;
  98007. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  98008. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  98009. throw new Error("Buffer access is out of range");
  98010. }
  98011. var buffer = loadedBufferView.buffer;
  98012. byteOffset += loadedBufferView.byteOffset;
  98013. switch (componentType) {
  98014. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  98015. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  98016. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  98017. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  98018. default: return new Float32Array(buffer, byteOffset, byteLength);
  98019. }
  98020. };
  98021. /**
  98022. * Returns a buffer from its accessor
  98023. * @param gltfRuntime: the GLTF runtime
  98024. * @param accessor: the GLTF accessor
  98025. */
  98026. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  98027. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  98028. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  98029. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  98030. };
  98031. /**
  98032. * Decodes a buffer view into a string
  98033. * @param view: the buffer view
  98034. */
  98035. GLTFUtils.DecodeBufferToText = function (view) {
  98036. var result = "";
  98037. var length = view.byteLength;
  98038. for (var i = 0; i < length; ++i) {
  98039. result += String.fromCharCode(view[i]);
  98040. }
  98041. return result;
  98042. };
  98043. /**
  98044. * Returns the default material of gltf. Related to
  98045. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  98046. * @param scene: the Babylon.js scene
  98047. */
  98048. GLTFUtils.GetDefaultMaterial = function (scene) {
  98049. if (!GLTFUtils._DefaultMaterial) {
  98050. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  98051. "precision highp float;",
  98052. "",
  98053. "uniform mat4 worldView;",
  98054. "uniform mat4 projection;",
  98055. "",
  98056. "attribute vec3 position;",
  98057. "",
  98058. "void main(void)",
  98059. "{",
  98060. " gl_Position = projection * worldView * vec4(position, 1.0);",
  98061. "}"
  98062. ].join("\n");
  98063. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  98064. "precision highp float;",
  98065. "",
  98066. "uniform vec4 u_emission;",
  98067. "",
  98068. "void main(void)",
  98069. "{",
  98070. " gl_FragColor = u_emission;",
  98071. "}"
  98072. ].join("\n");
  98073. var shaderPath = {
  98074. vertex: "GLTFDefaultMaterial",
  98075. fragment: "GLTFDefaultMaterial"
  98076. };
  98077. var options = {
  98078. attributes: ["position"],
  98079. uniforms: ["worldView", "projection", "u_emission"],
  98080. samplers: new Array(),
  98081. needAlphaBlending: false
  98082. };
  98083. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  98084. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  98085. }
  98086. return GLTFUtils._DefaultMaterial;
  98087. };
  98088. // The GLTF default material
  98089. GLTFUtils._DefaultMaterial = null;
  98090. return GLTFUtils;
  98091. }());
  98092. GLTF1.GLTFUtils = GLTFUtils;
  98093. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  98094. })(BABYLON || (BABYLON = {}));
  98095. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  98096. "use strict";
  98097. var BABYLON;
  98098. (function (BABYLON) {
  98099. var GLTF1;
  98100. (function (GLTF1) {
  98101. var GLTFLoaderExtension = /** @class */ (function () {
  98102. function GLTFLoaderExtension(name) {
  98103. this._name = name;
  98104. }
  98105. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  98106. get: function () {
  98107. return this._name;
  98108. },
  98109. enumerable: true,
  98110. configurable: true
  98111. });
  98112. /**
  98113. * Defines an override for loading the runtime
  98114. * Return true to stop further extensions from loading the runtime
  98115. */
  98116. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  98117. return false;
  98118. };
  98119. /**
  98120. * Defines an onverride for creating gltf runtime
  98121. * Return true to stop further extensions from creating the runtime
  98122. */
  98123. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  98124. return false;
  98125. };
  98126. /**
  98127. * Defines an override for loading buffers
  98128. * Return true to stop further extensions from loading this buffer
  98129. */
  98130. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  98131. return false;
  98132. };
  98133. /**
  98134. * Defines an override for loading texture buffers
  98135. * Return true to stop further extensions from loading this texture data
  98136. */
  98137. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  98138. return false;
  98139. };
  98140. /**
  98141. * Defines an override for creating textures
  98142. * Return true to stop further extensions from loading this texture
  98143. */
  98144. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  98145. return false;
  98146. };
  98147. /**
  98148. * Defines an override for loading shader strings
  98149. * Return true to stop further extensions from loading this shader data
  98150. */
  98151. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  98152. return false;
  98153. };
  98154. /**
  98155. * Defines an override for loading materials
  98156. * Return true to stop further extensions from loading this material
  98157. */
  98158. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  98159. return false;
  98160. };
  98161. // ---------
  98162. // Utilities
  98163. // ---------
  98164. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  98165. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  98166. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  98167. }, function () {
  98168. setTimeout(function () {
  98169. if (!onSuccess) {
  98170. return;
  98171. }
  98172. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  98173. });
  98174. });
  98175. };
  98176. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  98177. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  98178. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  98179. }, function () {
  98180. setTimeout(function () {
  98181. onSuccess();
  98182. });
  98183. });
  98184. };
  98185. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  98186. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  98187. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  98188. }, function () {
  98189. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  98190. });
  98191. };
  98192. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  98193. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  98194. if (buffer) {
  98195. GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  98196. }
  98197. }, onError);
  98198. };
  98199. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  98200. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  98201. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  98202. }, function () {
  98203. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  98204. });
  98205. };
  98206. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  98207. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  98208. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  98209. }, function () {
  98210. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  98211. });
  98212. };
  98213. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  98214. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  98215. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  98216. }, function () {
  98217. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  98218. });
  98219. };
  98220. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  98221. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  98222. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  98223. }, function () {
  98224. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  98225. });
  98226. };
  98227. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  98228. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  98229. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  98230. if (func(loaderExtension)) {
  98231. return;
  98232. }
  98233. }
  98234. defaultFunc();
  98235. };
  98236. return GLTFLoaderExtension;
  98237. }());
  98238. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  98239. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  98240. })(BABYLON || (BABYLON = {}));
  98241. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  98242. "use strict";
  98243. var BABYLON;
  98244. (function (BABYLON) {
  98245. var GLTF1;
  98246. (function (GLTF1) {
  98247. var BinaryExtensionBufferName = "binary_glTF";
  98248. ;
  98249. ;
  98250. var GLTFBinaryExtension = /** @class */ (function (_super) {
  98251. __extends(GLTFBinaryExtension, _super);
  98252. function GLTFBinaryExtension() {
  98253. return _super.call(this, "KHR_binary_glTF") || this;
  98254. }
  98255. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  98256. var extensionsUsed = data.json.extensionsUsed;
  98257. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  98258. return false;
  98259. }
  98260. this._bin = data.bin;
  98261. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  98262. return true;
  98263. };
  98264. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  98265. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  98266. return false;
  98267. }
  98268. if (id !== BinaryExtensionBufferName) {
  98269. return false;
  98270. }
  98271. onSuccess(this._bin);
  98272. return true;
  98273. };
  98274. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  98275. var texture = gltfRuntime.textures[id];
  98276. var source = gltfRuntime.images[texture.source];
  98277. if (!source.extensions || !(this.name in source.extensions)) {
  98278. return false;
  98279. }
  98280. var sourceExt = source.extensions[this.name];
  98281. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  98282. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  98283. onSuccess(buffer);
  98284. return true;
  98285. };
  98286. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  98287. var shader = gltfRuntime.shaders[id];
  98288. if (!shader.extensions || !(this.name in shader.extensions)) {
  98289. return false;
  98290. }
  98291. var binaryExtensionShader = shader.extensions[this.name];
  98292. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  98293. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  98294. setTimeout(function () {
  98295. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  98296. onSuccess(shaderString);
  98297. });
  98298. return true;
  98299. };
  98300. return GLTFBinaryExtension;
  98301. }(GLTF1.GLTFLoaderExtension));
  98302. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  98303. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  98304. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  98305. })(BABYLON || (BABYLON = {}));
  98306. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  98307. "use strict";
  98308. var BABYLON;
  98309. (function (BABYLON) {
  98310. var GLTF1;
  98311. (function (GLTF1) {
  98312. ;
  98313. ;
  98314. ;
  98315. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  98316. __extends(GLTFMaterialsCommonExtension, _super);
  98317. function GLTFMaterialsCommonExtension() {
  98318. return _super.call(this, "KHR_materials_common") || this;
  98319. }
  98320. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  98321. if (!gltfRuntime.extensions)
  98322. return false;
  98323. var extension = gltfRuntime.extensions[this.name];
  98324. if (!extension)
  98325. return false;
  98326. // Create lights
  98327. var lights = extension.lights;
  98328. if (lights) {
  98329. for (var thing in lights) {
  98330. var light = lights[thing];
  98331. switch (light.type) {
  98332. case "ambient":
  98333. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  98334. var ambient = light.ambient;
  98335. if (ambient) {
  98336. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  98337. }
  98338. break;
  98339. case "point":
  98340. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  98341. var point = light.point;
  98342. if (point) {
  98343. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  98344. }
  98345. break;
  98346. case "directional":
  98347. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  98348. var directional = light.directional;
  98349. if (directional) {
  98350. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  98351. }
  98352. break;
  98353. case "spot":
  98354. var spot = light.spot;
  98355. if (spot) {
  98356. 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);
  98357. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  98358. }
  98359. break;
  98360. default:
  98361. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  98362. break;
  98363. }
  98364. }
  98365. }
  98366. return false;
  98367. };
  98368. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  98369. var material = gltfRuntime.materials[id];
  98370. if (!material || !material.extensions)
  98371. return false;
  98372. var extension = material.extensions[this.name];
  98373. if (!extension)
  98374. return false;
  98375. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  98376. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  98377. if (extension.technique === "CONSTANT") {
  98378. standardMaterial.disableLighting = true;
  98379. }
  98380. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  98381. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  98382. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  98383. // Ambient
  98384. if (typeof extension.values.ambient === "string") {
  98385. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  98386. }
  98387. else {
  98388. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  98389. }
  98390. // Diffuse
  98391. if (typeof extension.values.diffuse === "string") {
  98392. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  98393. }
  98394. else {
  98395. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  98396. }
  98397. // Emission
  98398. if (typeof extension.values.emission === "string") {
  98399. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  98400. }
  98401. else {
  98402. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  98403. }
  98404. // Specular
  98405. if (typeof extension.values.specular === "string") {
  98406. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  98407. }
  98408. else {
  98409. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  98410. }
  98411. return true;
  98412. };
  98413. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  98414. // Create buffer from texture url
  98415. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  98416. // Create texture from buffer
  98417. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  98418. }, onError);
  98419. };
  98420. return GLTFMaterialsCommonExtension;
  98421. }(GLTF1.GLTFLoaderExtension));
  98422. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  98423. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  98424. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  98425. })(BABYLON || (BABYLON = {}));
  98426. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  98427. "use strict";
  98428. var BABYLON;
  98429. (function (BABYLON) {
  98430. var GLTF2;
  98431. (function (GLTF2) {
  98432. var ArrayItem = /** @class */ (function () {
  98433. function ArrayItem() {
  98434. }
  98435. ArrayItem.Assign = function (values) {
  98436. if (values) {
  98437. for (var index = 0; index < values.length; index++) {
  98438. values[index]._index = index;
  98439. }
  98440. }
  98441. };
  98442. return ArrayItem;
  98443. }());
  98444. GLTF2.ArrayItem = ArrayItem;
  98445. var AnimationMultiTarget = /** @class */ (function () {
  98446. function AnimationMultiTarget() {
  98447. this.subTargets = new Array();
  98448. }
  98449. Object.defineProperty(AnimationMultiTarget.prototype, "position", {
  98450. set: function (value) {
  98451. for (var _i = 0, _a = this.subTargets; _i < _a.length; _i++) {
  98452. var subTarget = _a[_i];
  98453. subTarget.position = value;
  98454. }
  98455. },
  98456. enumerable: true,
  98457. configurable: true
  98458. });
  98459. Object.defineProperty(AnimationMultiTarget.prototype, "rotationQuaternion", {
  98460. set: function (value) {
  98461. for (var _i = 0, _a = this.subTargets; _i < _a.length; _i++) {
  98462. var subTarget = _a[_i];
  98463. subTarget.rotationQuaternion = value;
  98464. }
  98465. },
  98466. enumerable: true,
  98467. configurable: true
  98468. });
  98469. Object.defineProperty(AnimationMultiTarget.prototype, "scaling", {
  98470. set: function (value) {
  98471. for (var _i = 0, _a = this.subTargets; _i < _a.length; _i++) {
  98472. var subTarget = _a[_i];
  98473. subTarget.scaling = value;
  98474. }
  98475. },
  98476. enumerable: true,
  98477. configurable: true
  98478. });
  98479. Object.defineProperty(AnimationMultiTarget.prototype, "influence", {
  98480. set: function (value) {
  98481. for (var _i = 0, _a = this.subTargets; _i < _a.length; _i++) {
  98482. var subTarget = _a[_i];
  98483. subTarget.influence = value;
  98484. }
  98485. },
  98486. enumerable: true,
  98487. configurable: true
  98488. });
  98489. return AnimationMultiTarget;
  98490. }());
  98491. GLTF2.AnimationMultiTarget = AnimationMultiTarget;
  98492. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  98493. })(BABYLON || (BABYLON = {}));
  98494. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  98495. "use strict";
  98496. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  98497. "use strict";
  98498. var BABYLON;
  98499. (function (BABYLON) {
  98500. var GLTF2;
  98501. (function (GLTF2) {
  98502. var GLTFLoader = /** @class */ (function () {
  98503. function GLTFLoader() {
  98504. this._completePromises = new Array();
  98505. this._disposed = false;
  98506. this._state = null;
  98507. this._extensions = {};
  98508. this._defaultSampler = {};
  98509. this._defaultBabylonMaterials = {};
  98510. this._requests = new Array();
  98511. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  98512. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  98513. this.compileMaterials = false;
  98514. this.useClipPlane = false;
  98515. this.compileShadowGenerators = false;
  98516. this.onDisposeObservable = new BABYLON.Observable();
  98517. this.onMeshLoadedObservable = new BABYLON.Observable();
  98518. this.onTextureLoadedObservable = new BABYLON.Observable();
  98519. this.onMaterialLoadedObservable = new BABYLON.Observable();
  98520. this.onExtensionLoadedObservable = new BABYLON.Observable();
  98521. this.onCompleteObservable = new BABYLON.Observable();
  98522. }
  98523. GLTFLoader._Register = function (name, factory) {
  98524. if (GLTFLoader._Factories[name]) {
  98525. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  98526. return;
  98527. }
  98528. GLTFLoader._Factories[name] = factory;
  98529. // Keep the order of registration so that extensions registered first are called first.
  98530. GLTFLoader._Names.push(name);
  98531. };
  98532. Object.defineProperty(GLTFLoader.prototype, "state", {
  98533. get: function () {
  98534. return this._state;
  98535. },
  98536. enumerable: true,
  98537. configurable: true
  98538. });
  98539. GLTFLoader.prototype.dispose = function () {
  98540. if (this._disposed) {
  98541. return;
  98542. }
  98543. this._disposed = true;
  98544. this.onDisposeObservable.notifyObservers(this);
  98545. this.onDisposeObservable.clear();
  98546. this._clear();
  98547. };
  98548. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  98549. var _this = this;
  98550. return Promise.resolve().then(function () {
  98551. var nodes = null;
  98552. if (meshesNames) {
  98553. var nodeMap_1 = {};
  98554. if (_this._gltf.nodes) {
  98555. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  98556. var node = _a[_i];
  98557. if (node.name) {
  98558. nodeMap_1[node.name] = node;
  98559. }
  98560. }
  98561. }
  98562. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  98563. nodes = names.map(function (name) {
  98564. var node = nodeMap_1[name];
  98565. if (!node) {
  98566. throw new Error("Failed to find node '" + name + "'");
  98567. }
  98568. return node;
  98569. });
  98570. }
  98571. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  98572. return {
  98573. meshes: _this._getMeshes(),
  98574. particleSystems: [],
  98575. skeletons: _this._getSkeletons(),
  98576. animationGroups: _this._getAnimationGroups()
  98577. };
  98578. });
  98579. });
  98580. };
  98581. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  98582. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  98583. };
  98584. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  98585. var _this = this;
  98586. return Promise.resolve().then(function () {
  98587. _this._loadExtensions();
  98588. _this._babylonScene = scene;
  98589. _this._rootUrl = rootUrl;
  98590. _this._progressCallback = onProgress;
  98591. _this._state = BABYLON.GLTFLoaderState.Loading;
  98592. _this._loadData(data);
  98593. _this._checkExtensions();
  98594. var promises = new Array();
  98595. if (nodes) {
  98596. promises.push(_this._loadNodesAsync(nodes));
  98597. }
  98598. else {
  98599. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  98600. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  98601. }
  98602. if (_this.compileMaterials) {
  98603. promises.push(_this._compileMaterialsAsync());
  98604. }
  98605. if (_this.compileShadowGenerators) {
  98606. promises.push(_this._compileShadowGeneratorsAsync());
  98607. }
  98608. var resultPromise = Promise.all(promises).then(function () {
  98609. _this._state = BABYLON.GLTFLoaderState.Ready;
  98610. _this._startAnimations();
  98611. });
  98612. resultPromise.then(function () {
  98613. _this._rootBabylonMesh.setEnabled(true);
  98614. BABYLON.Tools.SetImmediate(function () {
  98615. if (!_this._disposed) {
  98616. Promise.all(_this._completePromises).then(function () {
  98617. _this._state = BABYLON.GLTFLoaderState.Complete;
  98618. _this.onCompleteObservable.notifyObservers(_this);
  98619. _this.onCompleteObservable.clear();
  98620. _this._clear();
  98621. }).catch(function (error) {
  98622. BABYLON.Tools.Error("glTF Loader: " + error.message);
  98623. _this._clear();
  98624. });
  98625. }
  98626. });
  98627. });
  98628. return resultPromise;
  98629. }).catch(function (error) {
  98630. BABYLON.Tools.Error("glTF Loader: " + error.message);
  98631. _this._clear();
  98632. throw error;
  98633. });
  98634. };
  98635. GLTFLoader.prototype._loadExtensions = function () {
  98636. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  98637. var name_1 = _a[_i];
  98638. var extension = GLTFLoader._Factories[name_1](this);
  98639. this._extensions[name_1] = extension;
  98640. this.onExtensionLoadedObservable.notifyObservers(extension);
  98641. }
  98642. this.onExtensionLoadedObservable.clear();
  98643. };
  98644. GLTFLoader.prototype._loadData = function (data) {
  98645. this._gltf = data.json;
  98646. this._setupData();
  98647. if (data.bin) {
  98648. var buffers = this._gltf.buffers;
  98649. if (buffers && buffers[0] && !buffers[0].uri) {
  98650. var binaryBuffer = buffers[0];
  98651. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  98652. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  98653. }
  98654. binaryBuffer._data = Promise.resolve(data.bin);
  98655. }
  98656. else {
  98657. BABYLON.Tools.Warn("Unexpected BIN chunk");
  98658. }
  98659. }
  98660. };
  98661. GLTFLoader.prototype._setupData = function () {
  98662. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  98663. GLTF2.ArrayItem.Assign(this._gltf.animations);
  98664. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  98665. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  98666. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  98667. GLTF2.ArrayItem.Assign(this._gltf.images);
  98668. GLTF2.ArrayItem.Assign(this._gltf.materials);
  98669. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  98670. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  98671. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  98672. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  98673. GLTF2.ArrayItem.Assign(this._gltf.skins);
  98674. GLTF2.ArrayItem.Assign(this._gltf.textures);
  98675. if (this._gltf.nodes) {
  98676. var nodeParents = {};
  98677. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  98678. var node = _a[_i];
  98679. if (node.children) {
  98680. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  98681. var index = _c[_b];
  98682. nodeParents[index] = node._index;
  98683. }
  98684. }
  98685. }
  98686. var rootNode = this._createRootNode();
  98687. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  98688. var node = _e[_d];
  98689. var parentIndex = nodeParents[node._index];
  98690. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  98691. }
  98692. }
  98693. };
  98694. GLTFLoader.prototype._checkExtensions = function () {
  98695. if (this._gltf.extensionsRequired) {
  98696. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  98697. var name_2 = _a[_i];
  98698. var extension = this._extensions[name_2];
  98699. if (!extension || !extension.enabled) {
  98700. throw new Error("Require extension " + name_2 + " is not available");
  98701. }
  98702. }
  98703. }
  98704. };
  98705. GLTFLoader.prototype._createRootNode = function () {
  98706. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  98707. this._rootBabylonMesh.setEnabled(false);
  98708. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  98709. switch (this.coordinateSystemMode) {
  98710. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  98711. if (!this._babylonScene.useRightHandedSystem) {
  98712. rootNode.rotation = [0, 1, 0, 0];
  98713. rootNode.scale = [1, 1, -1];
  98714. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  98715. }
  98716. break;
  98717. }
  98718. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  98719. this._babylonScene.useRightHandedSystem = true;
  98720. break;
  98721. }
  98722. default: {
  98723. throw new Error("Invalid coordinate system mode (" + this.coordinateSystemMode + ")");
  98724. }
  98725. }
  98726. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  98727. return rootNode;
  98728. };
  98729. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  98730. var promises = new Array();
  98731. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  98732. var node = nodes_1[_i];
  98733. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  98734. }
  98735. promises.push(this._loadAnimationsAsync());
  98736. return Promise.all(promises).then(function () { });
  98737. };
  98738. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  98739. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  98740. if (promise) {
  98741. return promise;
  98742. }
  98743. var promises = new Array();
  98744. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  98745. var index = _a[_i];
  98746. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  98747. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  98748. }
  98749. promises.push(this._loadAnimationsAsync());
  98750. return Promise.all(promises).then(function () { });
  98751. };
  98752. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  98753. if (node._primitiveBabylonMeshes) {
  98754. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  98755. var babylonMesh = _a[_i];
  98756. callback(babylonMesh);
  98757. }
  98758. }
  98759. else {
  98760. callback(node._babylonMesh);
  98761. }
  98762. };
  98763. GLTFLoader.prototype._getMeshes = function () {
  98764. var meshes = new Array();
  98765. // Root mesh is always first.
  98766. meshes.push(this._rootBabylonMesh);
  98767. var nodes = this._gltf.nodes;
  98768. if (nodes) {
  98769. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  98770. var node = nodes_2[_i];
  98771. if (node._babylonMesh) {
  98772. meshes.push(node._babylonMesh);
  98773. }
  98774. if (node._primitiveBabylonMeshes) {
  98775. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  98776. var babylonMesh = _b[_a];
  98777. meshes.push(babylonMesh);
  98778. }
  98779. }
  98780. }
  98781. }
  98782. return meshes;
  98783. };
  98784. GLTFLoader.prototype._getSkeletons = function () {
  98785. var skeletons = new Array();
  98786. var skins = this._gltf.skins;
  98787. if (skins) {
  98788. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  98789. var skin = skins_1[_i];
  98790. if (skin._babylonSkeleton) {
  98791. skeletons.push(skin._babylonSkeleton);
  98792. }
  98793. }
  98794. }
  98795. return skeletons;
  98796. };
  98797. GLTFLoader.prototype._getAnimationGroups = function () {
  98798. var animationGroups = new Array();
  98799. var animations = this._gltf.animations;
  98800. if (animations) {
  98801. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  98802. var animation = animations_1[_i];
  98803. if (animation._babylonAnimationGroup) {
  98804. animationGroups.push(animation._babylonAnimationGroup);
  98805. }
  98806. }
  98807. }
  98808. return animationGroups;
  98809. };
  98810. GLTFLoader.prototype._startAnimations = function () {
  98811. switch (this.animationStartMode) {
  98812. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  98813. // do nothing
  98814. break;
  98815. }
  98816. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  98817. var babylonAnimationGroups = this._getAnimationGroups();
  98818. if (babylonAnimationGroups.length !== 0) {
  98819. babylonAnimationGroups[0].start(true);
  98820. }
  98821. break;
  98822. }
  98823. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  98824. var babylonAnimationGroups = this._getAnimationGroups();
  98825. for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) {
  98826. var babylonAnimationGroup = babylonAnimationGroups_1[_i];
  98827. babylonAnimationGroup.start(true);
  98828. }
  98829. break;
  98830. }
  98831. default: {
  98832. BABYLON.Tools.Error("Invalid animation start mode (" + this.animationStartMode + ")");
  98833. return;
  98834. }
  98835. }
  98836. };
  98837. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  98838. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  98839. if (promise) {
  98840. return promise;
  98841. }
  98842. if (node._babylonMesh) {
  98843. throw new Error(context + ": Invalid recursive node hierarchy");
  98844. }
  98845. var promises = new Array();
  98846. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  98847. node._babylonMesh = babylonMesh;
  98848. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  98849. node._babylonAnimationTargets.push(babylonMesh);
  98850. GLTFLoader._LoadTransform(node, babylonMesh);
  98851. if (node.mesh != undefined) {
  98852. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  98853. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  98854. }
  98855. if (node.children) {
  98856. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  98857. var index = _a[_i];
  98858. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  98859. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  98860. }
  98861. }
  98862. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  98863. return Promise.all(promises).then(function () { });
  98864. };
  98865. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  98866. // TODO: instancing
  98867. var _this = this;
  98868. var promises = new Array();
  98869. var primitives = mesh.primitives;
  98870. if (!primitives || primitives.length === 0) {
  98871. throw new Error(context + ": Primitives are missing");
  98872. }
  98873. GLTF2.ArrayItem.Assign(primitives);
  98874. if (primitives.length === 1) {
  98875. var primitive = primitives[0];
  98876. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  98877. }
  98878. else {
  98879. node._primitiveBabylonMeshes = [];
  98880. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  98881. var primitive = primitives_1[_i];
  98882. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  98883. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  98884. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  98885. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  98886. }
  98887. }
  98888. if (node.skin != undefined) {
  98889. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  98890. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  98891. }
  98892. return Promise.all(promises).then(function () {
  98893. _this._forEachPrimitive(node, function (babylonMesh) {
  98894. babylonMesh._refreshBoundingInfo(true);
  98895. });
  98896. });
  98897. };
  98898. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  98899. var _this = this;
  98900. var promises = new Array();
  98901. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  98902. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonVertexData) {
  98903. new BABYLON.Geometry(babylonMesh.name, _this._babylonScene, babylonVertexData, false, babylonMesh);
  98904. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
  98905. }));
  98906. var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  98907. if (primitive.material == undefined) {
  98908. babylonMesh.material = this._getDefaultMaterial(babylonDrawMode);
  98909. }
  98910. else {
  98911. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  98912. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  98913. babylonMesh.material = babylonMaterial;
  98914. }));
  98915. }
  98916. return Promise.all(promises).then(function () { });
  98917. };
  98918. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  98919. var _this = this;
  98920. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  98921. if (promise) {
  98922. return promise;
  98923. }
  98924. var attributes = primitive.attributes;
  98925. if (!attributes) {
  98926. throw new Error(context + ": Attributes are missing");
  98927. }
  98928. var promises = new Array();
  98929. var babylonVertexData = new BABYLON.VertexData();
  98930. if (primitive.indices == undefined) {
  98931. var positionAccessorIndex = attributes["POSITION"];
  98932. if (positionAccessorIndex != undefined) {
  98933. var accessor = GLTFLoader._GetProperty(context + "/attributes/POSITION", this._gltf.accessors, positionAccessorIndex);
  98934. babylonVertexData.indices = new Uint32Array(accessor.count);
  98935. for (var i = 0; i < babylonVertexData.indices.length; i++) {
  98936. babylonVertexData.indices[i] = i;
  98937. }
  98938. }
  98939. }
  98940. else {
  98941. var indicesAccessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  98942. promises.push(this._loadAccessorAsync("#/accessors/" + indicesAccessor._index, indicesAccessor).then(function (data) {
  98943. babylonVertexData.indices = data;
  98944. }));
  98945. }
  98946. var loadAttribute = function (attribute, kind) {
  98947. if (attributes[attribute] == undefined) {
  98948. return;
  98949. }
  98950. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  98951. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  98952. babylonMesh._delayInfo.push(kind);
  98953. }
  98954. if (attribute === "COLOR_0") {
  98955. // Assume vertex color has alpha on the mesh. The alphaMode of the material controls whether the material should use alpha or not.
  98956. babylonMesh.hasVertexAlpha = true;
  98957. }
  98958. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  98959. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  98960. var attributeData = GLTFLoader._ConvertToFloat32Array(context, accessor, data);
  98961. if (attribute === "COLOR_0" && accessor.type === "VEC3") {
  98962. attributeData = GLTFLoader._ConvertVec3ToVec4(context, attributeData);
  98963. }
  98964. babylonVertexData.set(attributeData, kind);
  98965. }));
  98966. };
  98967. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  98968. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  98969. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  98970. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  98971. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  98972. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  98973. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  98974. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  98975. return Promise.all(promises).then(function () {
  98976. return babylonVertexData;
  98977. });
  98978. };
  98979. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  98980. if (!primitive.targets) {
  98981. return;
  98982. }
  98983. if (node._numMorphTargets == undefined) {
  98984. node._numMorphTargets = primitive.targets.length;
  98985. }
  98986. else if (primitive.targets.length !== node._numMorphTargets) {
  98987. throw new Error(context + ": Primitives do not have the same number of targets");
  98988. }
  98989. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  98990. for (var index = 0; index < primitive.targets.length; index++) {
  98991. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  98992. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  98993. // TODO: tell the target whether it has positions, normals, tangents
  98994. }
  98995. };
  98996. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonVertexData) {
  98997. if (!primitive.targets) {
  98998. return Promise.resolve();
  98999. }
  99000. var promises = new Array();
  99001. var morphTargetManager = babylonMesh.morphTargetManager;
  99002. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  99003. var babylonMorphTarget = morphTargetManager.getTarget(index);
  99004. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonVertexData, primitive.targets[index], babylonMorphTarget));
  99005. }
  99006. return Promise.all(promises).then(function () { });
  99007. };
  99008. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonVertexData, attributes, babylonMorphTarget) {
  99009. var _this = this;
  99010. var promises = new Array();
  99011. var loadAttribute = function (attribute, setData) {
  99012. if (attributes[attribute] == undefined) {
  99013. return;
  99014. }
  99015. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  99016. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  99017. setData(data);
  99018. }));
  99019. };
  99020. loadAttribute("POSITION", function (data) {
  99021. if (babylonVertexData.positions) {
  99022. for (var i = 0; i < data.length; i++) {
  99023. data[i] += babylonVertexData.positions[i];
  99024. }
  99025. babylonMorphTarget.setPositions(data);
  99026. }
  99027. });
  99028. loadAttribute("NORMAL", function (data) {
  99029. if (babylonVertexData.normals) {
  99030. for (var i = 0; i < data.length; i++) {
  99031. data[i] += babylonVertexData.normals[i];
  99032. }
  99033. babylonMorphTarget.setNormals(data);
  99034. }
  99035. });
  99036. loadAttribute("TANGENT", function (data) {
  99037. if (babylonVertexData.tangents) {
  99038. // Tangent data for morph targets is stored as xyz delta.
  99039. // The vertexData.tangent is stored as xyzw.
  99040. // So we need to skip every fourth vertexData.tangent.
  99041. for (var i = 0, j = 0; i < data.length; i++) {
  99042. data[i] += babylonVertexData.tangents[j++];
  99043. if ((i + 1) % 3 == 0) {
  99044. j++;
  99045. }
  99046. }
  99047. babylonMorphTarget.setTangents(data);
  99048. }
  99049. });
  99050. return Promise.all(promises).then(function () { });
  99051. };
  99052. GLTFLoader._ConvertToFloat32Array = function (context, accessor, data) {
  99053. if (accessor.componentType == 5126 /* FLOAT */) {
  99054. return data;
  99055. }
  99056. var factor = 1;
  99057. if (accessor.normalized) {
  99058. switch (accessor.componentType) {
  99059. case 5121 /* UNSIGNED_BYTE */: {
  99060. factor = 1 / 255;
  99061. break;
  99062. }
  99063. case 5123 /* UNSIGNED_SHORT */: {
  99064. factor = 1 / 65535;
  99065. break;
  99066. }
  99067. default: {
  99068. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  99069. }
  99070. }
  99071. }
  99072. var result = new Float32Array(accessor.count * GLTFLoader._GetNumComponents(context, accessor.type));
  99073. for (var i = 0; i < result.length; i++) {
  99074. result[i] = data[i] * factor;
  99075. }
  99076. return result;
  99077. };
  99078. GLTFLoader._ConvertVec3ToVec4 = function (context, data) {
  99079. var result = new Float32Array(data.length / 3 * 4);
  99080. var offset = 0;
  99081. for (var i = 0; i < result.length; i++) {
  99082. if ((i + 1) % 4 === 0) {
  99083. result[i] = 1;
  99084. }
  99085. else {
  99086. result[i] = data[offset++];
  99087. }
  99088. }
  99089. return result;
  99090. };
  99091. GLTFLoader._LoadTransform = function (node, babylonNode) {
  99092. var position = BABYLON.Vector3.Zero();
  99093. var rotation = BABYLON.Quaternion.Identity();
  99094. var scaling = BABYLON.Vector3.One();
  99095. if (node.matrix) {
  99096. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  99097. matrix.decompose(scaling, rotation, position);
  99098. }
  99099. else {
  99100. if (node.translation)
  99101. position = BABYLON.Vector3.FromArray(node.translation);
  99102. if (node.rotation)
  99103. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  99104. if (node.scale)
  99105. scaling = BABYLON.Vector3.FromArray(node.scale);
  99106. }
  99107. babylonNode.position = position;
  99108. babylonNode.rotationQuaternion = rotation;
  99109. babylonNode.scaling = scaling;
  99110. };
  99111. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  99112. var _this = this;
  99113. var assignSkeleton = function () {
  99114. _this._forEachPrimitive(node, function (babylonMesh) {
  99115. babylonMesh.skeleton = skin._babylonSkeleton;
  99116. });
  99117. // Ignore the TRS of skinned nodes.
  99118. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  99119. node._babylonMesh.parent = _this._rootBabylonMesh;
  99120. node._babylonMesh.position = BABYLON.Vector3.Zero();
  99121. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  99122. node._babylonMesh.scaling = BABYLON.Vector3.One();
  99123. };
  99124. if (skin._loaded) {
  99125. return skin._loaded.then(function () {
  99126. assignSkeleton();
  99127. });
  99128. }
  99129. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  99130. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  99131. var skeletonId = "skeleton" + skin._index;
  99132. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  99133. skin._babylonSkeleton = babylonSkeleton;
  99134. _this._loadBones(context, skin, inverseBindMatricesData);
  99135. assignSkeleton();
  99136. }));
  99137. };
  99138. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  99139. if (skin.inverseBindMatrices == undefined) {
  99140. return Promise.resolve(null);
  99141. }
  99142. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  99143. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  99144. return data;
  99145. });
  99146. };
  99147. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  99148. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  99149. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  99150. node._babylonAnimationTargets.push(babylonBone);
  99151. return babylonBone;
  99152. };
  99153. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  99154. var babylonBones = {};
  99155. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  99156. var index = _a[_i];
  99157. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  99158. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  99159. }
  99160. };
  99161. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  99162. var babylonBone = babylonBones[node._index];
  99163. if (babylonBone) {
  99164. return babylonBone;
  99165. }
  99166. var boneIndex = skin.joints.indexOf(node._index);
  99167. var baseMatrix = BABYLON.Matrix.Identity();
  99168. if (inverseBindMatricesData && boneIndex !== -1) {
  99169. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  99170. baseMatrix.invertToRef(baseMatrix);
  99171. }
  99172. var babylonParentBone = null;
  99173. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  99174. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  99175. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  99176. }
  99177. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  99178. babylonBones[node._index] = babylonBone;
  99179. return babylonBone;
  99180. };
  99181. GLTFLoader.prototype._getNodeMatrix = function (node) {
  99182. return node.matrix ?
  99183. BABYLON.Matrix.FromArray(node.matrix) :
  99184. 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());
  99185. };
  99186. GLTFLoader.prototype._loadAnimationsAsync = function () {
  99187. var animations = this._gltf.animations;
  99188. if (!animations) {
  99189. return Promise.resolve();
  99190. }
  99191. var promises = new Array();
  99192. for (var index = 0; index < animations.length; index++) {
  99193. var animation = animations[index];
  99194. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  99195. }
  99196. return Promise.all(promises).then(function () { });
  99197. };
  99198. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  99199. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  99200. animation._babylonAnimationGroup = babylonAnimationGroup;
  99201. var promises = new Array();
  99202. GLTF2.ArrayItem.Assign(animation.channels);
  99203. GLTF2.ArrayItem.Assign(animation.samplers);
  99204. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  99205. var channel = _a[_i];
  99206. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  99207. }
  99208. return Promise.all(promises).then(function () {
  99209. babylonAnimationGroup.normalize();
  99210. });
  99211. };
  99212. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  99213. var _this = this;
  99214. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  99215. if (!targetNode._babylonMesh) {
  99216. return Promise.resolve();
  99217. }
  99218. // Ignore animations targeting TRS of skinned nodes.
  99219. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  99220. if (targetNode.skin != undefined && channel.target.path !== "weights" /* WEIGHTS */) {
  99221. return Promise.resolve();
  99222. }
  99223. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  99224. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  99225. var targetPath;
  99226. var animationType;
  99227. switch (channel.target.path) {
  99228. case "translation" /* TRANSLATION */: {
  99229. targetPath = "position";
  99230. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  99231. break;
  99232. }
  99233. case "rotation" /* ROTATION */: {
  99234. targetPath = "rotationQuaternion";
  99235. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  99236. break;
  99237. }
  99238. case "scale" /* SCALE */: {
  99239. targetPath = "scaling";
  99240. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  99241. break;
  99242. }
  99243. case "weights" /* WEIGHTS */: {
  99244. targetPath = "influence";
  99245. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  99246. break;
  99247. }
  99248. default: {
  99249. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  99250. }
  99251. }
  99252. var outputBufferOffset = 0;
  99253. var getNextOutputValue;
  99254. switch (targetPath) {
  99255. case "position": {
  99256. getNextOutputValue = function () {
  99257. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  99258. outputBufferOffset += 3;
  99259. return value;
  99260. };
  99261. break;
  99262. }
  99263. case "rotationQuaternion": {
  99264. getNextOutputValue = function () {
  99265. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  99266. outputBufferOffset += 4;
  99267. return value;
  99268. };
  99269. break;
  99270. }
  99271. case "scaling": {
  99272. getNextOutputValue = function () {
  99273. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  99274. outputBufferOffset += 3;
  99275. return value;
  99276. };
  99277. break;
  99278. }
  99279. case "influence": {
  99280. getNextOutputValue = function () {
  99281. var value = new Array(targetNode._numMorphTargets);
  99282. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  99283. value[i] = data.output[outputBufferOffset++];
  99284. }
  99285. return value;
  99286. };
  99287. break;
  99288. }
  99289. }
  99290. var getNextKey;
  99291. switch (data.interpolation) {
  99292. case "STEP" /* STEP */: {
  99293. getNextKey = function (frameIndex) { return ({
  99294. frame: data.input[frameIndex],
  99295. value: getNextOutputValue(),
  99296. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  99297. }); };
  99298. break;
  99299. }
  99300. case "LINEAR" /* LINEAR */: {
  99301. getNextKey = function (frameIndex) { return ({
  99302. frame: data.input[frameIndex],
  99303. value: getNextOutputValue()
  99304. }); };
  99305. break;
  99306. }
  99307. case "CUBICSPLINE" /* CUBICSPLINE */: {
  99308. getNextKey = function (frameIndex) { return ({
  99309. frame: data.input[frameIndex],
  99310. inTangent: getNextOutputValue(),
  99311. value: getNextOutputValue(),
  99312. outTangent: getNextOutputValue()
  99313. }); };
  99314. break;
  99315. }
  99316. }
  99317. var keys = new Array(data.input.length);
  99318. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  99319. keys[frameIndex] = getNextKey(frameIndex);
  99320. }
  99321. if (targetPath === "influence") {
  99322. var _loop_1 = function (targetIndex) {
  99323. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  99324. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  99325. babylonAnimation.setKeys(keys.map(function (key) { return ({
  99326. frame: key.frame,
  99327. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  99328. value: key.value[targetIndex],
  99329. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  99330. }); }));
  99331. var multiTarget = new GLTF2.AnimationMultiTarget();
  99332. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  99333. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  99334. multiTarget.subTargets.push(morphTarget);
  99335. });
  99336. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, multiTarget);
  99337. };
  99338. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  99339. _loop_1(targetIndex);
  99340. }
  99341. }
  99342. else {
  99343. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  99344. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  99345. babylonAnimation.setKeys(keys);
  99346. if (targetNode._babylonAnimationTargets) {
  99347. var multiTarget = new GLTF2.AnimationMultiTarget();
  99348. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  99349. var target = _a[_i];
  99350. multiTarget.subTargets.push(target);
  99351. }
  99352. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, multiTarget);
  99353. }
  99354. }
  99355. });
  99356. };
  99357. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  99358. if (sampler._data) {
  99359. return sampler._data;
  99360. }
  99361. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  99362. switch (interpolation) {
  99363. case "STEP" /* STEP */:
  99364. case "LINEAR" /* LINEAR */:
  99365. case "CUBICSPLINE" /* CUBICSPLINE */: {
  99366. break;
  99367. }
  99368. default: {
  99369. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  99370. }
  99371. }
  99372. var inputData;
  99373. var outputData;
  99374. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  99375. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  99376. sampler._data = Promise.all([
  99377. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  99378. inputData = data;
  99379. }),
  99380. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  99381. outputData = data;
  99382. })
  99383. ]).then(function () {
  99384. return {
  99385. input: inputData,
  99386. interpolation: interpolation,
  99387. output: outputData,
  99388. };
  99389. });
  99390. return sampler._data;
  99391. };
  99392. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  99393. if (buffer._data) {
  99394. return buffer._data;
  99395. }
  99396. if (!buffer.uri) {
  99397. throw new Error(context + ": Uri is missing");
  99398. }
  99399. buffer._data = this._loadUriAsync(context, buffer.uri);
  99400. return buffer._data;
  99401. };
  99402. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  99403. if (bufferView._data) {
  99404. return bufferView._data;
  99405. }
  99406. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  99407. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  99408. try {
  99409. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  99410. }
  99411. catch (e) {
  99412. throw new Error(context + ": " + e.message);
  99413. }
  99414. });
  99415. return bufferView._data;
  99416. };
  99417. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  99418. var _this = this;
  99419. if (accessor.sparse) {
  99420. throw new Error(context + ": Sparse accessors are not currently supported");
  99421. }
  99422. if (accessor._data) {
  99423. return accessor._data;
  99424. }
  99425. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  99426. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  99427. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  99428. var byteOffset = accessor.byteOffset || 0;
  99429. var byteStride = bufferView.byteStride;
  99430. if (byteStride === 0) {
  99431. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  99432. }
  99433. try {
  99434. switch (accessor.componentType) {
  99435. case 5120 /* BYTE */: {
  99436. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  99437. }
  99438. case 5121 /* UNSIGNED_BYTE */: {
  99439. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  99440. }
  99441. case 5122 /* SHORT */: {
  99442. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  99443. }
  99444. case 5123 /* UNSIGNED_SHORT */: {
  99445. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  99446. }
  99447. case 5125 /* UNSIGNED_INT */: {
  99448. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  99449. }
  99450. case 5126 /* FLOAT */: {
  99451. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  99452. }
  99453. default: {
  99454. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  99455. }
  99456. }
  99457. }
  99458. catch (e) {
  99459. throw new Error(context + ": " + e.messsage);
  99460. }
  99461. });
  99462. return accessor._data;
  99463. };
  99464. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  99465. byteOffset += data.byteOffset;
  99466. var targetLength = count * numComponents;
  99467. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  99468. return new typedArray(data.buffer, byteOffset, targetLength);
  99469. }
  99470. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  99471. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  99472. var targetBuffer = new typedArray(targetLength);
  99473. var sourceIndex = 0;
  99474. var targetIndex = 0;
  99475. while (targetIndex < targetLength) {
  99476. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  99477. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  99478. targetIndex++;
  99479. }
  99480. sourceIndex += elementStride;
  99481. }
  99482. return targetBuffer;
  99483. };
  99484. GLTFLoader.prototype._getDefaultMaterial = function (drawMode) {
  99485. var babylonMaterial = this._defaultBabylonMaterials[drawMode];
  99486. if (!babylonMaterial) {
  99487. babylonMaterial = this._createMaterial(BABYLON.PBRMaterial, "__gltf_default", drawMode);
  99488. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  99489. babylonMaterial.metallic = 1;
  99490. babylonMaterial.roughness = 1;
  99491. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  99492. }
  99493. return babylonMaterial;
  99494. };
  99495. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material, babylonMaterial) {
  99496. var promises = new Array();
  99497. // Ensure metallic workflow
  99498. babylonMaterial.metallic = 1;
  99499. babylonMaterial.roughness = 1;
  99500. var properties = material.pbrMetallicRoughness;
  99501. if (properties) {
  99502. if (properties.baseColorFactor) {
  99503. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  99504. babylonMaterial.alpha = properties.baseColorFactor[3];
  99505. }
  99506. else {
  99507. babylonMaterial.albedoColor = BABYLON.Color3.White();
  99508. }
  99509. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  99510. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  99511. if (properties.baseColorTexture) {
  99512. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  99513. babylonMaterial.albedoTexture = texture;
  99514. }));
  99515. }
  99516. if (properties.metallicRoughnessTexture) {
  99517. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  99518. babylonMaterial.metallicTexture = texture;
  99519. }));
  99520. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  99521. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  99522. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  99523. }
  99524. }
  99525. this._loadMaterialAlphaProperties(context, material, babylonMaterial);
  99526. return Promise.all(promises).then(function () { });
  99527. };
  99528. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  99529. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh, babylonDrawMode, assign);
  99530. if (promise) {
  99531. return promise;
  99532. }
  99533. material._babylonData = material._babylonData || {};
  99534. var babylonData = material._babylonData[babylonDrawMode];
  99535. if (!babylonData) {
  99536. var promises = new Array();
  99537. var name_3 = material.name || "materialSG_" + material._index;
  99538. var babylonMaterial = this._createMaterial(BABYLON.PBRMaterial, name_3, babylonDrawMode);
  99539. promises.push(this._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  99540. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material, babylonMaterial));
  99541. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  99542. babylonData = {
  99543. material: babylonMaterial,
  99544. meshes: [],
  99545. loaded: Promise.all(promises).then(function () { })
  99546. };
  99547. material._babylonData[babylonDrawMode] = babylonData;
  99548. }
  99549. babylonData.meshes.push(babylonMesh);
  99550. assign(babylonData.material);
  99551. return babylonData.loaded;
  99552. };
  99553. GLTFLoader.prototype._createMaterial = function (type, name, drawMode) {
  99554. var babylonMaterial = new type(name, this._babylonScene);
  99555. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  99556. babylonMaterial.fillMode = drawMode;
  99557. return babylonMaterial;
  99558. };
  99559. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  99560. var promises = new Array();
  99561. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  99562. if (material.doubleSided) {
  99563. babylonMaterial.backFaceCulling = false;
  99564. babylonMaterial.twoSidedLighting = true;
  99565. }
  99566. if (material.normalTexture) {
  99567. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  99568. babylonMaterial.bumpTexture = texture;
  99569. }));
  99570. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  99571. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  99572. if (material.normalTexture.scale != undefined) {
  99573. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  99574. }
  99575. }
  99576. if (material.occlusionTexture) {
  99577. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  99578. babylonMaterial.ambientTexture = texture;
  99579. }));
  99580. babylonMaterial.useAmbientInGrayScale = true;
  99581. if (material.occlusionTexture.strength != undefined) {
  99582. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  99583. }
  99584. }
  99585. if (material.emissiveTexture) {
  99586. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  99587. babylonMaterial.emissiveTexture = texture;
  99588. }));
  99589. }
  99590. return Promise.all(promises).then(function () { });
  99591. };
  99592. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  99593. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  99594. switch (alphaMode) {
  99595. case "OPAQUE" /* OPAQUE */: {
  99596. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  99597. break;
  99598. }
  99599. case "MASK" /* MASK */: {
  99600. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  99601. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  99602. if (babylonMaterial.albedoTexture) {
  99603. babylonMaterial.albedoTexture.hasAlpha = true;
  99604. }
  99605. break;
  99606. }
  99607. case "BLEND" /* BLEND */: {
  99608. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  99609. if (babylonMaterial.albedoTexture) {
  99610. babylonMaterial.albedoTexture.hasAlpha = true;
  99611. babylonMaterial.useAlphaFromAlbedoTexture = true;
  99612. }
  99613. break;
  99614. }
  99615. default: {
  99616. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  99617. }
  99618. }
  99619. };
  99620. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  99621. var _this = this;
  99622. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  99623. context = "#/textures/" + textureInfo.index;
  99624. var promises = new Array();
  99625. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  99626. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  99627. var deferred = new BABYLON.Deferred();
  99628. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  99629. if (!_this._disposed) {
  99630. deferred.resolve();
  99631. }
  99632. }, function (message, exception) {
  99633. if (!_this._disposed) {
  99634. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  99635. }
  99636. });
  99637. promises.push(deferred.promise);
  99638. babylonTexture.name = texture.name || "texture" + texture._index;
  99639. babylonTexture.wrapU = samplerData.wrapU;
  99640. babylonTexture.wrapV = samplerData.wrapV;
  99641. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  99642. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  99643. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  99644. babylonTexture.updateURL(objectURL);
  99645. }));
  99646. assign(babylonTexture);
  99647. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  99648. return Promise.all(promises).then(function () { });
  99649. };
  99650. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  99651. if (!sampler._data) {
  99652. sampler._data = {
  99653. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  99654. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  99655. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  99656. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  99657. };
  99658. }
  99659. ;
  99660. return sampler._data;
  99661. };
  99662. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  99663. if (image._objectURL) {
  99664. return image._objectURL;
  99665. }
  99666. var promise;
  99667. if (image.uri) {
  99668. promise = this._loadUriAsync(context, image.uri);
  99669. }
  99670. else {
  99671. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  99672. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  99673. }
  99674. image._objectURL = promise.then(function (data) {
  99675. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  99676. });
  99677. return image._objectURL;
  99678. };
  99679. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  99680. var _this = this;
  99681. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  99682. if (promise) {
  99683. return promise;
  99684. }
  99685. if (!GLTFLoader._ValidateUri(uri)) {
  99686. throw new Error(context + ": Uri '" + uri + "' is invalid");
  99687. }
  99688. if (BABYLON.Tools.IsBase64(uri)) {
  99689. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  99690. }
  99691. return new Promise(function (resolve, reject) {
  99692. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  99693. if (!_this._disposed) {
  99694. resolve(new Uint8Array(data));
  99695. }
  99696. }, function (event) {
  99697. if (!_this._disposed) {
  99698. try {
  99699. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  99700. request._lengthComputable = event.lengthComputable;
  99701. request._loaded = event.loaded;
  99702. request._total = event.total;
  99703. _this._onProgress();
  99704. }
  99705. }
  99706. catch (e) {
  99707. reject(e);
  99708. }
  99709. }
  99710. }, _this._babylonScene.database, true, function (request, exception) {
  99711. if (!_this._disposed) {
  99712. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  99713. }
  99714. });
  99715. _this._requests.push(request);
  99716. });
  99717. };
  99718. GLTFLoader.prototype._onProgress = function () {
  99719. if (!this._progressCallback) {
  99720. return;
  99721. }
  99722. var lengthComputable = true;
  99723. var loaded = 0;
  99724. var total = 0;
  99725. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  99726. var request = _a[_i];
  99727. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  99728. return;
  99729. }
  99730. lengthComputable = lengthComputable && request._lengthComputable;
  99731. loaded += request._loaded;
  99732. total += request._total;
  99733. }
  99734. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  99735. };
  99736. GLTFLoader._GetProperty = function (context, array, index) {
  99737. if (!array || index == undefined || !array[index]) {
  99738. throw new Error(context + ": Failed to find index (" + index + ")");
  99739. }
  99740. return array[index];
  99741. };
  99742. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  99743. // Set defaults if undefined
  99744. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  99745. switch (mode) {
  99746. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  99747. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  99748. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  99749. default:
  99750. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  99751. return BABYLON.Texture.WRAP_ADDRESSMODE;
  99752. }
  99753. };
  99754. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  99755. // Set defaults if undefined
  99756. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  99757. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  99758. if (magFilter === 9729 /* LINEAR */) {
  99759. switch (minFilter) {
  99760. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  99761. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  99762. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  99763. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  99764. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  99765. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  99766. default:
  99767. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  99768. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  99769. }
  99770. }
  99771. else {
  99772. if (magFilter !== 9728 /* NEAREST */) {
  99773. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  99774. }
  99775. switch (minFilter) {
  99776. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  99777. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  99778. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  99779. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  99780. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  99781. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  99782. default:
  99783. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  99784. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  99785. }
  99786. }
  99787. };
  99788. GLTFLoader._GetNumComponents = function (context, type) {
  99789. switch (type) {
  99790. case "SCALAR": return 1;
  99791. case "VEC2": return 2;
  99792. case "VEC3": return 3;
  99793. case "VEC4": return 4;
  99794. case "MAT2": return 4;
  99795. case "MAT3": return 9;
  99796. case "MAT4": return 16;
  99797. }
  99798. throw new Error(context + ": Invalid type (" + type + ")");
  99799. };
  99800. GLTFLoader._ValidateUri = function (uri) {
  99801. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  99802. };
  99803. GLTFLoader._GetDrawMode = function (context, mode) {
  99804. if (mode == undefined) {
  99805. mode = 4 /* TRIANGLES */;
  99806. }
  99807. switch (mode) {
  99808. case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode;
  99809. case 1 /* LINES */: return BABYLON.Material.LineListDrawMode;
  99810. case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode;
  99811. case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode;
  99812. case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode;
  99813. case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode;
  99814. case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode;
  99815. }
  99816. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  99817. };
  99818. GLTFLoader.prototype._compileMaterialsAsync = function () {
  99819. var promises = new Array();
  99820. if (this._gltf.materials) {
  99821. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  99822. var material = _a[_i];
  99823. if (material._babylonData) {
  99824. for (var babylonDrawMode in material._babylonData) {
  99825. var babylonData = material._babylonData[babylonDrawMode];
  99826. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  99827. var babylonMesh = _c[_b];
  99828. // Ensure nonUniformScaling is set if necessary.
  99829. babylonMesh.computeWorldMatrix(true);
  99830. var babylonMaterial = babylonData.material;
  99831. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  99832. if (this.useClipPlane) {
  99833. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  99834. }
  99835. }
  99836. }
  99837. }
  99838. }
  99839. }
  99840. return Promise.all(promises).then(function () { });
  99841. };
  99842. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  99843. var promises = new Array();
  99844. var lights = this._babylonScene.lights;
  99845. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  99846. var light = lights_1[_i];
  99847. var generator = light.getShadowGenerator();
  99848. if (generator) {
  99849. promises.push(generator.forceCompilationAsync());
  99850. }
  99851. }
  99852. return Promise.all(promises).then(function () { });
  99853. };
  99854. GLTFLoader.prototype._clear = function () {
  99855. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  99856. var request = _a[_i];
  99857. request.abort();
  99858. }
  99859. this._requests.length = 0;
  99860. if (this._gltf && this._gltf.images) {
  99861. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  99862. var image = _c[_b];
  99863. if (image._objectURL) {
  99864. image._objectURL.then(function (value) {
  99865. URL.revokeObjectURL(value);
  99866. });
  99867. image._objectURL = undefined;
  99868. }
  99869. }
  99870. }
  99871. delete this._gltf;
  99872. delete this._babylonScene;
  99873. this._completePromises.length = 0;
  99874. for (var name_4 in this._extensions) {
  99875. this._extensions[name_4].dispose();
  99876. }
  99877. this._extensions = {};
  99878. delete this._rootBabylonMesh;
  99879. delete this._progressCallback;
  99880. this.onMeshLoadedObservable.clear();
  99881. this.onTextureLoadedObservable.clear();
  99882. this.onMaterialLoadedObservable.clear();
  99883. };
  99884. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  99885. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  99886. var name_5 = _a[_i];
  99887. var extension = this._extensions[name_5];
  99888. if (extension.enabled) {
  99889. var promise = actionAsync(extension);
  99890. if (promise) {
  99891. return promise;
  99892. }
  99893. }
  99894. }
  99895. return null;
  99896. };
  99897. GLTFLoader._Names = new Array();
  99898. GLTFLoader._Factories = {};
  99899. return GLTFLoader;
  99900. }());
  99901. GLTF2.GLTFLoader = GLTFLoader;
  99902. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  99903. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  99904. })(BABYLON || (BABYLON = {}));
  99905. //# sourceMappingURL=babylon.glTFLoader.js.map
  99906. "use strict";
  99907. var BABYLON;
  99908. (function (BABYLON) {
  99909. var GLTF2;
  99910. (function (GLTF2) {
  99911. var GLTFLoaderExtension = /** @class */ (function () {
  99912. function GLTFLoaderExtension(loader) {
  99913. this.enabled = true;
  99914. this._loader = loader;
  99915. }
  99916. GLTFLoaderExtension.prototype.dispose = function () {
  99917. delete this._loader;
  99918. };
  99919. // #region Overridable Methods
  99920. /** Override this method to modify the default behavior for loading scenes. */
  99921. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  99922. /** Override this method to modify the default behavior for loading nodes. */
  99923. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  99924. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  99925. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  99926. /** Override this method to modify the default behavior for loading materials. */
  99927. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) { return null; };
  99928. /** Override this method to modify the default behavior for loading uris. */
  99929. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  99930. // #endregion
  99931. /** Helper method called by a loader extension to load an glTF extension. */
  99932. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  99933. if (!property.extensions) {
  99934. return null;
  99935. }
  99936. var extensions = property.extensions;
  99937. var extension = extensions[this.name];
  99938. if (!extension) {
  99939. return null;
  99940. }
  99941. // Clear out the extension before executing the action to avoid recursing into the same property.
  99942. delete extensions[this.name];
  99943. try {
  99944. return actionAsync(context + "/extensions/" + this.name, extension);
  99945. }
  99946. finally {
  99947. // Restore the extension after executing the action.
  99948. extensions[this.name] = extension;
  99949. }
  99950. };
  99951. /** Helper method called by the loader to allow extensions to override loading scenes. */
  99952. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  99953. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  99954. };
  99955. /** Helper method called by the loader to allow extensions to override loading nodes. */
  99956. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  99957. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  99958. };
  99959. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  99960. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  99961. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  99962. };
  99963. /** Helper method called by the loader to allow extensions to override loading materials. */
  99964. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh, babylonDrawMode, assign) {
  99965. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign); });
  99966. };
  99967. /** Helper method called by the loader to allow extensions to override loading uris. */
  99968. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  99969. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  99970. };
  99971. return GLTFLoaderExtension;
  99972. }());
  99973. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  99974. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  99975. })(BABYLON || (BABYLON = {}));
  99976. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  99977. "use strict";
  99978. var BABYLON;
  99979. (function (BABYLON) {
  99980. var GLTF2;
  99981. (function (GLTF2) {
  99982. var Extensions;
  99983. (function (Extensions) {
  99984. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  99985. var NAME = "MSFT_lod";
  99986. var MSFT_lod = /** @class */ (function (_super) {
  99987. __extends(MSFT_lod, _super);
  99988. function MSFT_lod() {
  99989. var _this = _super !== null && _super.apply(this, arguments) || this;
  99990. _this.name = NAME;
  99991. /**
  99992. * Maximum number of LODs to load, starting from the lowest LOD.
  99993. */
  99994. _this.maxLODsToLoad = Number.MAX_VALUE;
  99995. _this._loadingNodeLOD = null;
  99996. _this._loadNodeSignals = {};
  99997. _this._loadingMaterialLOD = null;
  99998. _this._loadMaterialSignals = {};
  99999. return _this;
  100000. }
  100001. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  100002. var _this = this;
  100003. return this._loadExtensionAsync(context, node, function (context, extension) {
  100004. var firstPromise;
  100005. var nodeLODs = _this._getLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  100006. var _loop_1 = function (indexLOD) {
  100007. var nodeLOD = nodeLODs[indexLOD];
  100008. if (indexLOD !== 0) {
  100009. _this._loadingNodeLOD = nodeLOD;
  100010. if (!_this._loadNodeSignals[nodeLOD._index]) {
  100011. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  100012. }
  100013. }
  100014. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  100015. if (indexLOD !== 0) {
  100016. var previousNodeLOD = nodeLODs[indexLOD - 1];
  100017. if (previousNodeLOD._babylonMesh) {
  100018. previousNodeLOD._babylonMesh.dispose(false, true);
  100019. delete previousNodeLOD._babylonMesh;
  100020. }
  100021. }
  100022. if (indexLOD !== nodeLODs.length - 1) {
  100023. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  100024. if (_this._loadNodeSignals[nodeIndex]) {
  100025. _this._loadNodeSignals[nodeIndex].resolve();
  100026. delete _this._loadNodeSignals[nodeIndex];
  100027. }
  100028. }
  100029. });
  100030. if (indexLOD === 0) {
  100031. firstPromise = promise;
  100032. }
  100033. else {
  100034. _this._loader._completePromises.push(promise);
  100035. _this._loadingNodeLOD = null;
  100036. }
  100037. };
  100038. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  100039. _loop_1(indexLOD);
  100040. }
  100041. return firstPromise;
  100042. });
  100043. };
  100044. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  100045. var _this = this;
  100046. // Don't load material LODs if already loading a node LOD.
  100047. if (this._loadingNodeLOD) {
  100048. return null;
  100049. }
  100050. return this._loadExtensionAsync(context, material, function (context, extension) {
  100051. var firstPromise;
  100052. var materialLODs = _this._getLODs(context, material, _this._loader._gltf.materials, extension.ids);
  100053. var _loop_2 = function (indexLOD) {
  100054. var materialLOD = materialLODs[indexLOD];
  100055. if (indexLOD !== 0) {
  100056. _this._loadingMaterialLOD = materialLOD;
  100057. if (!_this._loadMaterialSignals[materialLOD._index]) {
  100058. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  100059. }
  100060. }
  100061. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh, babylonDrawMode, indexLOD === 0 ? assign : function () { }).then(function () {
  100062. if (indexLOD !== 0) {
  100063. var babylonDataLOD = materialLOD._babylonData;
  100064. assign(babylonDataLOD[babylonDrawMode].material);
  100065. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  100066. if (previousBabylonDataLOD[babylonDrawMode]) {
  100067. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  100068. delete previousBabylonDataLOD[babylonDrawMode];
  100069. }
  100070. }
  100071. if (indexLOD !== materialLODs.length - 1) {
  100072. var materialIndex = materialLODs[indexLOD + 1]._index;
  100073. if (_this._loadMaterialSignals[materialIndex]) {
  100074. _this._loadMaterialSignals[materialIndex].resolve();
  100075. delete _this._loadMaterialSignals[materialIndex];
  100076. }
  100077. }
  100078. });
  100079. if (indexLOD === 0) {
  100080. firstPromise = promise;
  100081. }
  100082. else {
  100083. _this._loader._completePromises.push(promise);
  100084. _this._loadingMaterialLOD = null;
  100085. }
  100086. };
  100087. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  100088. _loop_2(indexLOD);
  100089. }
  100090. return firstPromise;
  100091. });
  100092. };
  100093. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  100094. var _this = this;
  100095. // Defer the loading of uris if loading a material or node LOD.
  100096. if (this._loadingMaterialLOD) {
  100097. var index = this._loadingMaterialLOD._index;
  100098. return this._loadMaterialSignals[index].promise.then(function () {
  100099. return _this._loader._loadUriAsync(context, uri);
  100100. });
  100101. }
  100102. else if (this._loadingNodeLOD) {
  100103. var index = this._loadingNodeLOD._index;
  100104. return this._loadNodeSignals[index].promise.then(function () {
  100105. return _this._loader._loadUriAsync(context, uri);
  100106. });
  100107. }
  100108. return null;
  100109. };
  100110. /**
  100111. * Gets an array of LOD properties from lowest to highest.
  100112. */
  100113. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  100114. if (this.maxLODsToLoad <= 0) {
  100115. throw new Error("maxLODsToLoad must be greater than zero");
  100116. }
  100117. var properties = new Array();
  100118. for (var i = ids.length - 1; i >= 0; i--) {
  100119. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  100120. if (properties.length === this.maxLODsToLoad) {
  100121. return properties;
  100122. }
  100123. }
  100124. properties.push(property);
  100125. return properties;
  100126. };
  100127. return MSFT_lod;
  100128. }(GLTF2.GLTFLoaderExtension));
  100129. Extensions.MSFT_lod = MSFT_lod;
  100130. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  100131. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  100132. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  100133. })(BABYLON || (BABYLON = {}));
  100134. //# sourceMappingURL=MSFT_lod.js.map
  100135. "use strict";
  100136. var BABYLON;
  100137. (function (BABYLON) {
  100138. var GLTF2;
  100139. (function (GLTF2) {
  100140. var Extensions;
  100141. (function (Extensions) {
  100142. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  100143. var NAME = "KHR_draco_mesh_compression";
  100144. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  100145. __extends(KHR_draco_mesh_compression, _super);
  100146. function KHR_draco_mesh_compression(loader) {
  100147. var _this = _super.call(this, loader) || this;
  100148. _this.name = NAME;
  100149. _this._dracoCompression = null;
  100150. // Disable extension if decoder is not available.
  100151. if (!BABYLON.DracoCompression.DecoderUrl) {
  100152. _this.enabled = false;
  100153. }
  100154. return _this;
  100155. }
  100156. KHR_draco_mesh_compression.prototype.dispose = function () {
  100157. if (this._dracoCompression) {
  100158. this._dracoCompression.dispose();
  100159. }
  100160. _super.prototype.dispose.call(this);
  100161. };
  100162. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  100163. var _this = this;
  100164. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  100165. if (primitive.mode != undefined) {
  100166. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  100167. primitive.mode !== 4 /* TRIANGLES */) {
  100168. throw new Error(context + ": Unsupported mode " + primitive.mode);
  100169. }
  100170. // TODO: handle triangle strips
  100171. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  100172. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  100173. }
  100174. }
  100175. var attributes = {};
  100176. var loadAttribute = function (name, kind) {
  100177. var uniqueId = extension.attributes[name];
  100178. if (uniqueId == undefined) {
  100179. return;
  100180. }
  100181. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  100182. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  100183. babylonMesh._delayInfo.push(kind);
  100184. }
  100185. attributes[kind] = uniqueId;
  100186. };
  100187. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  100188. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  100189. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  100190. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  100191. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  100192. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  100193. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  100194. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  100195. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  100196. return _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  100197. try {
  100198. if (!_this._dracoCompression) {
  100199. _this._dracoCompression = new BABYLON.DracoCompression();
  100200. }
  100201. return _this._dracoCompression.decodeMeshAsync(data, attributes);
  100202. }
  100203. catch (e) {
  100204. throw new Error(context + ": " + e.message);
  100205. }
  100206. });
  100207. });
  100208. };
  100209. return KHR_draco_mesh_compression;
  100210. }(GLTF2.GLTFLoaderExtension));
  100211. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  100212. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  100213. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  100214. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  100215. })(BABYLON || (BABYLON = {}));
  100216. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  100217. "use strict";
  100218. var BABYLON;
  100219. (function (BABYLON) {
  100220. var GLTF2;
  100221. (function (GLTF2) {
  100222. var Extensions;
  100223. (function (Extensions) {
  100224. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  100225. var NAME = "KHR_materials_pbrSpecularGlossiness";
  100226. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  100227. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  100228. function KHR_materials_pbrSpecularGlossiness() {
  100229. var _this = _super !== null && _super.apply(this, arguments) || this;
  100230. _this.name = NAME;
  100231. return _this;
  100232. }
  100233. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  100234. var _this = this;
  100235. return this._loadExtensionAsync(context, material, function (context, extension) {
  100236. material._babylonData = material._babylonData || {};
  100237. var babylonData = material._babylonData[babylonDrawMode];
  100238. if (!babylonData) {
  100239. var promises = new Array();
  100240. var name_1 = material.name || "materialSG_" + material._index;
  100241. var babylonMaterial = _this._loader._createMaterial(BABYLON.PBRMaterial, name_1, babylonDrawMode);
  100242. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  100243. promises.push(_this._loadSpecularGlossinessPropertiesAsync(context, material, extension, babylonMaterial));
  100244. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  100245. babylonData = {
  100246. material: babylonMaterial,
  100247. meshes: [],
  100248. loaded: Promise.all(promises).then(function () { })
  100249. };
  100250. material._babylonData[babylonDrawMode] = babylonData;
  100251. }
  100252. babylonData.meshes.push(babylonMesh);
  100253. assign(babylonData.material);
  100254. return babylonData.loaded;
  100255. });
  100256. };
  100257. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  100258. var promises = new Array();
  100259. if (properties.diffuseFactor) {
  100260. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  100261. babylonMaterial.alpha = properties.diffuseFactor[3];
  100262. }
  100263. else {
  100264. babylonMaterial.albedoColor = BABYLON.Color3.White();
  100265. }
  100266. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  100267. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  100268. if (properties.diffuseTexture) {
  100269. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  100270. babylonMaterial.albedoTexture = texture;
  100271. }));
  100272. }
  100273. if (properties.specularGlossinessTexture) {
  100274. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  100275. babylonMaterial.reflectivityTexture = texture;
  100276. }));
  100277. babylonMaterial.reflectivityTexture.hasAlpha = true;
  100278. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  100279. }
  100280. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  100281. return Promise.all(promises).then(function () { });
  100282. };
  100283. return KHR_materials_pbrSpecularGlossiness;
  100284. }(GLTF2.GLTFLoaderExtension));
  100285. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  100286. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  100287. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  100288. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  100289. })(BABYLON || (BABYLON = {}));
  100290. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  100291. "use strict";
  100292. var BABYLON;
  100293. (function (BABYLON) {
  100294. var GLTF2;
  100295. (function (GLTF2) {
  100296. var Extensions;
  100297. (function (Extensions) {
  100298. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  100299. var NAME = "KHR_lights";
  100300. var LightType;
  100301. (function (LightType) {
  100302. LightType["AMBIENT"] = "ambient";
  100303. LightType["DIRECTIONAL"] = "directional";
  100304. LightType["POINT"] = "point";
  100305. LightType["SPOT"] = "spot";
  100306. })(LightType || (LightType = {}));
  100307. var KHR_lights = /** @class */ (function (_super) {
  100308. __extends(KHR_lights, _super);
  100309. function KHR_lights() {
  100310. var _this = _super !== null && _super.apply(this, arguments) || this;
  100311. _this.name = NAME;
  100312. return _this;
  100313. }
  100314. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  100315. var _this = this;
  100316. return this._loadExtensionAsync(context, scene, function (context, extension) {
  100317. var promise = _this._loader._loadSceneAsync(context, scene);
  100318. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  100319. if (light.type !== LightType.AMBIENT) {
  100320. throw new Error(context + ": Only ambient lights are allowed on a scene");
  100321. }
  100322. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  100323. return promise;
  100324. });
  100325. };
  100326. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  100327. var _this = this;
  100328. return this._loadExtensionAsync(context, node, function (context, extension) {
  100329. var promise = _this._loader._loadNodeAsync(context, node);
  100330. var babylonLight;
  100331. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  100332. var name = node._babylonMesh.name;
  100333. switch (light.type) {
  100334. case LightType.AMBIENT: {
  100335. throw new Error(context + ": Ambient lights are not allowed on a node");
  100336. }
  100337. case LightType.DIRECTIONAL: {
  100338. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  100339. break;
  100340. }
  100341. case LightType.POINT: {
  100342. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  100343. break;
  100344. }
  100345. case LightType.SPOT: {
  100346. var spotLight = light;
  100347. // TODO: support inner and outer cone angles
  100348. //const innerConeAngle = spotLight.innerConeAngle || 0;
  100349. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  100350. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  100351. break;
  100352. }
  100353. default: {
  100354. throw new Error(context + ": Invalid light type (" + light.type + ")");
  100355. }
  100356. }
  100357. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  100358. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  100359. babylonLight.parent = node._babylonMesh;
  100360. return promise;
  100361. });
  100362. };
  100363. Object.defineProperty(KHR_lights.prototype, "_lights", {
  100364. get: function () {
  100365. var extensions = this._loader._gltf.extensions;
  100366. if (!extensions || !extensions[this.name]) {
  100367. throw new Error("#/extensions: '" + this.name + "' not found");
  100368. }
  100369. var extension = extensions[this.name];
  100370. return extension.lights;
  100371. },
  100372. enumerable: true,
  100373. configurable: true
  100374. });
  100375. return KHR_lights;
  100376. }(GLTF2.GLTFLoaderExtension));
  100377. Extensions.KHR_lights = KHR_lights;
  100378. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  100379. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  100380. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  100381. })(BABYLON || (BABYLON = {}));
  100382. //# sourceMappingURL=KHR_lights.js.map
  100383. return BABYLON;
  100384. });
  100385. /***/ }),
  100386. /* 35 */
  100387. /***/ (function(module, exports, __webpack_require__) {
  100388. /*!
  100389. * PEP v0.4.3 | https://github.com/jquery/PEP
  100390. * Copyright jQuery Foundation and other contributors | http://jquery.org/license
  100391. */
  100392. !function(a,b){ true?module.exports=b():"function"==typeof define&&define.amd?define(b):a.PointerEventsPolyfill=b()}(this,function(){"use strict";function a(a,b){b=b||Object.create(null);var c=document.createEvent("Event");c.initEvent(a,b.bubbles||!1,b.cancelable||!1);
  100393. // define inherited MouseEvent properties
  100394. // skip bubbles and cancelable since they're set above in initEvent()
  100395. for(var d,e=2;e<m.length;e++)d=m[e],c[d]=b[d]||n[e];c.buttons=b.buttons||0;
  100396. // Spec requires that pointers without pressure specified use 0.5 for down
  100397. // state and 0 for up state.
  100398. var f=0;
  100399. // add x/y properties aliased to clientX/Y
  100400. // define the properties of the PointerEvent interface
  100401. return f=b.pressure&&c.buttons?b.pressure:c.buttons?.5:0,c.x=c.clientX,c.y=c.clientY,c.pointerId=b.pointerId||0,c.width=b.width||0,c.height=b.height||0,c.pressure=f,c.tiltX=b.tiltX||0,c.tiltY=b.tiltY||0,c.twist=b.twist||0,c.tangentialPressure=b.tangentialPressure||0,c.pointerType=b.pointerType||"",c.hwTimestamp=b.hwTimestamp||0,c.isPrimary=b.isPrimary||!1,c}function b(){this.array=[],this.size=0}function c(a,b,c,d){this.addCallback=a.bind(d),this.removeCallback=b.bind(d),this.changedCallback=c.bind(d),A&&(this.observer=new A(this.mutationWatcher.bind(this)))}function d(a){return"body /shadow-deep/ "+e(a)}function e(a){return'[touch-action="'+a+'"]'}function f(a){return"{ -ms-touch-action: "+a+"; touch-action: "+a+"; }"}function g(){if(F){D.forEach(function(a){String(a)===a?(E+=e(a)+f(a)+"\n",G&&(E+=d(a)+f(a)+"\n")):(E+=a.selectors.map(e)+f(a.rule)+"\n",G&&(E+=a.selectors.map(d)+f(a.rule)+"\n"))});var a=document.createElement("style");a.textContent=E,document.head.appendChild(a)}}function h(){
  100402. // only activate if this platform does not have pointer events
  100403. if(!window.PointerEvent){if(window.PointerEvent=a,window.navigator.msPointerEnabled){var b=window.navigator.msMaxTouchPoints;Object.defineProperty(window.navigator,"maxTouchPoints",{value:b,enumerable:!0}),u.registerSource("ms",_)}else Object.defineProperty(window.navigator,"maxTouchPoints",{value:0,enumerable:!0}),u.registerSource("mouse",N),void 0!==window.ontouchstart&&u.registerSource("touch",V);u.register(document)}}function i(a){if(!u.pointermap.has(a)){var b=new Error("InvalidPointerId");throw b.name="InvalidPointerId",b}}function j(a){for(var b=a.parentNode;b&&b!==a.ownerDocument;)b=b.parentNode;if(!b){var c=new Error("InvalidStateError");throw c.name="InvalidStateError",c}}function k(a){var b=u.pointermap.get(a);return 0!==b.buttons}function l(){window.Element&&!Element.prototype.setPointerCapture&&Object.defineProperties(Element.prototype,{setPointerCapture:{value:W},releasePointerCapture:{value:X},hasPointerCapture:{value:Y}})}/**
  100404. * This is the constructor for new PointerEvents.
  100405. *
  100406. * New Pointer Events must be given a type, and an optional dictionary of
  100407. * initialization properties.
  100408. *
  100409. * Due to certain platform requirements, events returned from the constructor
  100410. * identify as MouseEvents.
  100411. *
  100412. * @constructor
  100413. * @param {String} inType The type of the event to create.
  100414. * @param {Object} [inDict] An optional dictionary of initial event properties.
  100415. * @return {Event} A new PointerEvent of type `inType`, initialized with properties from `inDict`.
  100416. */
  100417. var m=["bubbles","cancelable","view","detail","screenX","screenY","clientX","clientY","ctrlKey","altKey","shiftKey","metaKey","button","relatedTarget","pageX","pageY"],n=[!1,!1,null,null,0,0,0,0,!1,!1,!1,!1,0,null,0,0],o=window.Map&&window.Map.prototype.forEach,p=o?Map:b;b.prototype={set:function(a,b){return void 0===b?this["delete"](a):(this.has(a)||this.size++,void(this.array[a]=b))},has:function(a){return void 0!==this.array[a]},"delete":function(a){this.has(a)&&(delete this.array[a],this.size--)},get:function(a){return this.array[a]},clear:function(){this.array.length=0,this.size=0},
  100418. // return value, key, map
  100419. forEach:function(a,b){return this.array.forEach(function(c,d){a.call(b,c,d,this)},this)}};var q=[
  100420. // MouseEvent
  100421. "bubbles","cancelable","view","detail","screenX","screenY","clientX","clientY","ctrlKey","altKey","shiftKey","metaKey","button","relatedTarget",
  100422. // DOM Level 3
  100423. "buttons",
  100424. // PointerEvent
  100425. "pointerId","width","height","pressure","tiltX","tiltY","pointerType","hwTimestamp","isPrimary",
  100426. // event instance
  100427. "type","target","currentTarget","which","pageX","pageY","timeStamp"],r=[
  100428. // MouseEvent
  100429. !1,!1,null,null,0,0,0,0,!1,!1,!1,!1,0,null,
  100430. // DOM Level 3
  100431. 0,
  100432. // PointerEvent
  100433. 0,0,0,0,0,0,"",0,!1,
  100434. // event instance
  100435. "",null,null,0,0,0,0],s={pointerover:1,pointerout:1,pointerenter:1,pointerleave:1},t="undefined"!=typeof SVGElementInstance,u={pointermap:new p,eventMap:Object.create(null),captureInfo:Object.create(null),
  100436. // Scope objects for native events.
  100437. // This exists for ease of testing.
  100438. eventSources:Object.create(null),eventSourceList:[],/**
  100439. * Add a new event source that will generate pointer events.
  100440. *
  100441. * `inSource` must contain an array of event names named `events`, and
  100442. * functions with the names specified in the `events` array.
  100443. * @param {string} name A name for the event source
  100444. * @param {Object} source A new source of platform events.
  100445. */
  100446. registerSource:function(a,b){var c=b,d=c.events;d&&(d.forEach(function(a){c[a]&&(this.eventMap[a]=c[a].bind(c))},this),this.eventSources[a]=c,this.eventSourceList.push(c))},register:function(a){for(var b,c=this.eventSourceList.length,d=0;d<c&&(b=this.eventSourceList[d]);d++)
  100447. // call eventsource register
  100448. b.register.call(b,a)},unregister:function(a){for(var b,c=this.eventSourceList.length,d=0;d<c&&(b=this.eventSourceList[d]);d++)
  100449. // call eventsource register
  100450. b.unregister.call(b,a)},contains:/*scope.external.contains || */function(a,b){try{return a.contains(b)}catch(c){
  100451. // most likely: https://bugzilla.mozilla.org/show_bug.cgi?id=208427
  100452. return!1}},
  100453. // EVENTS
  100454. down:function(a){a.bubbles=!0,this.fireEvent("pointerdown",a)},move:function(a){a.bubbles=!0,this.fireEvent("pointermove",a)},up:function(a){a.bubbles=!0,this.fireEvent("pointerup",a)},enter:function(a){a.bubbles=!1,this.fireEvent("pointerenter",a)},leave:function(a){a.bubbles=!1,this.fireEvent("pointerleave",a)},over:function(a){a.bubbles=!0,this.fireEvent("pointerover",a)},out:function(a){a.bubbles=!0,this.fireEvent("pointerout",a)},cancel:function(a){a.bubbles=!0,this.fireEvent("pointercancel",a)},leaveOut:function(a){this.out(a),this.propagate(a,this.leave,!1)},enterOver:function(a){this.over(a),this.propagate(a,this.enter,!0)},
  100455. // LISTENER LOGIC
  100456. eventHandler:function(a){
  100457. // This is used to prevent multiple dispatch of pointerevents from
  100458. // platform events. This can happen when two elements in different scopes
  100459. // are set up to create pointer events, which is relevant to Shadow DOM.
  100460. if(!a._handledByPE){var b=a.type,c=this.eventMap&&this.eventMap[b];c&&c(a),a._handledByPE=!0}},
  100461. // set up event listeners
  100462. listen:function(a,b){b.forEach(function(b){this.addEvent(a,b)},this)},
  100463. // remove event listeners
  100464. unlisten:function(a,b){b.forEach(function(b){this.removeEvent(a,b)},this)},addEvent:/*scope.external.addEvent || */function(a,b){a.addEventListener(b,this.boundHandler)},removeEvent:/*scope.external.removeEvent || */function(a,b){a.removeEventListener(b,this.boundHandler)},
  100465. // EVENT CREATION AND TRACKING
  100466. /**
  100467. * Creates a new Event of type `inType`, based on the information in
  100468. * `inEvent`.
  100469. *
  100470. * @param {string} inType A string representing the type of event to create
  100471. * @param {Event} inEvent A platform event with a target
  100472. * @return {Event} A PointerEvent of type `inType`
  100473. */
  100474. makeEvent:function(b,c){
  100475. // relatedTarget must be null if pointer is captured
  100476. this.captureInfo[c.pointerId]&&(c.relatedTarget=null);var d=new a(b,c);return c.preventDefault&&(d.preventDefault=c.preventDefault),d._target=d._target||c.target,d},
  100477. // make and dispatch an event in one call
  100478. fireEvent:function(a,b){var c=this.makeEvent(a,b);return this.dispatchEvent(c)},/**
  100479. * Returns a snapshot of inEvent, with writable properties.
  100480. *
  100481. * @param {Event} inEvent An event that contains properties to copy.
  100482. * @return {Object} An object containing shallow copies of `inEvent`'s
  100483. * properties.
  100484. */
  100485. cloneEvent:function(a){for(var b,c=Object.create(null),d=0;d<q.length;d++)b=q[d],c[b]=a[b]||r[d],
  100486. // Work around SVGInstanceElement shadow tree
  100487. // Return the <use> element that is represented by the instance for Safari, Chrome, IE.
  100488. // This is the behavior implemented by Firefox.
  100489. !t||"target"!==b&&"relatedTarget"!==b||c[b]instanceof SVGElementInstance&&(c[b]=c[b].correspondingUseElement);
  100490. // keep the semantics of preventDefault
  100491. return a.preventDefault&&(c.preventDefault=function(){a.preventDefault()}),c},getTarget:function(a){var b=this.captureInfo[a.pointerId];return b?a._target!==b&&a.type in s?void 0:b:a._target},propagate:function(a,b,c){
  100492. // Order of conditions due to document.contains() missing in IE.
  100493. for(var d=a.target,e=[];d!==document&&!d.contains(a.relatedTarget);)
  100494. // Touch: Do not propagate if node is detached.
  100495. if(e.push(d),d=d.parentNode,!d)return;c&&e.reverse(),e.forEach(function(c){a.target=c,b.call(this,a)},this)},setCapture:function(b,c,d){this.captureInfo[b]&&this.releaseCapture(b,d),this.captureInfo[b]=c,this.implicitRelease=this.releaseCapture.bind(this,b,d),document.addEventListener("pointerup",this.implicitRelease),document.addEventListener("pointercancel",this.implicitRelease);var e=new a("gotpointercapture");e.pointerId=b,e._target=c,d||this.asyncDispatchEvent(e)},releaseCapture:function(b,c){var d=this.captureInfo[b];if(d){this.captureInfo[b]=void 0,document.removeEventListener("pointerup",this.implicitRelease),document.removeEventListener("pointercancel",this.implicitRelease);var e=new a("lostpointercapture");e.pointerId=b,e._target=d,c||this.asyncDispatchEvent(e)}},/**
  100496. * Dispatches the event to its target.
  100497. *
  100498. * @param {Event} inEvent The event to be dispatched.
  100499. * @return {Boolean} True if an event handler returns true, false otherwise.
  100500. */
  100501. dispatchEvent:/*scope.external.dispatchEvent || */function(a){var b=this.getTarget(a);if(b)return b.dispatchEvent(a)},asyncDispatchEvent:function(a){requestAnimationFrame(this.dispatchEvent.bind(this,a))}};u.boundHandler=u.eventHandler.bind(u);var v={shadow:function(a){if(a)return a.shadowRoot||a.webkitShadowRoot},canTarget:function(a){return a&&Boolean(a.elementFromPoint)},targetingShadow:function(a){var b=this.shadow(a);if(this.canTarget(b))return b},olderShadow:function(a){var b=a.olderShadowRoot;if(!b){var c=a.querySelector("shadow");c&&(b=c.olderShadowRoot)}return b},allShadows:function(a){for(var b=[],c=this.shadow(a);c;)b.push(c),c=this.olderShadow(c);return b},searchRoot:function(a,b,c){if(a){var d,e,f=a.elementFromPoint(b,c);for(
  100502. // is element a shadow host?
  100503. e=this.targetingShadow(f);e;){if(
  100504. // find the the element inside the shadow root
  100505. d=e.elementFromPoint(b,c)){
  100506. // shadowed element may contain a shadow root
  100507. var g=this.targetingShadow(d);return this.searchRoot(g,b,c)||d}
  100508. // check for older shadows
  100509. e=this.olderShadow(e)}
  100510. // light dom element is the target
  100511. return f}},owner:function(a){
  100512. // walk up until you hit the shadow root or document
  100513. for(var b=a;b.parentNode;)b=b.parentNode;
  100514. // the owner element is expected to be a Document or ShadowRoot
  100515. return b.nodeType!==Node.DOCUMENT_NODE&&b.nodeType!==Node.DOCUMENT_FRAGMENT_NODE&&(b=document),b},findTarget:function(a){var b=a.clientX,c=a.clientY,d=this.owner(a.target);
  100516. // if x, y is not in this root, fall back to document search
  100517. return d.elementFromPoint(b,c)||(d=document),this.searchRoot(d,b,c)}},w=Array.prototype.forEach.call.bind(Array.prototype.forEach),x=Array.prototype.map.call.bind(Array.prototype.map),y=Array.prototype.slice.call.bind(Array.prototype.slice),z=Array.prototype.filter.call.bind(Array.prototype.filter),A=window.MutationObserver||window.WebKitMutationObserver,B="[touch-action]",C={subtree:!0,childList:!0,attributes:!0,attributeOldValue:!0,attributeFilter:["touch-action"]};c.prototype={watchSubtree:function(a){
  100518. // Only watch scopes that can target find, as these are top-level.
  100519. // Otherwise we can see duplicate additions and removals that add noise.
  100520. //
  100521. // TODO(dfreedman): For some instances with ShadowDOMPolyfill, we can see
  100522. // a removal without an insertion when a node is redistributed among
  100523. // shadows. Since it all ends up correct in the document, watching only
  100524. // the document will yield the correct mutations to watch.
  100525. this.observer&&v.canTarget(a)&&this.observer.observe(a,C)},enableOnSubtree:function(a){this.watchSubtree(a),a===document&&"complete"!==document.readyState?this.installOnLoad():this.installNewSubtree(a)},installNewSubtree:function(a){w(this.findElements(a),this.addElement,this)},findElements:function(a){return a.querySelectorAll?a.querySelectorAll(B):[]},removeElement:function(a){this.removeCallback(a)},addElement:function(a){this.addCallback(a)},elementChanged:function(a,b){this.changedCallback(a,b)},concatLists:function(a,b){return a.concat(y(b))},
  100526. // register all touch-action = none nodes on document load
  100527. installOnLoad:function(){document.addEventListener("readystatechange",function(){"complete"===document.readyState&&this.installNewSubtree(document)}.bind(this))},isElement:function(a){return a.nodeType===Node.ELEMENT_NODE},flattenMutationTree:function(a){
  100528. // find children with touch-action
  100529. var b=x(a,this.findElements,this);
  100530. // flatten the list
  100531. // make sure the added nodes are accounted for
  100532. return b.push(z(a,this.isElement)),b.reduce(this.concatLists,[])},mutationWatcher:function(a){a.forEach(this.mutationHandler,this)},mutationHandler:function(a){if("childList"===a.type){var b=this.flattenMutationTree(a.addedNodes);b.forEach(this.addElement,this);var c=this.flattenMutationTree(a.removedNodes);c.forEach(this.removeElement,this)}else"attributes"===a.type&&this.elementChanged(a.target,a.oldValue)}};var D=["none","auto","pan-x","pan-y",{rule:"pan-x pan-y",selectors:["pan-x pan-y","pan-y pan-x"]}],E="",F=window.PointerEvent||window.MSPointerEvent,G=!window.ShadowDOMPolyfill&&document.head.createShadowRoot,H=u.pointermap,I=25,J=[1,4,2,8,16],K=!1;try{K=1===new MouseEvent("test",{buttons:1}).buttons}catch(L){}
  100533. // handler block for native mouse events
  100534. var M,N={POINTER_ID:1,POINTER_TYPE:"mouse",events:["mousedown","mousemove","mouseup","mouseover","mouseout"],register:function(a){u.listen(a,this.events)},unregister:function(a){u.unlisten(a,this.events)},lastTouches:[],
  100535. // collide with the global mouse listener
  100536. isEventSimulatedFromTouch:function(a){for(var b,c=this.lastTouches,d=a.clientX,e=a.clientY,f=0,g=c.length;f<g&&(b=c[f]);f++){
  100537. // simulated mouse events will be swallowed near a primary touchend
  100538. var h=Math.abs(d-b.x),i=Math.abs(e-b.y);if(h<=I&&i<=I)return!0}},prepareEvent:function(a){var b=u.cloneEvent(a),c=b.preventDefault;return b.preventDefault=function(){a.preventDefault(),c()},b.pointerId=this.POINTER_ID,b.isPrimary=!0,b.pointerType=this.POINTER_TYPE,b},prepareButtonsForMove:function(a,b){var c=H.get(this.POINTER_ID);
  100539. // Update buttons state after possible out-of-document mouseup.
  100540. 0!==b.which&&c?a.buttons=c.buttons:a.buttons=0,b.buttons=a.buttons},mousedown:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=H.get(this.POINTER_ID),c=this.prepareEvent(a);K||(c.buttons=J[c.button],b&&(c.buttons|=b.buttons),a.buttons=c.buttons),H.set(this.POINTER_ID,a),b&&0!==b.buttons?u.move(c):u.down(c)}},mousemove:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=this.prepareEvent(a);K||this.prepareButtonsForMove(b,a),b.button=-1,H.set(this.POINTER_ID,a),u.move(b)}},mouseup:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=H.get(this.POINTER_ID),c=this.prepareEvent(a);if(!K){var d=J[c.button];
  100541. // Produces wrong state of buttons in Browsers without `buttons` support
  100542. // when a mouse button that was pressed outside the document is released
  100543. // inside and other buttons are still pressed down.
  100544. c.buttons=b?b.buttons&~d:0,a.buttons=c.buttons}H.set(this.POINTER_ID,a),
  100545. // Support: Firefox <=44 only
  100546. // FF Ubuntu includes the lifted button in the `buttons` property on
  100547. // mouseup.
  100548. // https://bugzilla.mozilla.org/show_bug.cgi?id=1223366
  100549. c.buttons&=~J[c.button],0===c.buttons?u.up(c):u.move(c)}},mouseover:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=this.prepareEvent(a);K||this.prepareButtonsForMove(b,a),b.button=-1,H.set(this.POINTER_ID,a),u.enterOver(b)}},mouseout:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=this.prepareEvent(a);K||this.prepareButtonsForMove(b,a),b.button=-1,u.leaveOut(b)}},cancel:function(a){var b=this.prepareEvent(a);u.cancel(b),this.deactivateMouse()},deactivateMouse:function(){H["delete"](this.POINTER_ID)}},O=u.captureInfo,P=v.findTarget.bind(v),Q=v.allShadows.bind(v),R=u.pointermap,S=2500,T=200,U="touch-action",V={events:["touchstart","touchmove","touchend","touchcancel"],register:function(a){M.enableOnSubtree(a)},unregister:function(){},elementAdded:function(a){var b=a.getAttribute(U),c=this.touchActionToScrollType(b);c&&(a._scrollType=c,u.listen(a,this.events),
  100550. // set touch-action on shadows as well
  100551. Q(a).forEach(function(a){a._scrollType=c,u.listen(a,this.events)},this))},elementRemoved:function(a){a._scrollType=void 0,u.unlisten(a,this.events),
  100552. // remove touch-action from shadow
  100553. Q(a).forEach(function(a){a._scrollType=void 0,u.unlisten(a,this.events)},this)},elementChanged:function(a,b){var c=a.getAttribute(U),d=this.touchActionToScrollType(c),e=this.touchActionToScrollType(b);
  100554. // simply update scrollType if listeners are already established
  100555. d&&e?(a._scrollType=d,Q(a).forEach(function(a){a._scrollType=d},this)):e?this.elementRemoved(a):d&&this.elementAdded(a)},scrollTypes:{EMITTER:"none",XSCROLLER:"pan-x",YSCROLLER:"pan-y",SCROLLER:/^(?:pan-x pan-y)|(?:pan-y pan-x)|auto$/},touchActionToScrollType:function(a){var b=a,c=this.scrollTypes;return"none"===b?"none":b===c.XSCROLLER?"X":b===c.YSCROLLER?"Y":c.SCROLLER.exec(b)?"XY":void 0},POINTER_TYPE:"touch",firstTouch:null,isPrimaryTouch:function(a){return this.firstTouch===a.identifier},setPrimaryTouch:function(a){
  100556. // set primary touch if there no pointers, or the only pointer is the mouse
  100557. (0===R.size||1===R.size&&R.has(1))&&(this.firstTouch=a.identifier,this.firstXY={X:a.clientX,Y:a.clientY},this.scrolling=!1,this.cancelResetClickCount())},removePrimaryPointer:function(a){a.isPrimary&&(this.firstTouch=null,this.firstXY=null,this.resetClickCount())},clickCount:0,resetId:null,resetClickCount:function(){var a=function(){this.clickCount=0,this.resetId=null}.bind(this);this.resetId=setTimeout(a,T)},cancelResetClickCount:function(){this.resetId&&clearTimeout(this.resetId)},typeToButtons:function(a){var b=0;return"touchstart"!==a&&"touchmove"!==a||(b=1),b},touchToPointer:function(a){var b=this.currentTouchEvent,c=u.cloneEvent(a),d=c.pointerId=a.identifier+2;c.target=O[d]||P(c),c.bubbles=!0,c.cancelable=!0,c.detail=this.clickCount,c.button=0,c.buttons=this.typeToButtons(b.type),c.width=2*(a.radiusX||a.webkitRadiusX||0),c.height=2*(a.radiusY||a.webkitRadiusY||0),c.pressure=a.force||a.webkitForce||.5,c.isPrimary=this.isPrimaryTouch(a),c.pointerType=this.POINTER_TYPE,
  100558. // forward modifier keys
  100559. c.altKey=b.altKey,c.ctrlKey=b.ctrlKey,c.metaKey=b.metaKey,c.shiftKey=b.shiftKey;
  100560. // forward touch preventDefaults
  100561. var e=this;return c.preventDefault=function(){e.scrolling=!1,e.firstXY=null,b.preventDefault()},c},processTouches:function(a,b){var c=a.changedTouches;this.currentTouchEvent=a;for(var d,e=0;e<c.length;e++)d=c[e],b.call(this,this.touchToPointer(d))},
  100562. // For single axis scrollers, determines whether the element should emit
  100563. // pointer events or behave as a scroller
  100564. shouldScroll:function(a){if(this.firstXY){var b,c=a.currentTarget._scrollType;if("none"===c)
  100565. // this element is a touch-action: none, should never scroll
  100566. b=!1;else if("XY"===c)
  100567. // this element should always scroll
  100568. b=!0;else{var d=a.changedTouches[0],e=c,f="Y"===c?"X":"Y",g=Math.abs(d["client"+e]-this.firstXY[e]),h=Math.abs(d["client"+f]-this.firstXY[f]);
  100569. // if delta in the scroll axis > delta other axis, scroll instead of
  100570. // making events
  100571. b=g>=h}return this.firstXY=null,b}},findTouch:function(a,b){for(var c,d=0,e=a.length;d<e&&(c=a[d]);d++)if(c.identifier===b)return!0},
  100572. // In some instances, a touchstart can happen without a touchend. This
  100573. // leaves the pointermap in a broken state.
  100574. // Therefore, on every touchstart, we remove the touches that did not fire a
  100575. // touchend event.
  100576. // To keep state globally consistent, we fire a
  100577. // pointercancel for this "abandoned" touch
  100578. vacuumTouches:function(a){var b=a.touches;
  100579. // pointermap.size should be < tl.length here, as the touchstart has not
  100580. // been processed yet.
  100581. if(R.size>=b.length){var c=[];R.forEach(function(a,d){
  100582. // Never remove pointerId == 1, which is mouse.
  100583. // Touch identifiers are 2 smaller than their pointerId, which is the
  100584. // index in pointermap.
  100585. if(1!==d&&!this.findTouch(b,d-2)){var e=a.out;c.push(e)}},this),c.forEach(this.cancelOut,this)}},touchstart:function(a){this.vacuumTouches(a),this.setPrimaryTouch(a.changedTouches[0]),this.dedupSynthMouse(a),this.scrolling||(this.clickCount++,this.processTouches(a,this.overDown))},overDown:function(a){R.set(a.pointerId,{target:a.target,out:a,outTarget:a.target}),u.enterOver(a),u.down(a)},touchmove:function(a){this.scrolling||(this.shouldScroll(a)?(this.scrolling=!0,this.touchcancel(a)):(a.preventDefault(),this.processTouches(a,this.moveOverOut)))},moveOverOut:function(a){var b=a,c=R.get(b.pointerId);
  100586. // a finger drifted off the screen, ignore it
  100587. if(c){var d=c.out,e=c.outTarget;u.move(b),d&&e!==b.target&&(d.relatedTarget=b.target,b.relatedTarget=e,
  100588. // recover from retargeting by shadow
  100589. d.target=e,b.target?(u.leaveOut(d),u.enterOver(b)):(
  100590. // clean up case when finger leaves the screen
  100591. b.target=e,b.relatedTarget=null,this.cancelOut(b))),c.out=b,c.outTarget=b.target}},touchend:function(a){this.dedupSynthMouse(a),this.processTouches(a,this.upOut)},upOut:function(a){this.scrolling||(u.up(a),u.leaveOut(a)),this.cleanUpPointer(a)},touchcancel:function(a){this.processTouches(a,this.cancelOut)},cancelOut:function(a){u.cancel(a),u.leaveOut(a),this.cleanUpPointer(a)},cleanUpPointer:function(a){R["delete"](a.pointerId),this.removePrimaryPointer(a)},
  100592. // prevent synth mouse events from creating pointer events
  100593. dedupSynthMouse:function(a){var b=N.lastTouches,c=a.changedTouches[0];
  100594. // only the primary finger will synth mouse events
  100595. if(this.isPrimaryTouch(c)){
  100596. // remember x/y of last touch
  100597. var d={x:c.clientX,y:c.clientY};b.push(d);var e=function(a,b){var c=a.indexOf(b);c>-1&&a.splice(c,1)}.bind(null,b,d);setTimeout(e,S)}}};M=new c(V.elementAdded,V.elementRemoved,V.elementChanged,V);var W,X,Y,Z=u.pointermap,$=window.MSPointerEvent&&"number"==typeof window.MSPointerEvent.MSPOINTER_TYPE_MOUSE,_={events:["MSPointerDown","MSPointerMove","MSPointerUp","MSPointerOut","MSPointerOver","MSPointerCancel","MSGotPointerCapture","MSLostPointerCapture"],register:function(a){u.listen(a,this.events)},unregister:function(a){u.unlisten(a,this.events)},POINTER_TYPES:["","unavailable","touch","pen","mouse"],prepareEvent:function(a){var b=a;return $&&(b=u.cloneEvent(a),b.pointerType=this.POINTER_TYPES[a.pointerType]),b},cleanup:function(a){Z["delete"](a)},MSPointerDown:function(a){Z.set(a.pointerId,a);var b=this.prepareEvent(a);u.down(b)},MSPointerMove:function(a){var b=this.prepareEvent(a);u.move(b)},MSPointerUp:function(a){var b=this.prepareEvent(a);u.up(b),this.cleanup(a.pointerId)},MSPointerOut:function(a){var b=this.prepareEvent(a);u.leaveOut(b)},MSPointerOver:function(a){var b=this.prepareEvent(a);u.enterOver(b)},MSPointerCancel:function(a){var b=this.prepareEvent(a);u.cancel(b),this.cleanup(a.pointerId)},MSLostPointerCapture:function(a){var b=u.makeEvent("lostpointercapture",a);u.dispatchEvent(b)},MSGotPointerCapture:function(a){var b=u.makeEvent("gotpointercapture",a);u.dispatchEvent(b)}},aa=window.navigator;aa.msPointerEnabled?(W=function(a){i(a),j(this),k(a)&&(u.setCapture(a,this,!0),this.msSetPointerCapture(a))},X=function(a){i(a),u.releaseCapture(a,!0),this.msReleasePointerCapture(a)}):(W=function(a){i(a),j(this),k(a)&&u.setCapture(a,this)},X=function(a){i(a),u.releaseCapture(a)}),Y=function(a){return!!u.captureInfo[a]},g(),h(),l();var ba={dispatcher:u,Installer:c,PointerEvent:a,PointerMap:p,targetFinding:v};return ba});
  100598. /***/ }),
  100599. /* 36 */
  100600. /***/ (function(module, exports, __webpack_require__) {
  100601. "use strict";
  100602. Object.defineProperty(exports, "__esModule", { value: true });
  100603. var defaultViewer_1 = __webpack_require__(5);
  100604. var mappers_1 = __webpack_require__(1);
  100605. function InitTags(selector) {
  100606. if (selector === void 0) { selector = 'babylon'; }
  100607. var elements = document.querySelectorAll(selector);
  100608. for (var i = 0; i < elements.length; ++i) {
  100609. var element = elements.item(i);
  100610. var configMapper = mappers_1.mapperManager.getMapper('dom');
  100611. var config = configMapper.map(element);
  100612. var viewer = new defaultViewer_1.DefaultViewer(element, config);
  100613. }
  100614. }
  100615. exports.InitTags = InitTags;
  100616. /***/ })
  100617. /******/ ]);
  100618. return BabylonViewer;
  100619. });